_id
int64
0
49
text
stringlengths
71
4.19k
0
How to create fog effect over specific tiles in dungeon game I'm working on a game in unity and I have areas the player cannot enter blocked off by game objects that are animated sprites that are supposed to look like fog. They don't look that great and I'd like to try something a little more complex, but as a beginner with Unity I don't know where to start. I'd like to make a fog effect that surrounds the tiles that are blocked (Similair to this asset I found. But I only want it to be seen over specific tiles.) I also looked into something like a darkness emitting light, but haven't found anything that works. Here is a picture of the scene hierarchy.
0
Calculating price increases in a virtual economy I'm trying to design a method to have price increase depending on the number of items bought from shops in my game. I'm fairly new to coding and I am struggling to figure out how to program the increase in price when buying multiple items. Currently the price increase is a percentage increase based on the quantity of items in store, however if I buy 5 items, all 5 items will be charged the same. How can I get it so each item is charged at a different price? I also need a reasonable inflation system, right now my code just determines a price increase based on the percentage of items remaining, but it's very simple and easy to exploit. It looks like this 30 2 28 1 (28 30) 0.07 0.93 1 0.07 1.07 10 1.07 10.7 Rounded up Price 11 I'd like to make this more complex also.
0
Avoiding overlapping UI Images When an enemy dies in my game, it drops an item on the ground. Enemies may drop multiple items. Currently, the item will always drop a set distance directly below the origin of the enemy when it dies. Therefore, if multiple items are dropped, I only see the most recently dropped item on the ground. Moreover, each item has a UI label clamped to some offset distance above the item. As such, I only see the UI label of the "most recently" dropped item. Because every item dropped by an enemy drops at the same physical location, and because I haven't added code to deal with this kind of thing, the physical game objects overlap with each other and the UI labels of those items overlap with each other. My question is pretty general. What are the best ways to modify my code such that 1) If multiple items are dropped, there will appear to be multiple game objects on the ground (Close enough to the origin)? 2) The UI labels attached to each item will appear as close as possible to that item without overlapping with the other items' UI labels? I would appreciate direct assistance or references that deal with this kind of thing. Thanks.
0
How to access random material in a renderer besides first without cloning any materials except accessed one? Clones only first material renderer.material Clones all materials in the same renderer renderer.materials 0
0
Is there a way to check if an object is currently colliding with anything? I need to test from another Script on a different GameObject, whether a particular GameObject is colliding with anything (in particular using trigger). So, for my purpose, I don't need OnCollisionEnter OnTriggerEnter events, but I need something like this if ( myObject.isOnCollision ) do something How can I do this?
0
Odd behavior in Unity 5.1 2d project prefabs I am very worried something is corrupt in my project. I am making a 2d top down rogue like and am currently using prefabs to generate enemies from. I have started running into an issue where I get a null reference error when trying to iterate a collection of enemies after doing anything on the prefabs, even just selecting one in the editor. If I drag any of the enemy prefabs into the scene then immediately delete it I am fine until I touch a prefab in the inspector again. at one point I was getting "iHasError" 6 times with no info but the unity reinstall fixed that so far I have tried Deleting the library folder Doing a Reimport All Uninstalling and reinstalling Unity Reloading the project from a few days ago Removed a bunch of animations added this weekend Commenting out everything I had done recently in the Enemy script Googled for a couple hours and looking for things that seem similar My prefab is structured Gameobject Sprite Renderer Enemy (Script) About 500 lines Animator (simple 2 sprite swap animation) Does anyone have any ideas? Mike B
0
How to 9 slice meshes? So let us assume I have a 3D model of a window and I would like to stretch it like a 9 sliced sprite. How would you go by doing 9 slice on meshes? All I found online was about quads. What about more complicated meshes?
0
How do I get light to go through a window texture in Unity? I'm having trouble with the lighting (I have windows and the light wont go through). How do I get the light to proceed through the glass?
0
Creating a static 2D background at runtime I'm using unity for a 2D game. We have a lot of props for grass, plants, flowers, etc that are static and always in the background. I'd like to optimize the background and reduce the drawcalls as much as possible by making a big image with the final result of the background. The idea would be to draw on a texture all the elements in the background, and then use this texture as the background. This way a single element has to be drawn. How can I create these background texture at runtime, so it is generated as soon as the scene is loaded?
0
Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?
0
Unable to add button in Unity I am wanting to add a button to my scene in order to mute unmute music. I can add the button to my scene, but it's not appearing on the UI. I can't see it anywhere, not on the scene nor the game when running. Below is a screenshot of the editor. You can see the button in front of the camera and in front of the scene itself, but it doesn't appear. I can't actually see a button, just a 'move' control'. Things I have tried Changing the 'Layer' of the button to default Adjusting the z axis (I've tried 0, 1 5, 1 5) Giving the Image (Script) a material inside the Inspector The button has text, which isn't visible either. I could create a sprite and do a raycast, but that seems like overkill just to do a simple click action. Any ideas?
0
Unity3d Detect a collision between an image and a sphere So, I just realized, an image with BoxCollider2D wont detect any collision with Sphere with SphereCollider. I tried adding a BoxCollider to my image, but it behaves in a weird manner (The Canvas position keeps shifting) So, I can see the only way for it to work is adding a 2D Collider to the sphere? Is there any other better way to solve it? Adding a 2D Collider to the sphere wont cover the whole area
0
How do I find the face of an object? I'm working on a build mode but the thing of it is the player is able to deform meshes. Part of my build system includes having "snap" points thus I need to be able to find the face and recenter the snap point on deformed meshes. So, how do I find the face of an object and the center of said face? Also how would I find the center? To clarify The end goal is to keep the snap point positioned properly with the face that has been deformed manipulated.
0
Unity, errors when using Quaternion.Euler to copy rotations In the game I'm creating I have a square that rotates around a parent point, I want the square to always aim upright however (think of a rotating platform). What I've done is simply use child.transform.rotation Quaternion.Euler(0.0f, 0.0f, gameObject.transform.rotation.z) This rotates the child object in the opposite direction so that they're always aiming in the right direction. Except it doesn't, there is some error that piles up with bigger rotations. For example at 90 the child object will be rotated 90.77 instead which is very noticeable given that the game has a grid of sorts and when objects are not aligned to it they instantly pop out. So my question is, is there any way to avoid this error?
0
Servers do not remove spawned prefab after disconnection I built a multiplayer game with the Unity UNET. For doing this I bought a VPS server. Everything works fine. But sometimes when players want to quit the game, the servers do not destroy him from the scene!!! amp the other players still can see him in the scene till the servers being restarted and ran again!! For quitting the game I wrote this code NetworkManagers.singleton.client.Disconnect() Destroy(NetworkManagers.singleton.gameObject) For more explanation, this is my ConnectionConfig for server amp client MinUpdateTimeout 15 ConnectTimeout 1200 DisconnectTimeout 2000 PingTimeout 500 NetworkDropThreshold 50 OverflowDropThreshold 50 AckDelay 32 AcksType 1 MaxSentMessageQueueSize 150 Why this happening?! Did I miss something?! amp how can I avoid that?!
0
How to create a 2d procedural spline based road with 2 edge colliders? I am trying to make a top down 2d spline based road that is procedurally generated and endless. The aim is that the player starts inside the road and has to navigate the road and if he touches any of its edges he quot dies quot and the game reloads. I have looked at various resources online for help but can't seem to find the answer. I have tried using the Path creator tool (by sebastian lague) and followed his YouTube series and I have even tried to use Unity's 2d sprite shape asset. The issue is, with the Path creator tool, I am able to create the road procedurally, but I can't figure out how to add multiple edge colliders on its boundaries. The same issue is there for Unity's sprite shape asset except with that, I don't know how to generate the road also (procedurally) and I can't find any tutorial or resource that explains how to do so. Can someone explain an easy way to achieve this (also, it has to be procedurally since my goal is to make it endless)?
0
Unexpected Behavior Calling method on MonoBehaviour before Start() is called I'm implementing object pooling, though that's not the issue, and a bit confused about the order of operations between Monobehaviours. In the InitGame() method of MyGameManager, I call SpawnEnemy() on the EnemyManager singleton. What I would expect to happen (but is not happening) is for the Awake() method in EnemyManager to be called, then the EnemyManager Start() method, and then and only then, would SpawnEnemy() be called. What actually happens is that EnemyManager Awake() is called, then MyGameManager calls SpawnEnemy(), and when that's done, EnemyManager's Start() method is called last. The docs say, Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. I'm guessing that while my EnemyManager is Active, it is not Enabled, and thus it's Start() method is not called until after the call to SpawnEnemy(). I found it surprising that a method can be called on an object before Start() is called on that object. I can work around this situation by simply including the line gameObject.SetActive(false) in my EnemyManager's Awake() method, and thus the SpawnEnemy() method will find and spawn an object from the pool, but it would be helpful to have a deeper understanding of when Start() is actually called. I've read the docs and whatever I could find, but don't feel like I fully understand. Here is the Manager Singleton designed to easily create XxxxManager classes using UnityEngine public class Manager lt T gt MonoBehaviour where T MonoBehaviour private static T sharedInstance null public static T sharedInstance get if ( sharedInstance null) sharedInstance Object.FindObjectOfType lt T gt () if ( sharedInstance null) Debug.Log("Can't find " typeof(T)) return sharedInstance public virtual void Awake() ... An EnemyManager class using System.Collections using System.Collections.Generic using UnityEngine public class EnemyManager Manager lt EnemyManager gt static private List lt EnemyManager gt enemyControllers public EnemyManager SpawnEnemy(Vector3 location) foreach (EnemyManager controller in enemyControllers) if (controller.gameObject.activeSelf false) controller.gameObject.transform.position location object available controller.gameObject.SetActive(true) return controller Debug.Log("Not enough enemies available in pool.") return null public override void Awake() if (enemyControllers null) enemyControllers new List lt EnemyManager gt () enemyControllers.Add(this) If we SetActive(false) here, we DO get the desired behavior gameObject.SetActive(false) lt base.Awake() protected void Start() wake up and disable self If we SetActive(false) here, we do NOT get the desired behavior gameObject.SetActive(false) lt And I'm using these classes in MyGameManager using System.Collections using System.Collections.Generic using UnityEngine public class MyGameManager Manager lt MyGameManager gt private EnemyManager enemyManager public override void Awake() enemyManager EnemyManager.sharedInstance base.Awake() private void Start() InitGame() void InitGame() enemyManager.SpawnEnemy(new Vector3(0, 0, 0))
0
Saving predesigned tilemap "rooms" and access them in script in Unity3D? I'm working on a top down rogue like in Unity3D, and I already have some kind of dungeon generation. The next feature I'd like to implement, is to predesign some kind of "event rooms" (i.e. boss fight rooms), so my algorithm could place them at random locations. Is there some kind of Unity feature for this, or I have to implement an editor script which could save and load tilemaps into and from scriptable objects?
0
Is there an established way to create a 2D XY NavMesh in Unity? Specifically, one in the empty space between colliders, rather than on an XZ plane (more or less) over the surface of a collider? Specifically this is because I have a drone, in a current project, which must follow a target. This target isn't always reachable by shortest path, and I'm currently experimenting with a number of algorithms to find a way to guide it around obstacles. I am on something of a deadline and would like to minimize my work, if I can. I recognize that there are cheats around this, like having it magically appear from off screen at a critical distance. I'm going to implement them in any case, but that's not what this question is about. Unity's NavMesh tools were initially alluring, but as far as I can tell they seem to require a very specific FPS like setup for this project, which I am in no way following. This feels unlike Unity Technologies, and particularly short sighted of them so before I go further, I would like to verify that I'm interpreting all of this correctly. For the sake of stability, I would like to avoid hack around solutions, if possible. All the same, they are welcome.
0
Finding x and z value in the direction of another object In my game you can drive a car and it has an arrow point to an object you need to drive towards. The arrow pops up above the car using the same x and z value as the car but adding 2 to the y value. What I am trying to do is push the arrow out a little bit toward the object it is pointing to. This way it looks like it is rotating in a circle around the car instead of rotating about it's own center point. This is what I am doing right now if (!(Vector3.Angle(car.transform.forward, obj.transform.position car.transform.position) lt 40f)) arrow.SetActive(true) temp car.transform.position temp.y car.transform.position.y 2f arrow.transform.position temp temp obj.transform.position temp.y arrow.transform.position.y arrow.transform.LookAt(temp)
0
Tile base Farm Simulation in Unity I am thinking of creating a sprite base 2d top down farm simulation game. The game uses tiles and I was wondering (conceptually) what is the best way to handle the farm tiles. Each tiles should have the following list of features. The player should be able to add seeds to each tile The player should be able to plant a variety of vegetables. Plants should have different stages of growth The player should be able to interact with each tile (dig, cover holes, water, add fertilizer, etc). The farm layout can have a variety of shapes (i.e. Not just a square (9 x 9) or rectangle (9 x 15) a shaped farm.) Currently I have a script that generates a square or rectangle shaped like farm, each tile is a sprite object with a 2D collider. I have come up with a solution for planting and the different stages of growth. However, it isn't the most elegant solution. My current solution is to create prefab for each plant. Then once a seed is planted onto a tile, create a plant object in the location of the tile (using it's vector position), and make the plant a child object to that tile. Each plant will have an age counter that increase when a new day is triggered. To show the growth stage swap the texture depending on the plant's age. My biggest problem with the implementation is that if the players farm is very large the game will have to create a hundreds object, which seem very taxing. Is that a different way achieve these features without the use of so many objects? If so, how would I implement it (conceptual of course). Thanks!
0
Screen transition effect like subway surfers I would like to know how can I achieve this kind of screen transition effect ? The effect is screen independent. https www.youtube.com watch?v Muh7QFisCfE t 01m57s
0
Clamping after forcing aspect ratio I'm using the following script to force aspect ratio of 16 9 https forum.unity.com threads force camera aspect ratio 16 9 in viewport.385541 It works perfectly. However now my game objects are allowed to move off the edges. The camera of the game is fixed, and never needs to move or scale. I have changed my code to WorldToViewportPoint for this but half my of character still goes off the edge. void Update() Vector3 pos cam.WorldToViewportPoint(transform.position) pos.x Mathf.Clamp01(pos.x) transform.position Camera.main.ViewportToWorldPoint(pos) private void FixedUpdate() Vector3 pos cam.ScreenToWorldPoint(Input.mousePosition) if (pos.x transform.position.x gt 0.5f) transform.eulerAngles new Vector2(0, 180) animateOgre(true) Vector2 move new Vector2(1, 0) rb.MovePosition((Vector2)transform.position (move speed Time.deltaTime)) else if (pos.x transform.position.x lt 0.5f) transform.eulerAngles new Vector2(0, 0) animateOgre(true) Vector2 move new Vector2( 1, 0) rb.MovePosition((Vector2)transform.position (move speed Time.deltaTime)) else animateOgre(false) My questions are How do I allow the whole character to stay within the Viewport? How can I clamp within the fixed update method rather than making a seperate update method. Is there anyway to prevent character from moving when the mouse is aligned up with the position of the character. Right now I'm using a hacky solution to find if the x difference is 0.5. (If i don't do this the character just moves back and forth when mouse stops)
0
Detect when an Oculus headset is stationary idle using transform.hasChanged I want to know how can I change in unity the thershold of the method below transform.haschanged At the moment it is so sensitive and it triggers with 0.00001 change in the camera. We have created an Interactive VR video in unity and we want that everytime the user doesnt use the oculus for 30 seconds, a trailer video starts to play! We have created the code below but even when the oculus is on the ground, still moves a bit (too sensitive) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Video public class Trailer MonoBehaviour public int timeOut private int timeOutTimer 0 private Quaternion gameObjectrotation private VideoPlayer videoPlayer public float dynamicRange 100f Use this for initialization public void Awake() Vector3 lastPos videoPlayer GetComponentInParent lt VideoPlayer gt () gameObjectrotation Camera.main.gameObject.transform.rotation InvokeRepeating("ScreenSaver", 0, 1.0f) public void ScreenSaver() timeOutTimer var wMinus gameObjectrotation.w dynamicRange var wPlus gameObjectrotation.w dynamicRange var xMinus gameObjectrotation.x dynamicRange var xPlus gameObjectrotation.x dynamicRange var yMinus gameObjectrotation.y dynamicRange var yPlus gameObjectrotation.y dynamicRange var zMinus gameObjectrotation.z dynamicRange var zPlus gameObjectrotation.z dynamicRange var cameraW Camera.main.gameObject.transform.rotation.w var cameraX Camera.main.gameObject.transform.rotation.x var cameraY Camera.main.gameObject.transform.rotation.y var cameraZ Camera.main.gameObject.transform.rotation.z if (cameraW gt wMinus amp amp cameraW lt wPlus amp amp cameraX gt xMinus amp amp cameraX lt xPlus amp amp cameraY gt yMinus amp amp cameraY lt yPlus amp amp cameraZ gt zMinus amp amp cameraZ lt zPlus amp amp timeOutTimer gt timeOut) Show video videoPlayer.gameObject.SetActive(true) videoPlayer.Play() else Hide Video videoPlayer.gameObject.SetActive(false) videoPlayer.Stop() videoPlayer.frame 1 if (cameraW gt wPlus cameraW lt wMinus cameraX gt xPlus cameraX lt xMinus cameraY gt yPlus cameraY lt yMinus cameraZ gt zPlus cameraZ lt zMinus) timeOutTimer 0 gameObjectrotation Camera.main.gameObject.transform.rotation Any help would be appreciated! Cheers
0
Unity Change Sceneview to camera view On selecting camera, I get the camera preview. In Unity, while editing the scene, I wish to switch in such a perspective view that is exactly visible by the main camera. Is there a short cut to change the view?
0
Why is this Mono Behavior in the animator? I'm looking through the 3D Game Kit from the asset store to accustom myself with the animator, and I'm just wondering what this is referring to. I was looking into controlling MonoBehaviors through the animation controller the other day and thought I had come to the conclusion that it couldn't be done directly, so what's this?
0
When to use a blend tree vs state machine for animation Im an experienced game dev hobbiest making my first game with 3d animated characters (in Unity) and am struggling to figure out when to use blend trees vs animation state machines. I understand both conceptually but have seen both blend trees and animation state machines used for character animation in a bunch of tutorials both from Unity and from other sources. I am not sure when why one is better than the other am hoping someone can point me in the right direction. My game is a 3rd person action rpg a'la WoW or KOTOR or Mass Effect (different systems I know but the perspectives and combat styles are kinda close at a high level). I have tons and tons of animations for attacks, blocks, feigns, deaths, walking, running, jumping, shooting etc but I am unclear on how to sequence them together naturally. I have seen blend trees used for locomotion which makes sense to me when trying to keep character motion fluid, but I dont understand how to go from that blend tree to an attack state and nothing I have seen so far has gone past locomotion (no attacks etc). Do I need to make blend trees from my motion states to attack death dodge states? Do I have more control using just state machines? Im a little cautious of state machines because of the transition bloat that is so common with them and because I suspect there is greater potential for janky animation sequencing without blending. I am planning to use the Unity character controller and write my own logic scripts to drive it. For the AI I will be using the built in nav mesh agents. Are character controller animations handled differently than the AI ones? Any insights would be more than welcome! Thanks
0
Rolling on collision I'm having a small issue where if I collide with another object (let's use a simple cube) with my player (this player is just a sphere), the ball will infinitely roll in the opposite direction and WILL NOT STOP. my code is as follows using UnityEngine public class PlayerController MonoBehaviour private Rigidbody rb private float moveHorizontal private float moveVertical public float moveSpeed Start is called before the first frame update private void Awake() rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() moveHorizontal Input.GetAxis("Horizontal") moveVertical Input.GetAxis("Vertical") private void FixedUpdate() MovePlayer() private void MovePlayer() Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement moveSpeed) I even changed the ForceMode to ForceMode.Impulse so be able to see what it was doing a little easier, and it is in fact slowly rolling away infinitely with no way to stop it. Both objects have a Rigidbody for them to be able to react to being hit. This is my first time messing with 3d. I tried to do something like this to make it not roll away on impact private void OnCollisionExit(Collision collision) if (collision.collider.gameObject.layer ! LayerMask.NameToLayer("Ground")) rb.velocity Vector3.zero But then if I want to jump on the cube (lets say the cube is an enemy and I'm jumping on it to kill it), then it acts very wonky each time it touches the edge of the cube and I haven't made it on top (again, because the velocity is being set to zero). I am all out of ideas and would love some input here! EDIT I now realize that the ball will slowly roll forever even without collision and just simply moving. I am very lost !
0
Why are my records duplicated when writing them to a file? I am writing data to a file every two seconds. I used InvokeRepeating and everything is Ok except that every record is saved 3 times in the file void Start() File.WriteAllText(filePath users, "timestamp" "," "id" "," "pos" "," "rot" System.Environment.NewLine) InvokeRepeating("SaveUsersTracking", 1.0f, 2.0f) void SaveUsersTracking() save this data every two seconds... File.AppendAllText(filePath users, System.DateTime.Now.ToString() "," "U1" "," "( 2.7, 1.3, 1.8)" "," "(0.2, 0.7, 0.2)" System.Environment.NewLine) My results look like timestamp,id,pos,rot 4 20 2019 8 09 47 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) 4 20 2019 8 09 47 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 47 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 49 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) 4 20 2019 8 09 49 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 49 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 51 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) 4 20 2019 8 09 51 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 51 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record
0
Prevent keyframe interpolation in imported model animation in Unity I made first person model in blender. It also has animations in it. Most of animation works fine, but in some cases, Unity's keyframe interpolation makes wrong result. Note that animation was made by 60 frames per second in Blender. To explain my problem, you have to see my model As you can see there are two magazines. Each named Mag1 and Mag2 and Mag1 is the magazine that attached to the gun. Mag2 is always located very bottom of the screen so that it is impossible to see, except reloading animation. While reloading, first pull out the mag1 from the gun and put in the mag2 to the gun. And here is the trick, after mag2 is attached to a gun, hand put the mag1 somewhere, maybe magazine pouch. Anyway as soon as mag1 disappeared from the screen, it switches mag1 and mag2 immediately at only single frame. So mag1 is now move back to the gun and mag2 is also reloated to bottom. In Blender, it seems nothing wrong but in Unity is quite different. As soon as mag1 disappeared, it doesn't switched immediately and it moves smoothly animated so I can see that magazines were moved. I'm pretty sure that this happens maybe Unity interpolates keyframes. I already turned off Animation Compression option and resample curves, but still won't worked. This is the video that I made to explain my situation https www.youtube.com watch?v 7aew959ejL4 amp feature youtu.be Is there a way to "turn off" that interpolation? I want to disable it only that frame. Unity doesn't allow me to edit animation clip, so I just duplicate animation clip and change the option(I don't know what it called) to "Flat" and use that clip instead, but still have same problem. (Note that it wasn't easy because Unity doesn't show me the animation if I duplicate and modify it) I struggled this issue almost a year and still figuring out how to fix it, and I think it's time to solve it. Any advice will very appreciate it.
0
How can I change a variable value in specific time duration according to animation clip time length? I will change my question with more details to make it more clear In the Assets I created Animator Controller and Animation Named them both FPSController. FPSController is the object I want to animate it's rotation on the Z from 50 to 0 Then I opened the Animator window and dragged the Animation into the Animator window Then I opened the Animation window and recorded the clip The rotation on Z is going from 50 to 0 in 7 seconds. I'm rotating the FPSController on the Z from 50 to 0 This is the Animation part and this is working fine. The FPSController(player) is starting when the Z rotation value is at 50 and slowly move to 0. Now The game is start when the whole camera is blurry. For this I'm using Post Processing. Next step was to create a profile of the Post Processing called it CC and this profile I dragged in the Hierarchy to the FPSCamera In the FPSCamera I dragged to it a script name Post Processing Behaviour and then dragged to the script in the Inspector the CC profile This way the Post Processing effects affecting the camera view So to make it clear I'm rotating on the Z the FPSController by animation. And on the FPSCamera I'm using the Post Processing for making effects. This is how the game start. This is the game view screenshot. The game start when everything is blurry and the FPSController(player) is rotating to the right by 50 degrees Now the part of the animation of rotating the FPSController by 50 is working fine. While it's rotating the FPSController I want slowly by the same time in this case 7 seconds to change the blurry effect and make the picture clear once the animation end. The property of the Post Processing CC profile I need to change is the focalLength. By default I start it with the value of 300. And I need in 7 seconds to change it from 300 to 0. This is the script I ended with so far The script is attached to the FPSCamera using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DOFControl MonoBehaviour public PostProcessingProfile postProcProf public Animator anim private float clipLength private void Start() AnimationClip clips anim.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length InvokeRepeating("incrementSpeed", 300, 0.1f) void incrementSpeed() var dof postProcProf.depthOfField.settings dof.focalLength 1f postProcProf.depthOfField.settings dof I'm getting the animation clip time length 7 seconds. But the part with the InvokeRepeating is not working. I want to incrementSpeed the focalLength down from 300 to 0 by 7 seconds. Not sure if using InvokeRepeating is the right way at all.
0
Getting position of a coordinate on the surface of a sphere So I want to create a object B close to another object A, but I'm trying to avoid that A covers B I have thinking how to achieve that. Take a look of the following drawing I have been thinking in a solution in a math geometry way before searching for some Unity3D function to solve the problem. I have realise A and B would be on the same surface if the camera is within a sphere with radius c A. So I guess the solution can be related to get a point at a B at a distance A B from A on the surface of the sphere with radius c A. Does it has sense? Any other idea? How to do it with maths and Unity?
0
A coroutine to rotate one point around another by a given angle without referring to game object I need to rotate a point around another point (in 2D) by a given angle over a given duration, independent of game object (meaning that I've manually created the points and they're not positions from a game objects transform ) as shown in the image below where point B rotates to C by and angle e around A by with radius AB. Using a coroutine would be preferable. UPDATE Based on links provided by MichaelHouse I wrote the following methods to rotate a control point over time by a certain angle but it rather moves to a point (which is not the desired point) immediately to another point, not by the right angle. I'm not sure what I've done wrong. public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle) return angle (point pivot) pivot IEnumerator RotateControlPointWithDuration(Vector3 point, Vector3 pivot, float duration, float angle) float currentTime 0.0f float ourTimeDelta 0 ourTimeDelta Time.deltaTime float angleDelta angle duration how many degress to rotate in one second while (currentTime lt duration) currentTime Time.deltaTime ourTimeDelta Time.deltaTime Vector3 newPos RotatePointAroundPivot(point, pivot, Quaternion.Euler(0, 0, angleDelta ourTimeDelta)) points 0 new Vector2(newPos.x, newPos.y) yield return null IEnumerator runMovement() yield return new WaitForSeconds(2.0f) Vector3 point new Vector3(points 0 .x, points 0 .y, 0) Vector3 pivot new Vector3(points 3 .x, points 3 .y, 0) StartCoroutine(RotateControlPointWithDuration(point, pivot, 2.0f, 45.0f)) UPDATE 2 I've tried another approach using trig functions, but the point moves erratically before finally arriving at a point that seems to be the right point. Please see the code below IEnumerator runMovement() yield return new WaitForSeconds(2.0f) Vector2 pivot points 3 StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f)) IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle) float currentTime 0.0f float ourTimeDelta 0 Vector2 startPos points 0 ourTimeDelta Time.deltaTime float angleDelta angle duration how many degress to rotate in one second while (currentTime lt duration) currentTime Time.deltaTime ourTimeDelta Time.deltaTime points 0 new Vector2(Mathf.Cos(angleDelta ourTimeDelta) (startPos.x pivot.x) Mathf.Sin(angleDelta ourTimeDelta) (startPos.y pivot.y) pivot.x, Mathf.Sin(angleDelta ourTimeDelta) (startPos.x pivot.x) Mathf.Cos(angleDelta ourTimeDelta) (startPos.y pivot.y) pivot.y) yield return null
0
How to detect collision position and that position's texture color in Unity? I have a prefab and I use Circlecollider2D for physics operations. I want to detect the color of the contact position of the collided objects ? Is is possible by using Unity's collider classes ?
0
Difference between unity scripting backend IL2CPP and Mono2x IL2CPP is a Unity developed scripting back end which you can use as an alternative to Mono when building projects for some platforms. Note IL2CPP is only available when building for the following platforms Android AppleTV, iOS , Nintendo 3DS, Nintendo Switch, Playstation 4 Playstation Vita, WebGL ,Windows Store, Xbox One I have a project(unity 5.2) which has switched for Android deployment. I tried to switch my scripting backed from Mono2x to IL2CPP and its showing me that IL2CPP on Andriod is experimental and unsupported So, my simple question is that if it is still not supported then why the option has included, what is the fundamental difference between IL2CPP and Mono2x. Why I switched to IL2CPP scripting backend ? what are its pros and cons? I have also checked in unity 5.5.2 there is not IL2CPP option in windows platform deployment.
0
just download first assetbundle In the Start of my scenes I call the method that downloads the assetBundles for that scene. The problem is that it only downloads the first assetBundle from the list, the second does not download it. My code is Note The Debug that shows the url shows the correct url both times, first http mihost.com assetbundles asset1 and then http mihost.com assetbundles asset2. However, in the Debug that shows the assets 'added' in both cases it shows the name only of those in asset1 public virtual IEnumerator LoadBundleFromServer() var AssetPathOnServer "http mihost.com assetbundles " var assetBundleNames new List lt string gt () assetBundleNames.Add("asset1") assetBundleNames.Add("asset2") for (int i 0 i lt assetBundleNames.Count i ) var currentAssetBundleName assetBundleNames i var url AssetPathOnServer currentAssetBundleName Debug.Log("url " url) var request UnityWebRequestAssetBundle.GetAssetBundle(url) yield return request.SendWebRequest() if (!request.isHttpError amp amp !request.isNetworkError) var asseBundle DownloadHandlerAssetBundle.GetContent(request,) Debug.Log("count assets " AssetNames.Count) for (int j 0 j lt AssetNames.Count j ) string assetName AssetNames j AssetBundleRequest asset asseBundle.LoadAssetAsync lt AudioClip gt (assetName) yield return asset AudioClip myClip asset.asset as AudioClip if (!assetDictionary.ContainsKey(assetName)) assetDictionary.Add(assetName, myClip) Debug.Log("added " assetName) asseBundle.Unload(false) else TODO aqui hay que mostrar un error Debug.LogErrorFormat("error request 0 , 1 ", url, request.error) public abstract List lt string gt AssetNames get
0
AudioClip is empty saving recording from Microphone EDIT I updated the code to what I have currently. I'm not sure why but, the editor and my platform complained when I put the WWW in a co routine, it seems to load the audio clips to the object but I cannot play them. In a script attached to the object I wait until the Audio Clip is loaded before I try to play it. So I am trying to record some Audio through the microphone and then save an AudioClip to the disk as a .wav file and also save the filepath as a playerpref and then later I can come back and load the string into a url but, for some reason the Audio Clip doesn't get loaded properly as I can see that there is an audio clip on my audio source in runtime but, it has no name and it has no sound on it. However, when I press play in the inspector I can hear my sound I am using SavWav.cs to save my audio clips to .wav files. Here is the url(filepath) I am sending to my load method string filename string.Format( "CapturedAudio 0 n.wav", Time.time) string filepath Path.Combine(Application.dataPath, filename) Here is the method I am using to get the AudioClip private void SpawnObject(string savedNames, Vector3 savedPositions, Quaternion savedRotations) GameObject cubeToSpawn Instantiate(cube, savedPositions, savedRotations) WWW www new WWW("file " savedNames) cubeToSpawn.GetComponent lt AudioSource gt ().clip www.GetAudioClip(false, false, AudioType.WAV) The obj is just a cube with an AudioSource attached to it that I instantiate prior to calling this method above. The filepath works fine for saving but, for some reason it doesn't want to load the audio clip. Any help would be greatly appreciated.
0
Unity, Pixel Perfect and Scaling I am totally stuck on with pixel perfectness of the game. I have tried a few pixel perfect camera assets, but they have lots of issues considering scalability. is it normal that these cameras zoom in and out, instead of scaling the camera screen when using different resolutions for the game. Because this is a huge problem for me, cause i need to make a game for aspect ratio of 16 10, and every resolution that has the same aspect ratio is needed to scale it correctly keeping the pixel perfectness. The ortographic camera size is dependent of screen width (width PPU 2) So it always zooms in or out with different resolutions. Question is Is there a way to make it scale the game sprites instead of zooming the view?
0
Creating placement grid in Unity I'm fairly new to C and Unity, so I don't really know much about it. I want to create an RTS like game where you have a huge grid that the whole world is placed on. Then you can place houses, walls etc on the tiles just like a lot other RTS games (i.e. Age of Empires, Stronghold Series etc). How would I go about this in Unity? I could imagine having some Terrain World manager that handles all the models and objects that you can interact with etc. And probably a lot of prefabs too with the different items, soldiers and so. So if anyone have any smart way of doing this or maybe a link to a tutorial explaining, then the help would be greatly appreciated.
0
Is there a way to hardcode a JSON file into a Unity build? I'm currently creating an external tool to generate dialogues that are exported as JSON files. The idea is that after you create a dialogue (as a JSON), my main Unity project reads that file and generates a dialogue. Right now it works just fine, but the JSON is an external file that you can modify even after compiling the game (of course). Is there a way to actually "hardcode" that JSON file so that the game doesn't need to find and read the file every single time it plays?
0
Iterating through all animator layers in Unity Mecanim I'm aware of how SetAnimatorLayerWeight works, I'm looking for a way to iterate through all layers of my controller at runtime. I've four layers and expect more, and need to update them at once, in essence, what I'm trying to do is something like this. To clarify The code below is boilerplate of what I'm trying to do. void SetCurrentWeaponLayerWeight(int index) animator.SetLayerWeight(index, 1) foreach(AnimatorLayer l in Animator.Layers) if (l.index ! index) animator.SetLayerWeight(l.index, 0)
0
How can I get my player's character to slide along a rail? I am creating a snowboarding game and would like my player to be able to jump on a rail and move along it if it lands on it. I have no idea how to approach this. I have already tried using ray casts and waypoints but nothing works. I need to make sure the player moves along the rail, from any point that the player jumps onto it e.g. if they land in the middle of the rail they keep following its curve from that point. The rails are not straight and have curves on them. How can I get my player to be able to jump on a curved rail like this, and start sliding from the point they jumped onto it?
0
How to rotate a 3D character on top of a plane with an isometric picture on it How to calculate the angles of the 3d charater so that it fits into the isometric environment projektet on a 2d plane? Also, how do you calculate the rotation of my character? What I want to achieve Describing the scenario
0
Unity crashes if there are more than 4 terrains please can you help me with the issue that I face, that is, I decided to create open world game by creating several terrains and connect them together in Unity and firstly respective size of the terrains was 500X500 then I decided to add more terrains to make game world bigger and once I added the 5th terrain in the scene, Unity simply crashed. Later, I thought what if I increase the sizes of terrains rather than create more new terrains then the sizes of originally created terrains were changed from 500X500 to 800X800 and again Unity crashed. Please guys help me out with that and how to overcome that and I am just trying to create game without using any ready plugins and, say, try to create the game on my own. Thank you for your attention))).
0
Why do I get this warning when using a null conditional operator? In the OnTriggerEnter2D function of my Bullet script, I have the following code private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag("Enemy")) var enemy other.GetComponent lt Enemy gt () enemy?.Death() The reason for the null conditional operator (the question mark) in enemy?.Death() is because the Death function actually destroys the Enemy component script, so it suppresses an error when the bullet hits the enemy again. It's supposed to be shorthand for if (enemy ! null) enemy.Death() The code works the error is suppressed. However, the IDE that I'm using, Jetbeans Rider, gives the following warning '?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity object. What does that mean exactly? Should I continue using the null conditional operator?
0
How to create button prompts for interactable objects in Unity? I have a class of objects tagged as interactables that my player can interact with when within range. When my player is near them, I want to display a button prompt at the bottom of the screen, along with a description of the type of interaction possible (for example, "inspect", "use", etc.). I want to account for the possibility that the player might be within range of two or more of them at once, and thus allow him to toggle through them, displaying their button prompts in turn. If my player interacts with something which generates a text box or other modal, I want the button prompt to disappear, but to return when the text box or modal is closed. Any advice on how to go about achieving this? I've done it in the past in different engines, but I have always been unhappy with how convoluted my method was. I'd like to hear how others might tackle this. Given how common this kind of thing is in games, I'm surprised I haven't found a good tutorial on it yet. You can be as general or as specific as you'd like in your answer.
0
How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?
0
how to prevent call on OnValidate() when running game I need OnValidate() to be called only when I am designing my level (placing game objects at their respective positions and setting properties before running the project). But I don't want it to be called when I run the project. I can manually comment it out, but that will take a lot of time, since I have several OnValidate() calls. How can this be done, if it is possible?
0
Open website URL from image marker using ARCore in Unity How can I open a website URL from an image marker using ARCore in Unity? I am trying to build an AR app using ARCore in Unity. I have ten images and ten url links to websites, I need to link the ten images with those ten url links. When I scan the image with the phone's camera, I want the URL to open directly. I've done image tracking with video before, but now I want to do image tracking linking to a URL.
0
Terrain Navmesh build, rebuild smaller pieces of the bigger navmesh terrain. UNITY when the area is very big and AI characters are required to walk a larger distance, it would be beneficial to have the large navmesh ready for finding a path. when we change the height of the terrain in runtime small areas of the terrain should be updated. so the buildnavmesh method is kind of an overkill. and the localnavmesh builder as a large type would be inefficient. how do we dynamically change a small part of a larger navmesh? advice or help would be highly appreciated.
0
Panning value of 2nd GameObject's AudioSource is not initializing I'm making a prototype and stuck in a problem where two GameObjects swap but there values of panStereo of AudioSource is not initializing from a float array which contains all the default values of panStereo of all the GameObjects in a scene panningArray new float Inventory.bowlsManager.BowlPanningValues.Length for (int i 0 i lt Inventory.bowlsManager.BowlPanningValues.Length i ) panningArray i Inventory.bowlsManager.BowlPanningValues i Selectable false SelectedBowl.GetComponent lt AudioSource gt ().spatialBlend SelectedBowl2.GetComponent lt AudioSource gt ().spatialBlend 1 iTween.MoveTo(SelectedBowl, iTween.Hash( quot position quot , temp2, quot time quot , transitionspeed)) iTween.MoveTo(SelectedBowl2, iTween.Hash( quot position quot , temp, quot time quot , transitionspeed)) SelectedBowl.GetComponent lt Renderer gt ().material SubsituteMaterial SelectedBowl2.GetComponent lt Renderer gt ().material SubsituteMaterial int SelectedBowlIndex Array.FindIndex(Inventory.allBowls.ToArray(), x gt x SelectedBowl.GetComponent lt Bowl gt ()) int SelectedBowlIndex2 Array.FindIndex(Inventory.allBowls.ToArray(), x gt x SelectedBowl2.GetComponent lt Bowl gt ()) print(Inventory.bowlsManager.BowlPanningValues SelectedBowlIndex2 ) print(Inventory.bowlsManager.BowlPanningValues SelectedBowlIndex ) val1 BowlPanning(SelectedBowl2 , panningArray SelectedBowlIndex ) val2 BowlPanning(SelectedBowl , panningArray SelectedBowlIndex2 ) Here is my bowl panning function public float BowlPanning(GameObject BowlRequire,float value) BowlRequire.GetComponent lt AudioSource gt ().panStereo value return BowlRequire.GetComponent lt AudioSource gt ().panStereo
0
How to get dynamic RigidBody rotation tilt on uneven platform? I have a rigid body with PolygonCollider2D which has some complex circular shape and I'm using uneven platform. Im using Following code to move the object forward CharacterRigidBody.velocity new Vector2 (speed, CharacterRigidBody.velocity.y) Problem The rigid body keeps on rotating when it moves forward. I want the character to move without rotation on asymmetrical platform(above).But i don't want to freeze rotation because i want the character to tilt when climbing or decending platform. My RigidBody2D config(I'm using unity 5.1.2) Can collider do anything with this problem?
0
Main camera transform.forward becomes up and down when looking from above The camera script is a 3rd person orbit camera, when I look straight it does what it supposed to do which is walk in the direction the camera is pointing, but when the camera is looking down from above the player, the camera's forward is now up. This means when I press W to go forwards I go into the ground and when I press S it goes upwards. Here is my movement script private void FixedUpdate() float x Input.GetAxisRaw("Horizontal") float z Input.GetAxisRaw("Vertical") Vector3 moveDirection Vector3.zero moveDirection Camera.main.transform.right moveDirection Camera.main.transform.forward moveDirection.y 0 Rotation if (x ! 0 z ! 0) anim.SetBool("Walking", true) if (x ! 0) transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.4f) else transform.localEulerAngles new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z) else anim.SetBool("Walking", false) Moving if (Input.GetKey(KeyCode.LeftShift) amp amp !idle) anim.SetBool("Running", true) rb.position z Camera.main.transform.forward Time.deltaTime runSpeed rb.position x Camera.main.transform.right Time.deltaTime runSpeed else anim.SetBool("Running", false) rb.position z Camera.main.transform.forward Time.deltaTime moveSpeed rb.position x Camera.main.transform.right Time.deltaTime moveSpeed while I'm asking, the movement script gets doubled when two keys are pressed, how do I fix it while keeping the same functionality of my current movement script?
0
How to prevent an object with high velocity from passing through a collider? Consider a simple 2D platformer. I have a BoxCollider2D on the player object and a TilemapCollider on the ground below(grid). I created a quot jump quot script for the player through which the player object jumps and comes back to the ground, clean. But when the player object goes relatively high and comes down with a high velocity, it doesn't collide with the ground(grid) instead it goes right through the tilemap collider and into the void. How can this behaviour be prevented?
0
Unity Collision Difficulties (How do I make a ground in unity with lots of pieces that doesn't have poor collision?) So I'm working on this game that I came up with the idea for while watching the Unity Roll a ball tutorials. So it's probably important to note that I'm extremely new to game design and I don't have a whole lot of experience in programming. So the game idea that I had is a lot more complex than what it should be for someone who's pretty much completely new to game design, so I guess I'm trying to break it down into smaller bits until I have enough experience to build it into a cohesive game. Currently what I want to work on is a game where you play as a sphere rolling down a plane with open edges so you can fall off. There are walls that you have to avoid, and if you run into them it will take away from the space between the walls and the edge of the plane. I guess I was sort of thinking of having a sort of similar visual style as bastion in that sense. The way I thought I would go about this is to break the plane up into smaller squares and then do some programming so that when you run into the walls the smaller squares at the edge of the plane fall off. Though before I could even get to programming I ran into a big problem. Because of the way Unity physics work and the way I built the ground, the player collision with the ground is god awful. When I was just testing it with some basic controls the ball would roll all choppy and if I picked up enough speed it would start to jump. I assume this is because it's colliding with all the edges of the grid system that I built. Does anyone know of any way I can program the edges to not interact with the player? Or if there's a better way to go about doing this?
0
How do I get my fish to face the right way? I'm making this 2d collecting game in Unity where you collect fish. However I can't get them to face the direction they are going. I've asked on some Discords and got no answer. Thanks in advance. Here's is the video of the fish. And here's the code using System.Collections using System.Collections.Generic using UnityEngine public class NewBehaviourScript MonoBehaviour public float minY public float maxY public float minX public float maxX public float speed public float maxZ Vector2 targetPosition Start is called before the first frame update void Start() targetPosition GetRandomPosition() Update is called once per frame void Update() if ((Vector2)transform.position ! targetPosition) transform.right (Vector2)targetPosition transform.position Vector2.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) else targetPosition GetRandomPosition() Vector2 GetRandomPosition() float randomX Random.Range(minX, maxX) float randomY Random.Range(minY, maxY) return new Vector2(randomX, randomY)
0
What is the proper way to handle data between scenes? I am developing my first 2D game in Unity and I have come across what seems an important question. How do I handle data between scenes? There seems to be different answers to this Someone mention using PlayerPrefs, while other people told me this should be used to store other things like screen brightness and so on. Someone told me that the best way was to make sure to write everything into a savegame everytime that I changed scenes, and to make sure that when the new scene loads, get the info from the savegame again. This seemed to me wasteful in performance. Was I wrong? The other solution, which is the one I have implemented so far is to have a global game object that isn't destroyed between scenes, handling all the data between scenes. So when the game starts, I load a Start Scene where this object is loaded. After this ends, it loads the first real game scene, usually a main menu. This is my implementation using UnityEngine using UnityEngine.UI using System.Collections public class GameController MonoBehaviour Make global public static GameController Instance get set void Awake () DontDestroyOnLoad (transform.gameObject) Instance this void Start() Load first game scene (probably main menu) Application.LoadLevel(2) Data persisted between scenes public int exp 0 public int armor 0 public int weapon 0 ... This object can be handled on my other classes like this private GameController gameController GameController.Instance While this has worked so far, it presents me with one big problem If I want to load directly a scene, let's say for instance the final level of the game, I can't load it directly, since that scene does not contain this global game object. Am I handling this problem the wrong way? Are there better practices for this kind of challenge? I would love to hear your opinions, thoughts and suggestions on this issue. Thanks
0
Lightmapper artifacts I really don't understand why this is creating these kinds of artifacts. I'm starting to think something is wrong with Unity. There are clearly no overlapping faces on the Model. There is enough of a margin to remove all chances of bleed. Yes the lid is a seperate object but any UV's of the lid and it's box are not overlapping. Thix odd pixelation occurs no matter the quality. It happened all the time sofar here and there and it forced me to replace a few objects in older projects. No idea what causes it. Really sick and tired of this. Edit when I rotate the crate by 90 degrees the artifacts appear on the adjacent side of the cube. From the perspective of the camera it would be the same side. So clearly it's not the UV's or anything. Lightmap settings Object Import settings
0
Refactoring out asynchronous webrequests to an interface I have a Unity project with UnityWebRequest calls in it. They are all working correctly, but I'd like to refactor them out (they are implemented pretty badly at the moment). The way I would like to do this is with a WebRequestSender class that implements an IWebRequest interface. Each call would return a WebResult object that I can use. public class WebResult public long ResponseCode get set public bool IsError get set public string Value get set public static WebResult Success(long responseCode, string value) return new WebResult IsError false, ResponseCode responseCode, Value value public static WebResult Failure(long responseCode) return new WebResult IsError true, ResponseCode responseCode, I'm having trouble understanding how to implement the interface, as these calls are asynchronous. Ideally, in the script when I need to make a call, I would have one line, like so WebRequest.Login(form) and that would return the result. I'm not sure what I have to add for it to wait for the call, or however it is executed. public interface IWebRequest WebResult Register(WWWForm form) Do I need to alter the return object so it allows for asynchronous calls? Or do I have to change the implementation the call of the implementation? As for my implementation, it doesn't work. The return statement on the Register function isn't called (even if it was, I'm not sure the return object would be populated?) Sample below public class WebRequestSender MonoBehaviour, IWebRequest private const string REGISTER URL "http localhost 51044 api Users Register" private WebResult webResult public WebResult Register(WWWForm form) StartCoroutine(MakeWebCall(REGISTER URL, form, (UnityWebRequest webRequest) gt RegisterDelegate(webRequest))) return webResult private void RegisterDelegate(UnityWebRequest webRequest) if (webRequest.isHttpError webRequest.isNetworkError) webResult WebResult.Failure(webRequest.responseCode) else webResult WebResult.Success(webRequest.responseCode, webRequest.downloadHandler.text) private IEnumerator MakeWebCall(string url, WWWForm form, Action lt UnityWebRequest gt finishDelegate) using (UnityWebRequest www UnityWebRequest.Post(url, form)) yield return www.SendWebRequest() finishDelegate(www)
0
Drag Object to Collide Unity Please help, I am developing a 2D game for a school project and I want to drag the apple to the think box then when it collides, the apple will go back to the original position then it will add 1 point to the score. I'm just new to Unity. So please help
0
Unity Game objects in scene load incrementally and not at the same time I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images. In order to load this data in the scene, I make a lot of UnityPlayer.UnitySendMessage(GameObject,Function,Params) calls to many C scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc. Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly. How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?
0
how to prevent call on OnValidate() when running game I need OnValidate() to be called only when I am designing my level (placing game objects at their respective positions and setting properties before running the project). But I don't want it to be called when I run the project. I can manually comment it out, but that will take a lot of time, since I have several OnValidate() calls. How can this be done, if it is possible?
0
Unity not opening in Ubuntu I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens. These are my system specifications. I was running Unity on the same computer, several months ago, using Windows. Model Thinkpad R500 Processor Intel Core 2 Duo CPU P8600 2.40GHz 2 RAM 2Gb DDR3 RAM Storage 155Gb HDD Graphics Card ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX Why is it doing this? Is there a problem with the latest build? What should I do to fix it?
0
how to automate the game testing? I am new into this field of testing. I just developed a basic game using unity engine but i want to test it. I have checked with selenium but i don't know how to get the value that is being returned which has the information of the action that is being performed in the game. If i am able to get the value then i will be able to take necessary action accordingly.
0
How do I prevent inappropriate ads from appearing in my game? My game implements Unity ads, and is designed with a universal audience in mind. As such, I would prefer not to have 18 ads (or even 13 ads depending on the circumstances) appearing in it, especially since it would appeal to younger audiences as well. My question is then, how do I prevent age inappropriate ads from appearing? Is there a way to simply set the age limit or content restrictions on Unity ads? The only setting along those lines that I can find is the COPPA toggle, and that would cause other issues (not to mention that it wouldn't do anything to the ads). I've looked in the dashboard for a while, and I've tried to research it beforehand, but the fact that they've shifted to a centralized services page, redirected all the old links (breaking them in the process), reorganized the settings in the dashboard, and 404d their FAQ post on the topic doesn't help either. Blocking ads based on a rating would work too, as I would have to get one because I am publishing to Google Play. Edit The second link only 404s some of the time. I just happened to get it every time before asking this question. Bad luck, I guess.
0
UNITY Prevent 3D Text Render Trough All Object Without Shader im tired of those answer i found trough search engine that just keep saying " the trick is to modify the shader " without thinking because they want to gain reputation , in my case , i have 2 3D text , one of them using special font and the other one using default font , and the shader to prevent the text render trough all object from http wiki.unity3d.com index.php?title 3DText is not working and giving weird white square plus i don't want to change from default Arial font because i want to make them look different , i also cannot use sprite as background because i need to change their color trough script to give some effect , this is my picture showing my problem If the picture is not clear , go here https i.stack.imgur.com hLqC9.png The menu dropped is at Z 100 while the background is at Z 20 , as you see , the text is rendered while the other not ( such as the border , ect ). And this is the picture when my special font without using the shader If the picture is not clear , go here https i.stack.imgur.com vbrQ1.png Now the picture of my special font using the shader If the picture is not clear , go here https i.stack.imgur.com hMAR2.png Is there any possible way to prevent the text rendered without shader change the background to sprite ? Im sorry if this already asked somewhere , i just cannot find it at search engine ( neither here ) .
0
Material tiling and offset in unity Ambiguity What exactly is the difference between Tiling the material and Offset of material? Need to do I need the material to be repeated n times on the object where I need to set the value of n via script.How do I do it? It seems to happen through Tiling(tried via inspector) but again what is difference between mainTextureOffset and setTextureOffset? Tried Following is the line of code that I tried to repeat the texture n number of times on an object(repeat across the width of object), but it does nothing significant that I can see.
0
Fixed distance between character and ground whatever slope value I am working on character moving on any ground meaning whatever slope degree ,the result i got is the character does not moving on just shake in his place the following the code i wrote public float speed 1 bool isMoving Transform childPosition Rigidbody rb private void Start ( ) rb GetComponent lt Rigidbody gt () Update is called once per frame void FixedUpdate () if (Input.GetAxis("Horizontal") gt 0) rb.velocity new Vector3(1f, rb.velocity.y, rb.velocity.z) else if (Input.GetAxis("Horizontal") lt 0) rb.velocity new Vector3( 1f, rb.velocity.y, rb.velocity.z) else transform.position transform.forward Time.deltaTime speed detectRoad() private void detectRoad() Ray ray new Ray(transform.position, transform.up) RaycastHit hit if (Physics.Raycast(ray, out hit)) transform.rotation Quaternion.FromToRotation(transform.up, hit.normal) transform.rotation if (hit.distance lt 0.6f) transform.position transform.up Time.deltaTime else if (hit.distance gt 2f) transform.position transform.up Time.deltaTime This animated gif is about what I want
0
A way around the deprecation of AppInvite in Unity I was using FB.Mobile.AppInvite, but according to the Facebook documentation, it is deprecated. So, how could I send an app invite?
0
I'm trying to write a randomly patrolling AI for my 2D Platformer I'm trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat quot sentient quot enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving. The problem is, it doesn't seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don't occur as frequently. I need to know what I've done wrong here. Thanks. void Update() RNG behaviour Random.Range(0,3) jumpSpeed Random.Range(1,5) clock timer Time.deltaTime time private float waitTime 2.0f private float timer 0.0f void MoveRandomizer() if((Mathf.Round(timer waitTime)) 0) if(behaviour 0) movingRight false if(behaviour 1) movingRight true if(behaviour 2) rb.velocity new Vector2(rb.velocity.x, jumpSpeed)
0
Missing UI options in Inspector window when I import FBX files I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files. In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well. This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.
0
How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?
0
How to find the angle of an arc for reflection I am using the following code to calculate points for a circle arc drawn with a Line Renderer. for (int i 0 i lt pts i ) float x radius Mathf.Cos(ang Mathf.Deg2Rad) float y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLine.positionCount i 1 arcLine.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts How can I change the angle ang to create a reflected arc along the line P1P2 as in the image below? Please note that totalAngle represents the portion of the circle that is to be drawn between 0 and 360.
0
How do I handle parallel lines when looking for intersections? I'm using the following method to determine the intersection point of two vector2 public static Vector2 LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2) Get A,B,C of first line points startPoint1 to endPoint1 float A1 endPoint1.y startPoint1.y float B1 startPoint1.x endPoint1.x float C1 A1 startPoint1.x B1 startPoint1.y Get A,B,C of second line points startPoint2 to endPoint2 float A2 endPoint2.y startPoint2.y float B2 startPoint2.x endPoint2.x float C2 A2 startPoint2.x B2 startPoint2.y Check if the lines are parallel float delta A1 B2 A2 B1 if (delta 0) throw new System.Exception("Lines are parallel") Return the intersection point return new Vector2( (B2 C1 B1 C2) delta, (A1 C2 A2 C1) delta ) Currently the method throws an exception for parallel lines but I don't like the idea to wrap every call of that function in a try catch. Is there a better solution for this? I can't return null because Vector2 is a struct. Maybe somthing like the following? public static bool LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2, out Vector2 intersectionPoint)
0
I want a variable field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid? I want a field I declared (float attackRange) to be only declared when inheriting class set "bool haveLongRangeAttack" is set to true. I wanted to use Compiler Directives for this purpose. Here is the code I wrote using UnityEngine public abstract class Enemy lt T gt MonoBehaviour where T Enemy lt T gt SerializeField protected bool haveCloseRangeAttack false, haveLongRangeAttack false if haveLongRangeAttack true SerializeField protected float attackRange 1f endif SerializeField protected GameObject mainCharacter null protected GameObject enemy null protected virtual void ChasePlayer() if(haveCloseRangeAttack) ... else if(haveLongRangeAttack) ... I don't know if it is right way to of do what I want or using Compiler Directives so please review my code and tell me if there is a problem, or if there is a better way. It was before 6 months when I started writing code, and C was my first language. I am trying to learn new things concepts and writing at my own style. So there will be another way (maybe more efficient) if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me... TY for taking time . ! PS There is no compiler directives tag in Tags section. Maybe it will be useful to add this tag.
0
Maya Single Model with different animation I am newbie in Maya and would like to clarify some implementations in Animation. I know how to create simple animations in Maya. These animations are exported to Unity3D (as .fbx with controllers) to use in my application. I want to know whether it's possible to attach different animations to one model. For example, let's say, I have an arrow mark model and I want to show different animations for the model like moving left, moving right, moving up, moving down, etc. So that, when I export, I'll get one model Arrow.fbx and different controllers LeftAnimController, RightAnimController, etc. Is that achievable? Or I need to create different Arrow mark model with it's own controllers. Any help will be appreciated. Thank you.
0
Unity Unable to blend 2D Light renderers I've followed the documentation on Unity regarding 2D lighting. It said to turn on Alpha blending in the options. But this is how it turns out If Alpha blending is off If Alpha blending is on I'm not entirely sure why it's turning black. These are my settings for the 2D light I've checked my layers, specifically the tile map floor, and it's on the Default layer. I just want my lights to blend well.
0
Unity Modify basic dissolve shader graph to dissolve from bottom up I have this dissolve shader made in shader graph which works fine, however I would like it to dissolve from bottom up, how would this be done?
0
pivot of a 3d model outside its mesh after importing into Unity3d as you can see, the pivot is outside my mesh. I want to use the pivot for rotating around, for that I need to set the pivot to the real quot rotating point quot . I know that there's the SetPivot script, but it only works with pivots inside meshes. This mesh is part of an object which contains several meshes, I created it with Wings3d. The problem appears with .obj and .3ds as file extension. 1.How can I fix this? 2.Is there a possibility to define a second pivot which can be used in scripts to quot rotate around quot (maybe a vector3 which can be set in quot Designer quot )?
0
Enabling Unity GUI drawtexture permanently? I'm trying to get an image to show in Unity based on a certain criteria. I would like the position of the image to be randomized every time on play. However since GUI.DrawTexture shows the image for a single frame only, I end up with the image flashing across the screen in random areas. I would the first location to be randomized and the image to remain still there. Any advice on how to perform this will be greatly appreciated. Code void OnGUI() if(HP gt 0.9f) GUI.DrawTexture(new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300) aTexture)
0
C in Unity with dependencies I am currently creating a c program to eventually use in Unity. This c program contains references to libraries like OpenCV and dlib, referenced with a include statement which calls in other files, which are installed on my machine. My question is How do you compile your c project so that it runs in Unity completely self contained? i.e no reference to external files are needed, and all that are references are included within the program. Is there a specific tool to use, or a useful tutorial on the net? Thanks for the help.
0
How to set emission level through C I am willing to change emission level through code without affecting its color. (i.e., changing the brightness number shown in the box at the right side of the inspector, while keeping the emission color unchanged) I have tried this so far, but I don't know how to use my value variable to update the material public class EmissionColourChange MonoBehaviour Material thisMat Color c public float value void Start () thisMat GetComponent lt Renderer gt ().material c GetComponent lt Renderer gt ().material.color thisMat.EnableKeyword( quot EMISSION quot ) value c.r void Update () thisMat.SetColor( quot EmissionColor quot , new Color(c.r,c.g,c.b))
0
Unity sprite rig affecting performance I created a simple sprite rig using the skinning editor provided by the new 2D Animation V2 package. But it causes a huge FPS drop when added to the scene. Methods such as SpriteSkin.LateUpdate generates significant amount of garbage as shown in the picture See the spike shown on the CPU profiler when the rig is being enabled The rig is not even animated. I also checked the other sample rigs provided by Unity and they also performed in a similar fashion. Is this normal? I'm targeting mobile, so anything that can be done to avoid or improve the situation will be helpful. I'm using 2d animation v2 2.0.0 preview.2 in Unity 2018.3.8f
0
Get the length of an animation from the Animator How do find the length of an animation that is included in the Animator attached to a GameObject?
0
Why the MoveTowards make the transform moving nonstop? In the Update in the else part, I'm trying to move the transform up from its current position on the exit more up by offset. When the flag bool exit is true I want the transform to move up more by the offset for example if the offset is 7 then move up on the Y more 7. but it's moving up non stop. I tried to like this with exitPosition variable for storing at exit but still, it's moving up non stop. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Testing MonoBehaviour public float speed public float offset private bool exited false private Vector3 exitPosition private void Start() Debug.Log( quot Position quot transform.position) private void OnTriggerExit(Collider other) if (other.name quot Cube quot ) Debug.Log( quot Exited ! quot ) exitPosition new Vector3(transform.position.x, transform.position.y offset, transform.position.z) exited true private void Update() if (!exited) transform.position Vector3.up speed Time.deltaTime else transform.position Vector3.MoveTowards(transform.position, exitPosition, speed Time.deltaTime)
0
Unity3d AudioSource is not playing if gameObject is removed after play was started I am not able to play my audio source if I deactivate the panel where the AudioSource is attached to AFTER it. audioBtnEnter tmpBtnGeneral.GetComponent lt AudioSource gt () audioBtnEnter.Play() tmpBtnGeneral.SetActive(false) I would totaly understand if this would not be possible tmpBtnGeneral.SetActive(false) audioBtnEnter.Play() But why does the first code not trigger the audio play? Is this a race condition problem?
0
How can I create a copy of an object in Unity? I'm new to unity. How can I make some copies of my GameObject in Unity by scripting? I have tried this by the way public GameObject stone 3 void Start () for (int i 0 i lt 10 i ) Instantiate(stone 3, new Vector3(i 2.0f, 0, 0), Quaternion.identity) I can't really understand why it's not working.
0
Unity3D, How do I press one key and then cant press another key while the one is pressed? I am making a horror game, and I want to press a key to look up while I am idle, that i've done but if I press the W key it stands in idle but floating forward. How can I disable the W key while I press the F key to look up ? Everything works fine I can press F and the LookUp Animation is being played and if KeyUp on F the Animation goes back to Idle. My problem is if I am in LookUp Animation when I press F, I can also press W to go forward but its floating not walking. I want to deactivate this function so I can just press F when I am Idle. Thanks for help. my Script public float speed 10f public Rigidbody rgb public Animator anim bool walk false Use this for initialization void Start () rgb.GetComponent lt Rigidbody gt () anim GetComponent lt Animator gt () Update is called once per frame void Update () float move Input.GetAxis ("Vertical") anim.SetFloat ("Speed", move) if (Input.GetKey (KeyCode.W) walk true) rgb.transform.position new Vector3(0, 0, 1) speed Time.deltaTime Debug.Log("Walking") else walk false Debug.Log("Idle") if (Input.GetKey (KeyCode.F)) anim.SetBool("LookUpIdle", true) rgb.transform.position transform.position else anim.SetBool("LookUpIdle", false)
0
Is it possible to have a point light cast shadows but no reflection? I'm working in Unity 5.3.6. I have a point light that is simulating sunlight from a window. It looks great, except the floor reflects a bright white circle. I want the floor to reflect other lights in the room, just not this one. Is this possible?
0
How to make Rigidbody.AddForce less delayed in Unity3D? I'm trying to make it so that when the player in my game moves left or right, he lightly jumps from his current position to his new position. The way I have it set up now, the jump occurs once he has arrived at his new position. What can I do to make it so that the jump happens sooner so that it appears that he jumps to his new position? Here is the code I have that controls that part of his movement if (Input.GetKeyDown(KeyCode.LeftArrow) amp amp transform.position.x gt minXPos) targetPos new Vector3(transform.position.x xIncrement, transform.position.y, transform.position.z) rb.AddForce(Vector3.up jumpForceTwo, ForceMode.Impulse) transform.position Vector3.MoveTowards(targetPos, transform.position, speed) isHorizontalingLeft true else if (Input.GetKeyDown(KeyCode.RightArrow) amp amp transform.position.x lt maxXPos) targetPos new Vector3(transform.position.x xIncrement, transform.position.y, transform.position.z) rb.AddForce(Vector3.up jumpForceTwo, ForceMode.Impulse) transform.position Vector3.MoveTowards(targetPos, transform.position, speed) isHorizontalingRight true Here is a video showing what is happening (sorry it's blurry) https youtu.be rPewtb8QywE
0
How to randomly generate biome with perlin noise? I want to generate a procedural world using perlin noise. As expected, my terrain is generating with a repetitive patern. I'd like to add biomes, zones separated with higher or lower amplitude to simulate mountains or plain. I first thought I could randomly select rectangles of verticesof random sizes and then give them bigger amplitude to simulate mountains. The problem with that is that It wont seem natural, since I will only have rectangle biomes and also I don't know how to make it so the mountains would connect with the plain to avoid things like this Here is my script public int size 10 public float amplitude public float frequence void GenerateTerrain(float amp, float freq) Mesh meshy MeshRenderer meshRenderer GetComponent lt MeshRenderer gt () meshRenderer.sharedMaterial new Material(Shader.Find( quot Standard quot )) MeshFilter meshFilter gameObject.GetComponent lt MeshFilter gt () List lt Vector2 gt uv new List lt Vector2 gt () Vector3 vert new Vector3 size size List lt int gt tri new List lt int gt () List lt Vector3 gt norm new List lt Vector3 gt () meshy new Mesh() for (int i 0, x 0 x lt size x ) for(int z 0 z lt size z ) float y Mathf.PerlinNoise(x amp, z amp) freq vert i new Vector3(x, y, z) i for (int i 0 i lt vert.Length i ) norm.Add( Vector3.forward) for (int x 0 x lt size 1 x ) for (int z 0 z lt size 1 z ) int i size x z tri.Add(i) tri.Add(i 1) tri.Add(i size) tri.Add(i size 1) tri.Add(i size) tri.Add(i 1) for (int i 0 i lt vert.Length i ) uv.Add(new Vector2(vert i .x, vert i .z)) meshy.vertices vert meshy.triangles tri.ToArray() meshy.uv uv.ToArray() meshy.normals norm.ToArray() meshFilter.mesh meshy void Update() if (Input.GetKeyDown( quot u quot )) GenerateTerrain(frequence, amplitude)
0
Prevent Animation Tab from changing the position of an object I am quite new to Unity. I am using the latest version. When I try to make a door open animation, it goes well with rotation. But when I add the position property it takes it to the Vector3(40,12.5,7.5) instead of (10,2.5,15) at the first frame. I try to change the value but it reverts after I write.
0
Custom build failure callback I've been working on some custom build scripts, which will manipulate the references of certain MonoBehaviours. I'm using IPreprocessBuildWithReport to do the manipulation, and I want to reset the references when the build completes. Even if the build fails, I want to do the operation, but I want to do some additional stuff if it fails. I'm also using IPostprocessBuildWithReport and IProcessSceneWithReport as well. I've tried putting a Debug.Log in OnProcessScene and OnPostProcessBuild. I'm building without JAVA path defined, for Android, or without the Keystore password, which fails the build. The IPreprocessBuildWithReport correctly prints the Debug, but the others don't. Is there any class or interface which has a callback for Build Failure which I can use? I've tried to get the summary from the BuildReport in OnPreprocessBuild, but the result is always returning Unknown. Edit I would also like to make the same changes if the Build was cancelled, rather than just if it was failing. Platforms Windows, Android Unity 2019.3.7f1
0
In Unity , How to clear instantiated object when I call the function? Here is a function I call out am UI element public void LoadCurrentItem(ItemType t) List lt Item gt itemList SessionManager.singleton.GetItemAsList(t) if (itemList null) return if (itemList.Count 0) return GameObject prefab (t ItemType.consumable) ? eq left.inventory.slotTemplateUD eq left.inventory.slotTemplateLR Transform p eq left.inventory.slotGrid int dif iconSlotCreated.Count itemList.Count int extra (dif gt 0)?dif 0 for (int i 0 i lt itemList.Count extra i ) if (i gt itemList.Count 1) iconSlotCreated i .gameObject.SetActive(false) continue IconBase icon null if(iconSlotCreated.Count 1 lt i) GameObject g Instantiate(prefab) as GameObject g.SetActive(true) g.transform.SetParent(p) icon g.GetComponent lt IconBase gt () iconSlotCreated.Add(icon) else icon iconSlotCreated i icon.gameObject.SetActive(true) icon.icon.enabled true icon.icon.sprite itemList i .icon icon.id itemList i .item id It might seem less informative, but my question is simple and stupid I want to destroy my GameObject g that instantiates prefab before it instantiates prefab so that I can refresh GameObject g to create eq left.inventory.slotTemplateUD or eq left.inventory.slotTemplateLR How can I achieve this goal?
0
How to simulate an elastic force, using Hinge Joint ? I've a bucket connected to a rope. I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope. How can i do that ? Thanks
0
How can i add a description of gameobject when click on the gameobject? I have this DetectInteractable working script attached to Player (FPSController). I'm using tag to detect interactable objects, each object i want to be interactable i change his tag in the editor to "Interactable". ( Maybe there is a better way to do it without using tag ? It's working but many told me not to use tag. ) I'm using Raycast to hit a gameobject detect if it's "Interactable" and if it does i display on the gameobject his name. For example "Security Door" or "Screen Monitor" or "Surveillance Camera" Now i want to do that if i hit a gameobject with the raycast and it's "Interactable" if i will click the mouse left button it will display a description text description about the gameobject. But this time i want to use some gui box so it will be in front of the screen in the middle and not on the gameobject. The problem is that i need to create a script for every "Interactable" gameobject and make that if i click on a button it will display a description. Then how do i make the script and how can i make that when i attach the script to each gameobject it will make in the inspector a box of text so i can enter and type there the description of the item(GameObject) ? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public Canvas canvas public Text interactableText private RaycastHit whatObjectHit private RotateObject rotateobj private void Start() rotateobj GetComponent lt RotateObject gt () private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (rotateobj.rotating false) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true interactableText.gameObject.SetActive(true) interactableText.text whatObjectHit.collider.gameObject.name print("Hit ! " whatObjectHit.collider.gameObject.name) else image.color Color.white interactableText.gameObject.SetActive(false) print("Not Hit !") else image.color Color.white public class ViewableObject MonoBehaviour public string displayText public bool isInteractable
0
Save Script Doesn't Save Item Variables I've been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player's itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don't receive any errors or warnings in the Console. Here is my script to the Saving System using System.Collections using System.Collections.Generic using UnityEngine using System using System.Runtime.Serialization.Formatters.Binary using System.IO public class InventorySave MonoBehaviour Public variables for inventory and health private GameObject itemHolder private ItemInformation myItemAmount Initiates before the first frame void Start() Gets components for the player variables itemHolder transform.gameObject myItemAmount itemHolder.GetComponent lt ItemInformation gt () Function that will be called when player saves game from pause menu public void SaveGame() Creates file to store variables BinaryFormatter bf new BinaryFormatter() FileStream file File.Create(Application.persistentDataPath quot SaveData.dat quot ) SaveData data new SaveData() Gets the player data data.itemSave myItemAmount.itemAmount Writes player data to file and encrypts it bf.Serialize(file, data) file.Close() Holds data that is to be saved Serializable class SaveData Variables for save file public int itemSave
0
How can I develop and publish a game when I don't have the money to buy a brand new computer? I'd like to complete and publish a game made with Unity, but given the fact that the cost of a brand new computer represents a significant part of my yearly income, I don't have enough money to buy one. My ultimate goal is to publish the game on iOS. Aside from generating more revenue upfront, what are my options? Notes from the moderators We've made this question canonical, so we're looking for non specific options (e.g. please avoid targeting specific regions, or suggesting to buy specific models, etc.) we'd like to help future visitors coming from all over the world, for the years to come.
0
combining multiple materials into one material (Unity) I am confused with how should I texture my character. I am using blender for modelling. And while my model is too complex I dont want to use uv map techniuqe. I can get what I need with using seperate materials. Therefore I assign different materials to different meshes in Blender then import it to Unity. Therefore I have lots of different material in one model and I think it increases draw call. What can I do to combine these material into just one. I thought baking would be sollution but while my character is dynamic I can not get a good result.
0
How move camera where i look? I am try make simple flying camera. Without character. But than I press forward camera moving to another direction. void Update() horizontalInput Input.GetAxisRaw("Horizontal") verticalInput Input.GetAxisRaw("Vertical") var mouseX Input.GetAxis("Mouse X") var mouseY Input.GetAxis("Mouse Y") var trm Camera.main.transform if (horizontalInput ! 0 verticalInput ! 0) trm.position moveSpeed new Vector3(horizontalInput, 0, verticalInput) var rotateValue new Vector3(mouseY 2, mouseX 2, 0) trm.eulerAngles rotateValue trm.rotation Quaternion.Euler(rotateValue) Than I press 'W' camera moving to left... I understand that it is necessary to coordinate the motion vectors and camera rotation. How best to do it?