(Unity) Physics based movement vs Straight position change Unity provides a cool physics engine for game development and I want to utilize it in my game. Shorter version I want to use physics engine for everything else other than character movement because trying to use physics engine for player movement doesn't yield the perfectmovement speed that I want move x units per second. If I use physics engine for character movement, it gets complicated. I would rather just add "moved distance" to the position to have things done simple. Is doing something like this wrong? All the learning sources I read recommend to use physics engine for movement if the game incorporates physics engine. I am nervous am I wrong? Longer version The following description is where I use "physics", why I need physics engine. In my game a player fires a bullet. When enemies collide with bullet, they get pushed back slightly. A strong blast can push enemies far back so that they even bounce back from hitting wall. A recommend, a proper way, I was told, to utilize this physics engine for character movement is to add force to the direction I want to move. But doing so(adding force to the direction I want to move) will result in truck like slowly warming up by adding velocity. To avoid "truck like movement" I was told to apply greater force at the beginning. Doing so result in change in velocity like the below picture. However problem is not over yet, you must consider a situation where you change direction of movement while the character is running. If you started to move backward, all of the sudden while running forward, you will need to slow down forward movement burn velocity by adding backward force. Thus rotation burns velocity. So a solution is to find out perpendicular velocity to your desired direction, then find out needed amount of force to "burn off" the undesired velocity. This seems way too complicated for a character to simply move around. I would rather just move character to desired direction by simply adding "constant X distance" to the character's position. But I can't find a source of example where it utilizes both "simple movement by directly adding moved distance to the position" and "using physics engine for the game". All the sources of learning(using Unity physics) I find say use this complicated way of having character to move around. I wonder is there a reason why people don't just add moved distance to the position?


How to rotate a rigidbody with a Pid controller I would like someone to describe me how to use a PID controller to rotate a rigidbody with AddTorque to a specific position. (like a spacecraft that rotates the Y axis of rotation towards Camera.forward for example). Can anyone show it to me with a script? Actually I already use this script to rotate with AddTorque but the object almost never stops at the precise point. Vector3 camForward Camera.main.transform.forward Vector3 rbForward rb.transform.forward Vector3 torqueY Vector3.Project(torque, Vector3.up) Vector3 torque Vector3.Cross(camForward, rbForward) rb.AddTorque(torque) rb.AddTorque( rb.angularVelocity)


Destroying copy of DontDestroyOnLoad GameObject? I have a Main Menu with level selecter up to 5 different scenes on one Map. I also have a MenuManager which doesn't get destroyed between the scenes to gather the bool information of level finished or not. When I start the game and change for example level 1 and move back to the Main Menu again the MenuManager gets copied. I tried this at first public static GameObject menuInstance void Awake() if ( menuInstance null) menuInstance this.gameObject else Destroy(gameObject) My problem with that is that the copied GameObject that get's destroyed is the wrong one. This is the copy that gets created after I switched the scenes and back to Main Menu. This is the original MenuManager that should be the menuInstance Object and the other one should be destroyed. How can I not delete the original one and delete the one without the references? I come up with something but I am not sure if this is the right way to do this. I changed the code in the Awake() function to void Awake() if ( menuInstance null) menuInstance this.gameObject I checked one of the missing references to be null and then destroy the fake copy. Update() if( startTheGame null) Destroy(gameObject)


Any problems with flipping a sprite by scale? (2d Platformer) I am wondering if there are any problems with flipping a sprite on the x axis using vector2 to tell which direction it is facing flip. Though doing this helps me write less code for Ray cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning.


StartCoroutine function inside TriggerOnEnter2D not working unity kinect So i'm using Kinect with unity to track user's hand movements, and let the user's hand act as a mouse, I have written the code to detect a collision between a button (sprite object) and the hand cursor using OnTriggerEnter2D, but I want the hand cursor to remain on the button (sprite object) for atleast 3 seconds for it to be considered as a button click action. The WaitForSeconds coroutine doesn't seem to be working. What am i doing wrong? public class MenuSelect MonoBehaviour private string btnName private string themeName Use this for initialization void Start () gestureListener Camera.main.GetComponent lt GestureListener gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) print("Collision Detected") StartCoroutine(WaitTime(3)) if(col.gameObject.tag "Button") btnName col.gameObject.name switch(btnName) case "musicBtn" Application.LoadLevel("Menu Music") break case "startBtn" Application.LoadLevel("Menu Select") break case "instructBtn" print("Instruction Clicked") break case "exitBtn" Application.Quit() break case "themeBtn" Application.LoadLevel("Menu Theme") break case "backBtn" Application.LoadLevel("Menu LoadScreen") break IEnumerator WaitTime(float waitTime) yield return new WaitForSeconds(waitTime) print("seconds up already")


Video playback in Unity I'm not satisfied with the quality of video playback in Unity (Movie texture which I run after converting video with Miro converter and importing it to Unity),... so, is there any chance that there is a 3rd party library which I can integrate inside Unity to play my movie file? My movie is full HD intro movie to my 3d app which can be played from application menu. I've tried to use Media Player Classic (MPC) as external application, but the problem is, when I run MPC as new Process from application menu, my menu minimizes and this looks awkward for one stand alone app. When intro finishes, I have to maximize my menu by clicking on application icon placed on Windows taskbar.


Not able to connect to Photon(PUN).photon unity networking error I'm new to photon Networking. My game was working great suddenly this is appearing Cannot send messages when not connected. Either connect to Photon OR use offline mode! UnityEngine.Debug LogError(Object)


Generating mesh along path I'm currently trying to generate a path along an array of points (Vector3) This is the result I'm currently getting The dark gray points are the given path The red points are the generated vertices And the triangles are obviously the mesh I failed to generate correctly And from the bottom it looks like this, which is odd, because I'd expect all the missing triangles to be at the bottom. But some of them just don't exist here's the code i wrote that generates the path mesh Removed code since there's no need in showing something that doesn't work And here's a quick example of what it looks like when I drag a path SOLUTION FOUND As the accepted answer states, I was skipping triangles in my triangle for loop. Here is my new working code public static Mesh extrudeAlongPath(Vector3 points, float width) if (points.Length lt 2) return null Mesh m new Mesh() List lt Vector3 gt verts new List lt Vector3 gt () List lt Vector3 gt norms new List lt Vector3 gt () for (int i 0 i lt points.Length i ) if(i ! points.Length 1) Vector3 perpendicularDirection new Vector3( ( points i 1 .z points i .z ), points i .y, points i 1 .x points i .x).normalized verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) else Vector3 perpendicularDirection new Vector3( ( points i .z points i 1 .z ), points i .y, points i .x points i 1 .x).normalized verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) m.vertices verts.ToArray () m.normals norms.ToArray () List lt int gt tris new List lt int gt () Changed i 3 to i for(int i 0 i lt m.vertices.Length 3 i ) if(i 2 0) tris.Add(i 2) tris.Add(i 1) tris.Add(i) else tris.Add(i) tris.Add(i 1) tris.Add(i 2) m.triangles tris.ToArray () m.name "pathMesh" m.RecalculateNormals () m.RecalculateBounds () m.Optimize () return m


Assigning valid moves on board game I am making a board game in unity 4.3 2d similar to checkers. I have added an empty object to all the points where player can move and added a box collider to each empty object.I attached a click to move script to each player token. Now I want to assign valid moves. e.g. as shown in picture... Players can only move on vertex of each square.Player can only move to adjacent vertex.Thus it can only move from red spot to yellow and cannot move to blue spot.There is another condition which is if there is the token of another player at the yellow spot then the player cannot move to that spot. Instead it will have to go from red to green spot. How can I find the valid moves of the player by scripting. I have another problem with click to move. When I click all the objects move to that position.But I only want to move a single token. So what can i add to script to select a specific object and then click to move the specific object.Here is my script for click to move. var obj Transform private var hitPoint Vector3 private var move boolean false private var startTime float var speed 1 function Update () if(Input.GetKeyDown(KeyCode.Mouse0)) var hit RaycastHit no point storing this really var ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, hit, 10000)) hitPoint hit.point move true startTime Time.time if(move) obj.position Vector3.Lerp(obj.position, hitPoint, Time.deltaTime speed) if(obj.position hitPoint) move false


Gizmos not being drawn until GameObject selected I have implemented Scene loading in my game and have three scenes Persistent, Main Menu and Game By default, the player is loaded into the Persistent scene, which immediately loads the Main Menu, and when the player clicks on Play, Main Menu is unloaded and Game is loaded. Now, the two active scenes are Persistent and Game. However, I have a script with OnDrawGizmos on a GameObject in the Game scene. It seems that by default gizmos only begin to be drawn when I click on that GameObject, sort of activating it, and everything works fine. This used to just work before because Game was my only scene and Unity automatically selected that first GameObject. Now, with multiple scenes, no GameObject is selected by default and my gizmos won't draw until I manually click on it. How can I solve this?


How to get Entitas components from gameObject.getEntityLink() I'm new to Entitas. I have a DamageSystem that should Physics.Raycast() toward the target and if tag is enemy it should reduce enemy health. I have HealthComponent public class HealthComponent IComponent public float value In DamageSystem I wanna do something like if(Physics.Raycast(target, direction, out hit)) tag.gameObject.entity.health.value currentHealth damage But after Physics.Raycast(), I have only the gameObject and getEntityLink() method that return EntityLink without actual components... I guess that getEntityLink() returns only abstract components, and there is no way to get HealthComponent from EntityLink? Does someone know how to get components from EntityLink, in a clean manner? Thanks!


How to get button component in Unity 2019.3 I have a simple class attached to a button in Unity Canvas using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements public class AudioButtonPlay MonoBehaviour public Button button void Start() button gameObject.GetComponent lt Button gt () But on the line button gameObject.GetComponent lt Button gt () I get the following message GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface How can I access the "Button" component?


Card displacement in Unity Following a tutorial on Youtube, https www.youtube.com watch?v P66SSOzCqFU, I'm trying to make a card game that uses dragged cards. When I drag a card it's supposed to stay centered with the mouse, but it's showing up on the edge of the screen when I start to drag it. How do I make it so the card drags with my mouse instead? Currently I'm using two scripts, one for a drop zone and one for "draggable". When I tried to debug the draggable section it kept referring me back to a line in my drop zone script that just had a ' '. I'm working in Unity 5.6.0f3 and Visual Studio 2017. My drop zone code looks like this public class DropZone MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler public void OnPointerEnter(PointerEventData eventData) Debug.Log("OnPointerEnter") if (eventData.pointerDrag null) return Draggable d eventData.pointerDrag.GetComponent lt Draggable gt () if (d ! null) d.placeholderParent this.transform public void OnPointerExit(PointerEventData eventData) Debug.Log("OnPointerExit") if (eventData.pointerDrag null) return Draggable d eventData.pointerDrag.GetComponent lt Draggable gt () if (d ! null amp amp d.placeholderParent this.transform) d.placeholderParent d.parentToReturnTo public void OnDrop(PointerEventData eventData) Debug.Log(eventData.pointerDrag.name "was dropped on" gameObject.name) Draggable d eventData.pointerDrag.GetComponent lt Draggable gt () if(d ! null) d.parentToReturnTo this.transform And my Draggable code looks like this public class Draggable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler public Transform parentToReturnTo null public Transform placeholderParent null GameObject placeholder null public void OnBeginDrag(PointerEventData eventData) Debug.Log("OnBeginDrag") placeholder new GameObject() placeholder.transform.SetParent(this.transform.parent) LayoutElement le placeholder.AddComponent lt LayoutElement gt () le.preferredWidth this.GetComponent lt LayoutElement gt ().preferredWidth le.preferredHeight this.GetComponent lt LayoutElement gt ().preferredHeight le.flexibleWidth 0 le.flexibleHeight 0 placeholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex()) parentToReturnTo this.transform.parent placeholderParent parentToReturnTo this.transform.SetParent(this.transform.parent.parent) GetComponent lt CanvasGroup gt ().blocksRaycasts false public void OnDrag(PointerEventData eventData) Debug.Log("OnDrag") this.transform.position eventData.position if(placeholder.transform.parent ! placeholderParent) placeholder.transform.SetParent() int newSiblingIndex placeholderParent.childCount for(int i 0 i lt placeholderParent.childCount i ) if(this.transform.position.x lt placeholderParent.GetChild(i).position.x) newSiblingIndex i if(placeholderParent.transform.GetSiblingIndex() lt newSiblingIndex) newSiblingIndex break placeholder.transform.SetSiblingIndex(newSiblingIndex) public void OnEndDrag(PointerEventData eventData) Debug.Log("OnEndDrag") this.transform.SetParent(parentToReturnTo) this.transform.SetSiblingIndex(placeholder.transform.GetSiblingIndex()) GetComponent lt CanvasGroup gt ().blocksRaycasts true Destroy(placeholder) In the draggable code, if(placeholder.transform.parent ! placeholderParent) placeholder.transform.SetParent() is commented out because that's where I stopped in the tutorial in order to go back and fix my displacement issue.


Roatating a Game Object downward In my game I have a rocket which is traveling horizontally across the screen. What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect. How do I do this?


Offsetting ground texture doesn't work in WebGL so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving. The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again. heres the code attached to the ground to keep it offsetting constantly using System.Collections using System.Collections.Generic using UnityEngine public class Offset MonoBehaviour public float scrollSpeed public Material mat private float offset Use this for initialization void Start () mat GetComponent lt Renderer gt ().material Update is called once per frame void Update () offset Mathf.Repeat(Time.time scrollSpeed, 1) mat.mainTextureOffset new Vector2(offset, mat.mainTextureOffset.y) What may I be doing wrong, and how can I fix it? Thanks in advance!


How to check for mesh overlap? I'm creating a level editor in Unity. I need to detect when an object is intersecting another as I don't want to allow the user to place an object when it is colliding with something else. In the below diagam, there is a corner road piece and a tree. The dashed red line represents the mesh bounds of the road and the blue dashed line represents the mesh bounds of the tree. My current approach is to use Physics.OverlapBox with mesh.bounds. In the diagram, visually, it is clear that the tree does not overlap the road. However, the bounds do overlap, therefore I cannot place the tree there. Whats the best way to check if they are actually colliding in an efficient way? The level editor could potentially have thousands of objects. EDIT I have since tried using Physics.ComputePenetration. Primitive primitive checks work ok, primitive mesh collider checks work ok, but mesh collider mesh collider checks fail. From what I understand a concave mesh collider cannot interact with another concave mesh collider. Is there a workaround for this or must I momentarily make it convex before checking overlap? I just don't want to lose the accuracy of the concave collider.


Object pooling with collisions in Unity I am trying to create doodle jump like game with object pool for platforms. I have created an empty object with box 2D collider attached to it. This object moves with player and should be gathering platforms which exit its collider, but it isn't. public class PoolGrabber MonoBehaviour Tooltip("Field for game manager.") SerializeField private GameObject gameManager private void Awake() gameManager GameObject.FindGameObjectWithTag("GameManager") private void OnTriggerExit2D(Collider2D collision) if(collision.tag "PooledObject") collision.gameObject.SetActive(false) gameManager.GetComponent lt LevelGenerator gt ().objectPool.Add(collision.gameObject) It also doesn't work with OnTriggerEnter2D. I have also tried private void OnBecameInvisible() gameObject.SetActive(false) on a platform. Doesnt work either. I have discovered that for all those methods above object required to has Rigidbody2D component. But what if I don't want any phisycs calculations to be handled. I don't need physics on those platforms at all. Also, an object doesn't become invisible if you see it in the editor window. Isn't very convenient.


Custom 2D physics on unity I have seen a lot of people think that for a 2D platformer game, Unity2D physics is not really the best approach, and recommend implementing your own physics. I found the idea interesting, but I don't know how to approach the issue. Using 2D Rigidbodies, and setting them as kinematic, allows you to ignore unity's physics. But how would collisions be handled without relying on Unity collision system?


Frequent stuttering, high FPS spikes with VSync option turned on in Unity standalone build I'm experiencing an issue using Unity 4.3.2 and standalone builds. If I turn on VSync in the project's Quality settings, running the game at the native monitor resolution, I'll frequently get high framerate spikes (over 100FPS), and a strong stutter for a few frames, and then it drops back down to 60FPS and runs normally. If I run the game at a lower resolution (800x600 for example), the framerate stays at around 500FPS and the stuttering is consistent. However, if I turn off VSync in the Quality settings, and force it on in the Nvidia Control Panel, I don't experience any stuttering or framerate spikes, nor when I turn off VSync completely (but lots of screen tearing, which is very ugly and distracting). Can anyone explain this behavior? Is there anything that can be done to circumvent it? I'd imagine other Unity developers have used the built in Unity VSync with success before (or maybe not?!) so I'm hoping I'm just doing something wrong on my end.


Some UI button script not working in apk build! There are a lot of posts regarding this problem in various website and even in this one but no one has given a feasible solution to this problem. I have a button that has a custom sprite. I also have a custom script attached to that button which when pressed down (IPOINTER DOWN) changes the color of particular sprite renderer. All this works in pc but not on apk build. Why? I have two canvas, so I thought there might be raycasting issues, so I disabled one but still no luck. The buttons are in world space in canvas. So, I thought I might not use a canvas but IPointer only works on clickable UI elements. The scene looks like this, star is the clickable button and the borders are a sprite(district). The script attached to the button is using UnityEngine using System.Collections using UnityEngine.UI using UnityEngine.EventSystems Required when using Event data. public class OnHighlighted MonoBehaviour, IPointerClickHandler, IPointerDownHandler required interface when using the OnPointerEnter method. HoldByeach button private GameObject correspondingImage void Start () correspondingImage GameObject.Find(gameObject.name) public void OnPointerClick(PointerEventData pointerEventData) GetComponent lt Image gt ().color new Color32 (36,53,53,255) correspondingImage.GetComponent lt SpriteRenderer gt ().color new Color32 (36,53,53,255) public void OnPointerDown(PointerEventData pointerEventData) GetComponent lt Image gt ().color new Color32 (47,255,0,255) correspondingImage.GetComponent lt SpriteRenderer gt ().color new Color32 (47,255,0,255)


To split or not to split large 3D objects? I have a fairly simple question for which I'm seeking guidance Should large 3D objects be splitted into smaller ones? By wide, I mean an object that would be as wide as a game level is, below is some mountain, the first picture shows it as a single mesh, the second picture shows it as multiple meshes. Facts I've considered (might be wrong) a large object simplifies the scene hierarchy with less objects in total, but at the same time it might be rendered more often than necessary since it will be considered as visible a large object made out of smaller objects makes the scene hierarchy more bloated, but at the same time on a performance aspect is better since only visible parts of it by the camera will be rendered, the rest being culled Note, these objects aren't complex by today standards, that mountain is less than 1K triangles and a complete level is likely to be less than 30K triangles. Ideally, I would like to have the least amount of objects in the scene hierarchy to keep it simple, but at the same time I am wondering whether or not over simplifying the level might put extra problems on the table I haven't thought about.


How to select parent of currently selected object? When i select an object, i can't find a function to select its parent. Does this basic feature exist ? I want to select the parent of selected object and then step up to find parent of parent so on without using the hierarchy window.


Creating Unity Handles without any visible game objects at given regions I am trying to create handles without any visible game objects. The image below from a sample scene shows rects (top left rect is at position ( 2, 4), size is (1, 1)) of the handles I want to appear when the mouse is hovered over the rectangular areas. So basically in a scene with no game objects I want to be able to hover over with the mouse to show the squares below as handles. I believe the issue is most likely with the Raycast in UpdateHandlePosition(). The handles only appear when there are objects on the screen and they appear at the wrong places. Please see the relevant code below. static void UpdateHandlePosition() if( Event.current null ) return Vector2 mousePosition new Vector2( Event.current.mousePosition.x, Event.current.mousePosition.y ) Ray ray HandleUtility.GUIPointToWorldRay( mousePosition ) RaycastHit hit if( Physics.Raycast( ray, out hit, Mathf.Infinity, 1 lt lt LayerMask.NameToLayer( "Default" ) ) true ) Vector3 offset Vector3.zero if( EditorPrefs.GetBool( "SelectBlockNextToMousePosition", true ) true ) offset hit.normal CurrentHandlePosition.x Mathf.Floor( hit.point.x hit.normal.x 0.001f offset.x ) CurrentHandlePosition.y Mathf.Floor( hit.point.y hit.normal.y 0.001f offset.y ) CurrentHandlePosition.z Mathf.Floor( hit.point.z hit.normal.z 0.001f offset.z ) CurrentHandlePosition new Vector3( 0.5f, 0.5f, 0.5f ) static void DrawHandlesCube( Vector3 center ) Vector3 p1 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p2 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p3 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p4 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p5 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p6 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p7 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p8 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f You can use Handles to draw 3d objects into the SceneView. If defined properly the user can even interact with the handles. For example Unitys move tool is implemented using Handles However here we simply draw a cube that the 3D position the mouse is pointing to Handles.DrawLine( p1, p2 ) Handles.DrawLine( p2, p3 ) Handles.DrawLine( p3, p4 ) Handles.DrawLine( p4, p1 ) Handles.DrawLine( p5, p6 ) Handles.DrawLine( p6, p7 ) Handles.DrawLine( p7, p8 ) Handles.DrawLine( p8, p5 ) Handles.DrawLine( p1, p5 ) Handles.DrawLine( p2, p6 ) Handles.DrawLine( p3, p7 ) Handles.DrawLine( p4, p8 )


Unity Direct Compute Setting a struct of arrays The NVIDIA Direct Compute programming guide lists some best practices for memory management on the GPU. One tip they give on page 8 ("Structured Buffers") is to use a 'structure of arrays' (SOA) layout rather than the typical 'array of structures' (AOS) one struct Particle float4 position float4 velocity RWStructuredBuffer lt Particle gt particles vs struct Particles RWStructuredBuffer lt float4 gt position RWStructuredBuffer lt float4 gt velocity Particles particles (At least, as far as I understand) AOS layout seems to be the most popular (maybe even only) way to manage lists of stuff in the compute shader. I haven't found a way to implement SOA from the CPU side, Unity's ComputeShader.cs doesn't have a set struct function or similar. Does Unity expose a way to set SOA structs from the CPU side at all?


How can I trigger to start timeline using distance and not OnTriggerEnter Exit? using UnityEngine using UnityEngine.Playables public class GenericTrigger MonoBehaviour public PlayableDirector timeline Use this for initialization void Start() timeline GetComponent lt PlayableDirector gt () void OnTriggerExit(Collider c) if (c.gameObject.tag "Player") timeline.Stop() void OnTriggerEnter(Collider c) if (c.gameObject.tag "Player") timeline.Play() The idea is to create some kind of cut scene. Once the player (First person, in the screenshot i'm just showing the door on the left where the player will come from and the soldiers ) exit the door on the left and is in a specific distance from the soldier the first soldier the closet one will start moving to the player. Later I will make that it will change to close up view on the soldier with some text conversion. That's the main goal. But the script the original script by the unity tutorial is using triggers. I'm not sure if I should using this way or using somehow by calculating the distance between the player and the soldier to start the timeline ? And how to do it. After the soldier is moving walking to the player at some point I will make it to change to a close up view on the soldier with blurry background something like this But first how should I approach to the triggering part ?


Unity 5 Time Remaining displaying in scene but not in Game I'm currently learning game development in Unity from this course on Lynda.com. Currently I'm trying to displaying the time remaining in the game after it has been set to 5 minutes initially. When I look at the scene, I can see the text for the timer displayed in the top left corner of the canvas, but when I run the game, I'm not seeing it at all. I made a script for a game manager which is derived from a Singleton class. The game manager contains a private variable (and an accessor method) for the time remaining. I have another script that accesses the value for the time remaining and displays it on screen. In the Unity editor, I added a UI game object for the text box and then added the text box to the GUI representation of the timer label attribute. It seems like everything should be working but since I'm still very new to this, I'm probably missing something simple. Here is the code for both scripts GameManager.cs public class GameManager Singleton lt GameManager gt private float timeRemaining public float TimeRemaining get return timeRemaining set timeRemaining value private float maxTime 5 60 In seconds. Use this for initialization void Start () TimeRemaining maxTime Update is called once per frame void Update () TimeRemaining Time.deltaTime if(TimeRemaining lt 0) Now Deprecated Application.LoadLevel(Application.loadedLevel) SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) TimeRemaining maxTime UpdateUI.cs public class UpdateUI MonoBehaviour SerializeField private Text timerLabel Use this for initialization void Start () Update is called once per frame void Update () timerLabel.text FormatTime(GameManager.Instance.TimeRemaining) private string FormatTime(float timeInSeconds) return string.Format(" 0 1 00 ", Mathf.FloorToInt(timeInSeconds 60), Mathf.FloorToInt(timeInSeconds 60)) EDIT Canvas Settings in the inspector Image of the Time Remaining displayed in the scene


Agent trying to reach same position as other agents, instead start spinning in place I create units in my game and have a rally point where they should walk to when created, like Age of Empires. My problem is that since they compete for this position after a while, sometimes they end up doing this https gfycat.com decentquestionableandeancondor https gfycat.com densehonoredgalapagosalbatross As you can see one of the guys cant reach the rally point, so he starts rotating. I realize this has to do with stopping distance, but no matter how high I set the stopping distance this eventually becomes a problem when there are many enough units. And if I set it too high they dont walk to the rally point at all, since its not THAT far from the building they spawn from. Is there any way to manage this scenario? i.e just making him go as close as he can, and then stop? My AI Script using UnityEngine using UnityEngine.AI RequireComponent(typeof(NavMeshAgent)) public class BaseAi MonoBehaviour HideInInspector public NavMeshAgent agent HideInInspector public NavMeshObstacle obstacle float sampleDistance 50 Transform mTransform private void Awake() agent GetComponent lt NavMeshAgent gt () obstacle GetComponent lt NavMeshObstacle gt () mTransform transform private void Start() agent.avoidancePriority Random.Range(agent.avoidancePriority 10, agent.avoidancePriority 10) void LateUpdate() if (agent.isActiveAndEnabled amp amp agent.hasPath) var projected agent.velocity projected.y 0f if (!Mathf.Approximately(projected.sqrMagnitude, 0f)) mTransform.rotation Quaternion.LookRotation(projected) lt summary gt Returns true if the position is a valid pathfinding position. lt summary gt lt param name "position" gt The position to sample. lt param gt public bool SamplePosition(Vector3 point) NavMeshHit hit return NavMesh.SamplePosition(point, out hit, sampleDistance, NavMesh.AllAreas) public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false public void Teleport(Vector3 point) agent.Warp(point) lt summary gt Return true if agent reached its destination lt summary gt public bool ReachedDestination() if (agent.isActiveAndEnabled amp amp !agent.pathPending) if (agent.remainingDistance lt agent.stoppingDistance) if (!agent.hasPath agent.velocity.sqrMagnitude 0f) return true return false public void ToggleObstacle(bool toggleOn) agent.enabled !toggleOn obstacle.enabled toggleOn void OnDrawGizmos() if (agent null) return if (agent.path null) return Color lGUIColor Gizmos.color Gizmos.color Color.red for (int i 1 i lt agent.path.corners.Length i ) Gizmos.DrawLine(agent.path.corners i 1 , agent.path.corners i )


Unity Assets folder is empty after opening package from the asset store I downloaded the following Survival Shooter Tutorial from the Asset Store https www.assetstore.unity3d.com en ! content 40756 I was prompted to open it in Unity so I did and began following this tutorial https www.youtube.com watch?v lP6epjupJs I am only 2 minutes into the first video and am stuck. In the tutorial there are lots of folders in the assets folder. I took a screenshot of what my screen looks like to show that it is empty.


How to run different animations with same suffix for different public objects? I would like to be able to run the corresponding animation (ending with "Get" in the title) for whatever item GameObject I plug into this treasurebox. I made 2 prefabs for "item get" animations today. Both GameObjects consist of 3 sprites The image representing the item, and 2 lightray images that I enable disable in alternation to get a halo effect (see animation below). You can see the 2 prefabs and their corresponding animation components in the Project panel These next two images show how similar the animations are they even both require two of the same sprites, flareA and flareB. Here is the code I am currently using to set the state of the ItemBox GameObject and run the animations. You can see that while the itemGet prefab is public (that is, I can plug in whatever gameobject I want in the editor), line 27 explicitly calls for the animation belonging only to the turd item. using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject itemGet null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(itemGet, transform.position new Vector3(0, 0.375f, 0), Camera.main.transform.rotation) itemClone.GetComponent lt Animator gt ().Play("turdGet") Destroy(itemClone, 1.6f) disabled true How can I change line 27 (the line before 'Destroy') so that it runs the appropriate " Get" animation for whatever itemGet object I plug into the inspector? I think I am already close. I intend to make more items (not too many for now) and the animation I want to play will always be structured like "Get". UPDATE 07 29 19 I tried making a public AnimationClip object in the ItemBox script and putting that name in quotes for line 27 and thw script still works, but now I get an index error saying the animation state was not found. I don't think I can plug the name of the public variable into the .Play("") quotes and make it work I think it only worked because there is only one animation for that item anyway. I ended up removing this new variable and just keeping the .Play("") part as empty quotes and it still works. I might decide to add more animations to these item objects later so I still need to know how to specifically play the animation that ends in "Get".


Play two different audio sources depended on code behind How can I play two different audio clips in Unity depended on the code behind? Into my object I've added two audio sources namely 'Player GunShot' and 'outOfAmmo'. Into the same object I've also added a C script whit this code public currentBullets 1 private AudioSource gunAudio private AudioSource outOfAmmo void Awake() gunAudio GetComponent lt AudioSource gt () outOfAmmo GetComponent lt AudioSource gt () void Update() if (currentBullets 0) outOfAmmo.Play() else gunAudio.Play() Can this code give any problems because in the Awake methode? I've not defined with audio source the variable must be. So which source go he take to play?


How do I know the data has arrived at server without requesting every frame of the game? I have a game where I have to get data from the server but the problem is I don't know when the data will become available on server. So I decided to use co routine and hit server at after specific time or on every frame. But certainly this is not the right, scale able and efficient approach. Now my question is that how do I know that data has arrived at server so that I can use this data to run my game. Or how should I direct the back end team to design the server in an efficient way that it responds efficiently. Our back end team currently uses REST Web services with JSON with Python. And they want to push data to my unity player without my frequent requests.


Unity c Interface object never equals null I've created an interface class for some mechanic I'm using to interact with things in my game. Now, I noticed that checking if that value is null never returns true. Here's a screenshot of where this happens The error I get is the following MissingReferenceException The object of type 'InteractiveItem' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. InteractiveItem.CurrentGameObject () (at Assets Scripts Interactive InteractiveItem.cs 10) Interactive.ManualStopInteract () (at Assets Scripts Interactive Interactive.cs 30) The line where this fails is if (IsInteracting() amp amp this.interacting.CurrentGameObject().GetComponent lt InteractiveUtilityChest gt () null amp amp !MainReferences.UIReferences.IsAnyMenuWindowOpen()) do something The IsInteracting() check is for some reason returning true here because the last line (InteractiveItem.cs 10) is in the method interacting.CurrentGameObject() I don't get how this can happen or how I should solve it. As far as I know, an interface is a nullable type.


Follow behaviour with transform.LookAt on Unity2d So i've been trying to make an enemy follow my player on Unity2d using transform.LookAt. While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas? follows player transform.position Vector2.MoveTowards(transform.position, target.position, speedEnemy Time.deltaTime) make enemy look towards player transform.LookAt(target)


Unity add InputTracking to my script I'm new to unity and 3D world developement so I'm following Unity's tutorial for beginners right here. And I'm in the section with title "Camera Nodes" where they gave me a c script to attach it to the camera object. I did attach it to the camera but the problem with the script when I debug it I get an error of undefined class The name 'InputTracking' does not exist in this context And this is the script using System.Collections using System.Collections.Generic using UnityEngine public class UpdateEyeAnchors MonoBehaviour GameObject eyes new GameObject 2 string eyeAnchorNames "LeftEyeAnchor", "RightEyeAnchor" Use this for initialization void Start () Update is called once per frame void Update () for (int i 0 i lt 2 i) If the eye anchor is no longer a child of us, don't use it if (eyes i ! null amp amp eyes i .transform.parent ! transform) eyes i null If we don't have an eye anchor, try to find one or create one if (eyes i null) Transform t transform.Find(eyeAnchorNames i ) if (t) eyes i t.gameObject if (eyes i null) eyes i new GameObject(eyeAnchorNames i ) eyes i .transform.parent gameObject.transform Update the eye transform eyes i .transform.localPosition InputTracking.GetLocalPosition((VRNode)i) the error is this line eyes i .transform.localRotation InputTracking.GetLocalRotation((VRNode)i) and this one This is the link of the class InputTracking in Unity's API, but I don't know how to add it to my script ) Thanks in advance.


how are semantics used when declaring a struct? I don't understand how semantics are used in shaders. While reading Unity's shader tutorials, I come across this struct v2f float worldPos TEXCOORD0 half3 worldNormal TEXCOORD1 float4 pos SV POSITION and also this struct v2f float3 worldPos TEXCOORD0 half3 tspace0 TEXCOORD1 half3 tspace1 TEXCOORD2 half3 tspace2 TEXCOORD3 float2 uv TEXCOORD4 float4 pos SV POSITION Microsoft's documentation says A semantic is a string attached to a shader input or output that conveys information about the intended use of a parameter. I know there is some kind of interpolation of data because vertices and pixels aren't one to one, thus I think semantics are used for telling the graphics library what to do about the data. But here it uses TEXCOORDX for things like world position and tangent space vectors. They don't seem to have anything to do with UV coordinates. So how are these semantics actully used?


How can I make the gun rotate and shoot like lost control and shooting all around? The shooting part I will make later. Now I'm trying to make the rotations part. The first thing I did is to rotate the gun barrel and this is working fine. The next thing I want to do is to rotate the gun body 360 degrees randomly so when the gun will shoot it will shoot randomly all around like lost control. This is a screenshot of the gun barrel And the gun body By rotating the gun body 360 degrees randomly I want to create a lost control effect so it will shoot all around hitting randomly. The script is attached to the top parent Drone using System.Collections using System.Collections.Generic using UnityEngine public class Rotate MonoBehaviour public Transform wings public Transform propellers public Transform gunBarrel public Transform gunBody public float propellersSpinSpeed 50 public float wingsSpinSpeed 50 public float gunBarrelSpeed 50 private float angle 360.0f Start is called before the first frame update void Start() Update is called once per frame void Update() for (int i 0 i lt propellers.Length i ) propellers i .Rotate(0, propellersSpinSpeed Time.deltaTime, 0) for (int i 0 i lt wings.Length i ) wings i .Rotate(0, wingsSpinSpeed Time.deltaTime, 0) gunBarrel.Rotate(0, 30 gunBarrelSpeed Time.deltaTime, 0) gunBody.Rotate(Vector3.zero, angle Time.deltaTime 1.0f) I tried to do gunBody.Rotate(Vector3.zero, angle Time.deltaTime 1.0f) But it does nothing not rotating it 360 degrees and I didn't use yet the Random. The gun barrel keep rotating but the lost control shooting all around is not working yet not sure how to do it. Update This is the current code using System.Collections using System.Collections.Generic using UnityEngine public class Rotate MonoBehaviour public Transform wings public Transform propellers public Transform gunBarrel public Transform gunBody public float propellersSpinSpeed 50 public float wingsSpinSpeed 50 public float gunBarrelSpeed 50 Start is called before the first frame update void Start() Update is called once per frame void Update() for (int i 0 i lt propellers.Length i ) propellers i .Rotate(0, propellersSpinSpeed Time.deltaTime, 0) for (int i 0 i lt wings.Length i ) wings i .Rotate(0, wingsSpinSpeed Time.deltaTime, 0) gunBarrel.Rotate(0, 30 gunBarrelSpeed Time.deltaTime, 0) gunBody.localEulerAngles new Vector3(Mathf.Clamp(gunBody.localEulerAngles.x, 0f, 90f), 0, 0) The gunBody is now facing down. This is a screenshot of what I want the gunBody to do I changed the gunBody on X and Z rotations a bit and this is the behaviour I want it to do randomly rotating on X and Z but not to pass too much up down and left right degrees. The Z to be in range more or less 150, 205 and the X range of 55,100 And make it moving smooth randomly on this ranges. I'm not sure to the float point if those are the ranges but more or less this is what I mean by randomly moving in circles 360 degrees shooting all around like lost control. Same behaviour of a turret trying to shoot on target and rotate 360 degrees in any direction the same thing here but only looking forward not backward. This is the logic I mean moving in circles and shooting around to the front.


How do set a layer on an ECS entity? I'm using Unity ECS entities to draw out some tiles. I would like to determine the layer (or sortOrder) of the rendered tile so that if a tile is placed over another at the same position, the tile with the higher layer value will be visible. It appears random at the moment. I tried entityManager.SetSharedComponentData(entity, new RenderMesh mesh mesh, material mat, layer level ) But it didn't seem to do anything.


Coroutine wrong Behavior when scene is loaded. Ok so I have this coroutine IEnumerator ShowCharTraits() while(!hasPlayerChosen) yield return null traitPanel.SetActive(true) hasPlayerChosen false traitPanel.SetActive(false) Debug.Log("Got called! job done") It's being called like this from the awake method in my GameManager players GameObject.FindGameObjectsWithTag("Player") foreach (GameObject g in players) ui Controller.StartShowCharTraits() g.GetComponent lt PlayerToken gt ().isTurn false StartShowCharTraits() is a simple method that does this public void StartShowCharTraits() StartCoroutine("ShowCharTraits") Now, I have checked the tags, no null reference exception, actually no errors or warnings are being thrown. If i load the scene in the editor and then play it everything works fine. traitPanel.SetActive(true) get called and my panel shows up. However when I load my scene from another scene using SceneManager.LoadScene(1) the above mentioned line is never reached. Any ideas why this is happening ?


Moving the rendered object the projection perspectives based on an AR marker I saw this video and now I am trying to making it. I have used Vuforia AR Camera Pulgin, and so far tracked the image on a marker but the problem is getting the four projections of the 3D object on a screen. Here is an example of what it looks like. I have used Viewport Rect method with four cameras but that does not seem to change the projections as I move the marker.


How can I make an infinte terrain with object pooling in Unity? I am currently making a 3D endless runner game in unity in C . I now need to make the platform(3D Tiles) infinite but I don't know how. I already did some research but I don't find the right tutorial. I already asked a similar question and I got the answer that I need to do it with object pooling but I don't find any good tutorial for object pooling. Does someone know how to make an infinite terrain with object pooling in unity? Thanks using System.Collections using System.Collections.Generic using UnityEngine public class TerrainScript MonoBehaviour public GameObject tilePrefabs public Transform playerTransform private float spawnZ 4500.56f private float tileLength 2.0f private int amtOfTilesOnScreen 2 void Start() for (int i 0 i lt amtOfTilesOnScreen i ) SpawnTile(0) void Update() if (playerTransform.position.z gt (spawnZ amtOfTilesOnScreen tileLength)) SpawnTile(0) private void SpawnTile(int prefabIndx 0) GameObject go go Instantiate(tilePrefabs prefabIndx ) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward spawnZ spawnZ tileLength


How to program (architecturally organize) a set of customizable changes to a game? The floor of my game (tower defense) is composed by a set of cubes. I wish to change these on some of the waves. I have a list of the changes that need to be made on each wave in a floorController class. However, in order to decide which floor cubes should appear or disappear on each round, I had to assign each cube a bool for each wave (if this is set to true the floor changes in that wave). However this process is tedious and not ease to change and customize in order to experiment with the level. From an architectural programming perspective how can I better structure this system?


Unity GUITexture or GUIText not showing up Currently I've got a little 2.5D platformer with the camera tracking the player. Now when I go to insert a GUITexture or GUIText game object into the scene, it comes up absolutely fine in the Editor view, but when I go to play it there's absolutely nothing to be seen! At first I thought it may have been a script I was using on the GUI, but I've tried it out with a completely bland GUITexture object that has no interaction with the rest of the game and I still get the same effect. I'm wondering if my camera is messing it up somehow, but I assumed that all GUI objects are drawn to screen space and just stay with the camera. I've been really stuck for the past few hours so if any one could offer some insight, I'd be very, very grateful! Ray


Why does my gameobject fly of into the air when the screen is touched? I am encountering a peculiar problem when updating a piece of code that translates my gameobject left and right based on mobile touch input. To provide context, the platform upon which the gameobject, which is a sphere in my case, translates, is this The platform is 10 units wide, with the sphere in the center. In its original form, the code looks like this void FixedUpdate () if(Input.touchCount 1) float touchXComponent Input.GetTouch(0).deltaPosition.x transform.Translate(Vector3.right Time.smoothDeltaTime touchXComponent 0.5f) It provides the desired left and right movement, but it has a tendency to allow the ball to leave the platform, and then start moving up and down in the air with each further touch. To combat that, I tried editing the code as follows void FixedUpdate() if (Input.touchCount 1) float touchXComponent Input.GetTouch(0).deltaPosition.x transform.Translate((Vector3.right Time.smoothDeltaTime touchXComponent 0.5f).x, transform.position.y, transform.position.z) This, however, causes the ball to fly of the screen the second it is touched, leaving me with this error in the console Assertion failed Invalid worldAABB. Object is too large or too far away from the origin. I would have thought that the update I made to the code would keep the ball stationary on the y and z axes, while allowing it to translate freely on the x axis. Why is that not the case? Thank you.


How to return the scene view camera to the default view By the quot scene view camera quot I don't mean a GameObject with a Camera component, I mean the camera used to draw the Scene window in the Unity editor, controlled by this quot Scene Gizmo quot widget The default view shows an almost isometric perspective, where all three X Y Z axes are visible. But when I clicked the green Y cone, my view changed to look straight down the Y axis, and I can't seem to return to the 3 axis view. Clicking the other cones on this widget just switchest to look along the X or Z axis instead, and clicking the cube in the middle or the quot Top quot label just toggles between orthographic and perspective projection. How can I get back to the default 3 axis view?


Movement in grid in Unity I am a beginner at Unity. I want to make a game like Lightbot, but in 2d (without the z axis movement) with some obstacles. Before making the function system of the Lightbot, I want to make the in game character move on a grid by the set of key inputs (e.g. WASD) by the player. But I'm stuck here. I searched on Tilemap which makes a grid, but I have no idea how to save the set of input keydowns and move my character on this grid at once. Suppose my character is on the (0, 0) square for example. After the player taps WWDD, then my character should move to the following squares, in the following order (0, 1) (0, 2) (1, 2) (2, 2) How can I achieve my goal?


Would landscape left right make difference when developing Google VR CardBoard Game with Unity? I'm trying to make a simple VR cardboard game using Google VR SDK for Unity. I'm really confused about the problem as my title. Will the values got from GvrViewer.Instance.HeadPose.Orientation.x change when the orientation of smartphone change from Portrait to Landscape Left Right? The following code works in Unity demo (after press play button and use alt right click to trigger head movement simulation), but I don't have a cardboard so I'm not sure whether it will still work on smartphone with landscape left or right attached to a cardboard. private void Update() forward if the value is positive. float forwardValue GvrViewr.Instance.HeadPose.Orientation.x turn left if the value is negative. float turnValue GvrViewr.Instance.HeadPose.Orientation.y private void Move() Vector3 movement transform.forward forwardValue m Speed Time.deltaTime Apply this movement to the rigidbody's position. m Rigidbody.MovePosition(m Rigidbody.position movement) private void Turn() Determine the number of degrees to be turned based on the input, speed and time between frames. float turn turnValue m TurnSpeed Time.deltaTime Make this into a rotation in the y axis. Quaternion turnRotation Quaternion.Euler(0f, turn, 0f) Apply this rotation to the rigidbody's rotation. m Rigidbody.MoveRotation(m Rigidbody.rotation turnRotation)


How do I convert distance covered from meters to kilometers, in Unity? I am developing a game in Unity where I have to find a distance in kilometers, to find a passenger's fare based on the covered distance. This is what I have tried private Vector3 previousPosition public float cumulatedDistance void Awake() initialize to the current position previousPosition transform.position Update is called once per frame void Update () cumulatedDistance (transform.position previousPosition).magnitude previousPosition transform.position How can I determine the distance covered, and convert it to kilometers?


Is Godot's NavMesh viable for dynamic pathfinding (e.g. avoiding moving enemies)? I am a novice (read low budget) designer looking at moving from Pygame to a real engine, and between Unity and Godot it looks like the latter has a much better 2D engine 1, 2, 3 . I would be happy to support Godot's open source model except that, as far as I can tell, its built in navigation mesh is purely static i.e. it can't update its path to account for dynamic obstacles 4, 5 while Unity's pathfinding system can 6 . So my question is Am I "stuck" with Unity? Or is there functionality that I haven't yet been able to find? Or, alternatively, is GDScript significantly faster than Python such that basic algorithms like fixed grid A would do the job? Edit By "stuck" with Unity I don't mean that it's a bad option or that there aren't good options I mean, 'if I need good pathfinding, do I have to give up on Godot and use what would otherwise be a second choice engine?'


Unity, OnMouseOver blocked by another gameobject with a collider in front of it I have two gameobjects, both with 2D colliders. One of them can be behind the other, and because of this its OnMouseOver can be blocked from firing as the GameObject in front blocks it from triggering. What is a way around this? I really like the ease of using OnMouseOver, and would rather not use raycastAll. Asked this question on SO, maybe it should be asked here.


How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object? I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have void Start () Color newShirtColor shirtColor Random.Range(0, shirtColor.Length) MaterialPropertyBlock props new MaterialPropertyBlock() props.AddColor(" Color", newShirtColor) GetComponent lt SkinnedMeshRenderer gt ().SetPropertyBlock(props) It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section?


Switching between world and battle scene with no or minimum loading? I am making a strategy game where the player roams a grid map. When the player encounter enemy on the map he is transferred to a quot battle quot scene where two armies are fighting in turn based battle. Imagine Heroes 3 like game. My question is Should I load the battle scene in additive mode and temporary hide the quot world map quot and when the battle is finished to just show the quot world map quot and hide the quot battle quot scene? Or i should unload the world scene and load the battle scene, and when the battle is over gt unload the battle scene and load the world scene ? I think the 1st approach will give me less loading time between the two scenes, but will require more RAM ? Second approach is standard one, but i will have loading between the scenes ? My idea is to have no or minimal loading between battle and world scenes. What do you guys thing ? Did you know what is the best practice in this case ? By the way, i am using Unity as a engine.


How to make a changeable color constant for editor materials? Due to the nature of a project I'm working on, the models I got have a bunch of redundant materials on them. I have to fiddle around with some of the colors, but every time I want to change the colors, I have to change each material to the exact same color. Is there any way to declare some kind of swatch that I can change and have those changes just apply to the materials or anywhere else? For instance, in code, you'd just make a readonly Color mainColor, that you'd use wherever you need and could change at will. I'm looking for this kind of behavior in the editor itself.


Rigidbody2D loses speed on collisions I'm trying to create a simple Breakout style game. In my game, the ball strikes a paddle that moves with the player's mouse. Depending on the position of the strike, the ball changes its direction. This allows the player to aim the ball. The problem I'm having is that each time I set the position, the ball loses velocity. I've tweaked every Physics2D setting I could find, but I'm not seeing any changes. Here's what my Ball class looks like using System.Collections using System.Collections.Generic using UnityEngine public class Ball MonoBehaviour public float initialVelocity public float collisionAngleRange public Paddle paddle private Rigidbody2D body public void Start() body GetComponent lt Rigidbody2D gt () body.velocity VectorUtilities.AngleToVector2(135) initialVelocity When colliding with the paddle, use the position of the strike to adjust the ball's position. public void OnCollisionEnter2D(Collision2D collision) Ignore the object if it's not the paddle. if (!collision.gameObject.CompareTag("Paddle")) return Get the collision coordinates Bounds bounds collision.gameObject.GetComponent lt BoxCollider2D gt ().bounds float left bounds.min.x float right bounds.max.x Vector2 contact collision.contacts 0 .point Interpolate the contact point and determine the angle. float interpolation (contact.x left) (right left) float angle 90 collisionAngleRange 2 collisionAngleRange (1 interpolation) Change the direction of the ball without affecting its speed. body.velocity VectorUtilities.AngleToVector2(angle) body.velocity.magnitude Log what's happening with the velocity Debug.Log(body.velocity.magnitude) The VectorUtilities class looks like this using UnityEngine A set of utility methods and extensions for Vector2 and Vector3. public static class VectorUtilities public static Vector2 AngleToVector2(float degrees) return new Vector2(Mathf.Cos(degrees Mathf.Deg2Rad), Mathf.Sin(degrees Mathf.Deg2Rad)) Here are my Ball game object's Rigidbody2D and CircleCollider2D settings The paddle's settings The material settings Physics2D settings I recognize I could solve this problem by multiplying the ball's normal vector by my desired speed, but it's more important to me to understand why this is happening and to fix the underlying problem. Why does the ball lose speed on every collision, and how can I prevent that from happening?


Screen Space vs World Space Canvas When should I use one over the other? I'm pretty sure I understand the key differences, but I'm not sure which use cases would prefer one over the other. For example, let's say I have objects on the ground in my 3D game and they have UI Images above them with the objects' names. Which method is better? Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff?


Smooth rotation Unity3d I have an animation and I modified some rotations of some bones in the animation at a certain frame. What I want to do is how to make the animation in the next couple of frames interpolate smoothly so that the changes I made looks smooth? Like for example, if I have an animation of a game object, and in frame number 100 it rotated 90 degree in the x direction. So now frame 100 has a modified rotation angle of the object, but frame 101 has the original animation. I want to smooth the rotation so that the transition of the obect from the modified frame back to the original animation looks smooth.


Unity Running code on the "Create Other" menu? Right now I am trying to create a TextMesh GameObject from code. The graphics primitives are accessible through PrimitiveTypes, I'm thinking there must be something similar, and if not, I could at least run whatever static function is bound to the menu if only I knew the name. The more general question is "how one get at all the other items on the "Create Other" without using the menu itself?"


Should I calculate in meters or pixels In my car sim I am doing my calculations in Standard Units, except for the distance which is in pixels. Is this still correct (my guess is no) or should I use Meters ? If I should use meters what is the best way to go about it? should I just pick a scale 10px 1m or is there a better way to do this ? thanks in advance. Some additional info I'm using Unity3D and using its physics engine.


Combat System Class Objects as Package and Listener So I've been trying to map out a combat system and I have an idea I'm laying out that I'm looking for a sanity check on, as well as suggestions. The idea is that all things that can do damage (weapons, spells, environmental traps, monsters that deal damage sans weapon) will have a CombatTalker() object attached that will contain information about the amount of damage and damage types (fire, frost, physical, magical, etc.), modifiers that it might have, and any special effects (apply DoT, blind, slow, etc.). Everything that can take damage will have a CombatListener() object that takes that information and transmogrifies it with the receivers resistances and any special properties it may have. The CombatTalker() will create a CombatPackage() from a collection class any time there is a collision, and send it to the CombatListener() on the collided objects, supposing it has one. The CombatPackage() is basically the raw data about the damage and effects. The CombatTalker() is a wrapper of sorts that generates the CombatPackage() based on the weapon (or whatever) base damage, then the specific details of that individual weapon, and sends it (like a network packet) to the CombatListener(). The CombatListener() unwraps the package, and in reverse applies the resistances then applies any relevant damage and effects. I know some of that was slightly repetitive, but I was trying to outline the idea completely, which apparently took two paragraphs. I know this might be slightly complex, but the creatures and players and weapons and spells can change over time, so there isn't just a pool of static data that can be attached to the item. It needs to be able to read stats from JSON, apply specific information about the damage and send it. The same goes on the other side in reverse. Is there a reason that this is "too complex"? Am I considerably overthinking it, or is this a reasonable method for a combat system? Thanks!


Loop in coroutine stops after going halfway I have a very weird problem with a particular loop in a coroutine public IEnumerator DestroyCubesGameOver() var startingCubeHolder GameObject.FindWithTag("StartingCubeHolder") DestroyOutOfCameraCubes() Debug.Log(cubeGroup.transform.childCount) for (int i 0 i lt cubeGroup.transform.childCount i ) Debug.Log(i) Destroy(cubeGroup.transform.GetChild(i).gameObject) yield return new WaitForSeconds(0.001f) Destroy(startingCubeHolder) The loop starts doing its thing and it needs to do it 100 times for example. However it stops after going about halfway and after destroying about half of the objects. Even if I increase the delay for each repeat it still does the same exact thing needs to repeat itself and destroy 100 objects, ends after destroying just 50. What is causing this? Edit If I make it just a void method it destroys all of the objects. Edit 2 This loop was initially a foreach but I rewrote it to try the other way same thing.


Why can't I expose a Plane variable in my unity script? I've got a script which creates raycasts. I wanted to use the (presumably less expensive) Plane.Raycast rather than the GameObject.Collider.Raycast (because the gameobject one has a distance parameter so that's one more check) I can expose the plane gameobject in my scene easily by simply making a public gameobject variable like this public GameObject floor however when I turn it into this public Plane floor It doesn't expose in the scene. Why is this?


Unity Problems with scene object orientation and rotation after updating my project from 5.0.0 to 5.2.2 Last year I made a large project on Unity 5.0.0, today I re opened it on 5.2.2 to do some work on it. I was given the message that the project needed to be updated, I allowed it to do the update. Now when I open up my scenes, many of my scene objects are misplaced, the rotation is completely wrong and positioned in the wrong place. My scenes are of a refinery and the most commonly broken object is the pipework, something that would take hours to correct manually. My pipework is created this way... All pipes are made in blender and each scene's pipes are saved as a single blender model (with each pipe make from a bezier curve and left as a separate object). Once imported into Unity (as a single .blend file), I've then dragged and dropped coloured materials onto all the individual pipes, so they are all coloured correctly. This has all been fine until updating the project to 5.2.2 now some of the pipes are in the right place, but many are rotated in completely the wrong direction, leaving it looking a mess. If I delete the pipes from Unity and reimport the pipe model back in, this would solve the problem, but then all the materials colours will be gone. Due to the sheer amount of pipes throughout the whole project, to re colour them all again would be an extremely problematic task, especially as it's critical that the pipes are the right colour. I am confused how some of the pipes within the same pipe model are fine and the others are wrong, it would be so much easier to sort if they had all changed rotation together, then I could just switch them all back in 1 go. I have a total of 13 scenes and so far all of them have suffered the same problem. Nothing whatsoever has been changed on any of the scenes, assets or indeed anything in the project folder. In fact I haven't touched a single file within the project since October last year, so it is certainly to do with updating to 5.2.2. Is there anything I can do to fix the problem without having to re import the models back in or manually rotate everything back? I have attached some screenshots to show the issue See how in the blender image, all the pipework is placed correctly and then in the Unity image, half the pipes have flipped and are facing the wrong way. I have removed the ground so this can be seen clearer. Any help would be much appreciated. Many thanks


How can I make the camera to rotate from side side but in static movement range? I mean for some reason now the camera is rotating to the left and to the right but sometimes it's rotating to one of the sides a lot I mean a very sharp angle and sometimes less rotation. How can I control how much rotation will be from side to side by degrees ? using UnityEngine using System.Collections public class scr camera MonoBehaviour public float rotate amount Use this for initialization void Start () Update is called once per frame void Update () transform.rotation Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) rotate amount) transform.eulerAngles.y, transform.eulerAngles.z) Sometimes cam14 make almost 240 even close to 300 degrees rotation to one of the sides sometimes less. The rotation is not equal to both sides. I want simple rotation to both side just to see the room and not the walls behind the camera. In this case I set the rotate amount to 7 so it will rotate faster.


Unity Blend tree weird transition I have duplicated the blend tree from the ThirdPersonCharacter (Ethan) which comes with the Standard Assets package. In the duplicate I went into the blend tree and swapped out the walk animation "HumanoidWalk" with my own animation named "walk", but now I get a weird transition from the animation "walk" to "HumanoidRun". Both animations, my walk animation and the original "HumanoidWalk" are root animated and look similar they have around 1.5 velocity both and same frame length. Animation Settings I created the animation in blender, you will see in my video below that the animation itself runs smooth and as it should, but the transition to HumanoidRun is very weird for unknown reasons. I am using a custom metarig armature which comes with the blender add on "rigify", I deleted some bones on the finger, but the avatar has a check and is ok (no warnings either). Rig Settings Player settings I basically "copied" all the components from Ethan (ThirdPersonController) and only changed the Animator Controller and the Capsule Collider settings to match the model. I made some short videos where you clearly see the problem, it happens if the parameter Forward is at about 0.6 0.8. https youtu.be Q T7FplDxLE https youtu.be nrJNeo1ltsg NOTE First I am demonstrating how it looks with the normal animations, then I add my own. What am I doing wrong? More Infos I just baked the walk animation in blender and exported it to unity again, but this made no difference. I tried to export it from blender as FBX, it made no difference. However, I noticed that the import is happening much faster and applying in unity importer is very fast now.


How to make player stay on a moving object I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window. Thanks, Nova


Can a UIKit application co exist with a Unity game as a single application? I have a typical UIKit application with three buttons one opens an RSS feed in a UITableView, the second opens some kind of gallery view, and the third opens a Unity 3D game. Is it possible and how easy it is to support both in one application?


Having trouble making game time pause and unpause I've been trying to make it where when the player does a certain task, the game's time will pause. When the player does another action, the game's time would unpause and continue. I had my code like so using UnityEngine using System.Collections using UnityEngine.UI public class timeScript MonoBehaviour uGUI Items public Text date public Text playerCash Times public static int week public static int month public static int year 1980 amount of cash public static int myCash 10000 public AlertBox alert public Text timeText bool timeActive true int time int day void Start() InvokeRepeating("Timer", 0, 1) public static void Timer() timeText.GetComponent lt Text gt ().text "W" week.ToString() "" year.ToString() playerCash.GetComponent lt Text gt ().text " " myCash.ToString() region YEAR Check if month equals 13 (allows for 12th month to be counted) if (month 13) year month 0 endregion region MONTH Check if week equals 5 (allows for 5th week to be counted) if (month 5) month week 0 endregion region WEEK Check if day equals 8 (allows for 7th day to be counted) if (day 8) week day 0 endregion region DAY Check if Time equals 5 (allows for 4 seconds) if (time 2) day time 0 else time endregion I tried using CancelInvoke(timeScript.Timer()) in another c file but all it did was give me an error that stated I couldn't convert from string to void.


System.Runtime.Serialization.SerializationException while trying to deserialize List I'm trying to serialize deserialize a class that holds inventory items. The code is attached below. First I call AddOne() void a few times, then I call SaveFile(), then I call LoadFile(). In LoadFile() the following error occurs ex "System.Runtime.Serialization.SerializationException End of Stream encountered before parsing was completed. r n at System.Runtime.Serialization.Formatters.Binary. BinaryParser.Run () 0x00288 in lt 1f0c1ef1ad524c38bbc5536809c46b48 0 r n at System.Runt... Does anybody see my mistake? Thank you for the help! using System using System.Collections using System.Collections.Generic using System.IO using System.Runtime.Serialization.Formatters.Binary using UnityEngine public enum Type undefined 0, Pistol 1, Magnum 2, Grenade 3, BlendGrenade 4, FireGrenade 5, PistolAmmo 6, MagnumAmmo 7, Rifle, RifleAmmo, System.Serializable public class Inventory MonoBehaviour public class InventoryItem public int Amount 0 public int Row 0 public int Col 0 public int Rotation 0 public Type ItemType Type.undefined public List lt InventoryItem gt Items public void Start() Items new List lt InventoryItem gt () public void AddOne() InventoryItem n new InventoryItem() this.Items.Add(n) public void SaveFile() string destination Application.persistentDataPath " save3.dat" if (File.Exists(destination)) File.Delete(destination) using (Stream stream File.Open(destination, FileMode.Create)) BinaryFormatter bin new BinaryFormatter() bin.Serialize(stream, this.Items) public void LoadFile() string destination Application.persistentDataPath " save3.dat" using (Stream stream File.Open(destination, FileMode.Open)) BinaryFormatter bin new BinaryFormatter() try this.Items (List lt InventoryItem gt )bin.Deserialize(stream) catch (Exception ex) Debug.Log(ex.ToString())


Editor Window How to create this? I am trying to create this in my editor window but not sure how. Basically a drop down arrow, next to a C icon, next to a toggle, next to a Label with a cog at the end


How can I use Body tracking in Android using ARCore or some other libraries? I know that ARCore on Android doesn't support Body Tracking like ARKit does. But is there some alternative or workaround to achieve it? Some other SDKs or Libraries or maybe even if there is some way to do it through ARCore itself? To make it clearer I plan to use something like this in an AR game for Android. I plan to develop it in Unity 2019.4.x. My search result in Google didn't yield a useful result as it gets mixed with ARCore Motion Tracking (which isn't what I am talking about here) or implementation with ARKit. But I got a little hope that there might be some way out after reading this post on Unity Forums.


Unity's Animator.GetBehaviour always returning null I have the following line As you can see "transitionOutAnimator" is null before the line runs. transitionOutAnimator is a StateMachineBehaviour of type ThoughtBubbleTransitionOutAnimator. We can check that the StateMachineBehaviour of the correct type is actually stored in the run time animator Yet when the line runs Am I doing something obviously wrong? Is this a bug? I have another identical instance in the code where I do this, and it works perfectly. EDIT Immediate window EDIT This is still a problem as of Unity 5.3.5f1.


Camera not following ragdoll in unity I have made a ragdoll and attached (as child object) the main camera to it, but the camera doesn't follow the ragdoll. Why is this happening? And how do I fix this?


Why do my trees share the same health? My trees keep on falling at the same time and I am not sure why! I am new to Unity3D javascript. Here is my script pragma strict INTS var health 5 GAMEOBJECTS var tree GameObject var log GameObject function Start () tree this.gameObject function Update () if(Input.GetKeyDown(KeyCode.Mouse0) amp amp Player script.axehave amp amp health gt 1 amp amp Camera script.tree) health 1 if(health 0) tree.GetComponent. lt Animation gt ().Play() Destroy() function Destroy() yield WaitForSeconds(2) Destroy(tree.gameObject)


How can I change the splash screen for a standalone game in Unity3D? I want to change the normal Unity splash screen to be customized for my game and every time I change the splash image in the player setting it does not appear. So how can I do that please?


How do I enable and disable objects with a certain tag in C ? I have a script that is supposed to find every active object with a certain tag and on the push of a button enable and disable it's meshrenderer and collider. but the script only tries to enable and disable the previous on the object the script is attached to. what am i doing wrong and is there any feasible way to do this? I've checked all tags, but the script keeps trying to reach this unrelated object. i even tried adding a mesh renderer and a colider. but nothing here is the script private bool on true public void Update() GameObject gameObjectArray GameObject.FindGameObjectsWithTag("buildnode") if (Input.GetKeyDown("b")) on !on if (on false) foreach (GameObject go in GameObject.FindGameObjectsWithTag("buildnode")) go.GetComponent lt MeshRenderer gt ().enabled false go.GetComponent lt Collider gt ().enabled false if (on true) foreach (GameObject go in GameObject.FindGameObjectsWithTag("buildnode")) go.GetComponent lt MeshRenderer gt ().enabled true go.GetComponent lt Collider gt ().enabled true Thank you and have a good day.


Surface Depth Intersection Shader I recently asked a question about the creating an accurate Depth Intersection Shader. When creating this in a fragment vertex shader it could be achieved by the following code SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" Pass CGPROGRAM pragma target 3.0 pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 float3 normal NORMAL struct v2f float2 uv TEXCOORD0 sampler2D MainTex float4 MainTex ST sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength v2f vert(appdata v, out float4 vertex SV POSITION) v2f o vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag (v2f i, UNITY VPOS TYPE vpos VPOS) SV Target float2 screenuv vpos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(vpos.z) float intersect 0 if(diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) return fixed4(lerp(tex2D( MainTex, i.uv) Color, GlowColor, pow(intersect, 4))) ENDCG However, when I try to put the same logic into a surface shader, the result does not show any depth intersections. SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows alpha fade Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex struct Input float2 uv MainTex float4 screenPos float eyeDepth half Glossiness half Metallic sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. See https docs.unity3d.com Manual GPUInstancing.html for more information about instancing. pragma instancing options assumeuniformscaling UNITY INSTANCING CBUFFER START(Props) put more per instance properties here UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float2 screenuv IN.screenPos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(IN.screenPos.z) float intersect 0 if (diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) fixed4 col fixed4(lerp(tex2D( MainTex, IN.uv MainTex) Color, GlowColor, pow(intersect, 4))) o.Albedo col.rgb o.Alpha col.a o.Metallic Metallic o.Smoothness Glossiness ENDCG


How to start in animating my model? I got a model from TurboSquid. Which is an archer and when i imported the model I got all the textures to be put on properly. The thing is the actual character has no children nodes, is it possible to still animate this model. I have looked throughout the files and there are a bunch of textures, but I don't happen to see any animations. Along side that the asset comes with an Avatar, I looked on the docs and still a little confused as to what that is about. If I cannot animate this model how could I force it to animate somehow or how could I make my own model. I am not a artist at all and just focus on the gaming logic and and programming, and I am working solo. Just wondering what are some options to get a game up and running with some decent graphics. So, far I use the model to get the game play down, but now I want to make it visually appealing.


How can I write a dots effect shader when the character is behind an object? I watched an interesting effect while I was playing Super Mario Odyssey when Mario or another character was behind an obstacle (walls, etc), a tiny gray silhouette mesh appears. I tried to build something similar using an amplify shader with Unity but I could not achieve it. How could I write this? Here is an example from the game


What would be the easiest way to define actions of multiple buttons So I'm creating a game that involves lots of different areas that involve pushing buttons to do certain things. Anyway, I'm trying to figure out how to let each button do its own separate thing, like open a door or things like that. I already know how to setup a Raycast between the player's mouse to the button, but now I'm just figuring out how to make each button trigger a separate action. Basically, should I set up a new tag for each button? Or create different scripts, even? I haven't tried anything yet and I need help. Thanks D


How To Have My Character Turn When The Camera View Moves So I have recently finished animating my character, having it move with key presses and have applied a camera to it. But I am stumped on how to have the player turn when the camera view moves, and have them both in sink. I want to have this instead of using keys to turn because that can be very awkward and hard to control. I would really appreciate any help I can get on this, as it will allow me to finally finish my character. Thanks, Nova


Unable to open project from a scene.unity file The tutorial I'm following has provided its project files, and I'm trying to open them in Unity. Here is the project download link. You can also go to the tutorial webpage and scroll down to download. I can't figure out how to do it. Here is what I've done. a) Extract zip to my Unity Scenes folder. b) Open Unity, create a new project called tutorial c) File Open Scene navigate to Unity Scenes voxeltut3 scene.unity d) Click Open It opens.. but then I don't see any of the tutorial's files in my project. There's none of the c scripts, no art, no prefabs... It's just the original empty project that I created. I also tried importing it as a new package e) Assets Import New Asset... select Unity Scenes voxeltut3 scene.unity f) Click Import And nothing happens. The Import New Asset dialogbox is still open with the scene.unity selected. It's like it's telling me that I've selected an invalid file. So I guess this is wrong? How do I open this tutorial project? I'm using unity 5.3.2 This is the folder structure the new Unity project that it created for me C Users me Documents Unity Scenes tutorial Assets Library ProjectSettings I unzipped the tutorial files in C Users me Documents Unity Scenes voxeltut3 Materials tiles.mat tiles.mat.meta Block.cs BlockAir.cs BlockGrass.cs scene.unity ... (other files)


Season system Implementation system in unity So I am planning on implementing a seasons system for a 2D top down game. Each season will have a characteristic terrain feature e.g. summers will have patches of grass spread out .. which I wanna reproduce by green bloat spread around on a 2D plane or quad... These features will need to generate dynamically for every season. The implementation will be simplistic nonetheless... using green bloats for grass patches, blue bloats for waterholes.. Can you guys give me like pointers to solve this problem? Some Reference images Notice how the backdrop background changes for each season Green Patches denotes grass Light blue denotes unfrozen water, dark blue denotes frozen water These bloats are to be generated dynamically, with some conditions like frozen water and unfrozen water need to spawn next to each other Summer Season Monsoon Season Winter Season


Unity change sprites to something that uses less memory I have a game that uses only silhuette textures, but they take up waay too much memory (360 MB overall and this is a mobile game) so I plan to avoid using sprites with alpha punchouts (1 bit alphas). From what I gathered, I could use an asset from Unity store like SVG importer, but I have no financial means to do so. So I plan to make low poly 3D (in fact 2D) planes that somewhat cover my textures. Now, I have a lot of sprites already. I saw that Unity can create a 2D mesh collider around my sprites. Can I use that to create my meshes and then apply a single colour unlit material to them? How would it roughly effect memory usage as opposed to my generally 500x600 sprites? If I'm going in the wrong direction, is there a way to create Shapes, just like in Photoshop or GIMP?


Unity Shader blending colors and color values above 1 I have source images where each pixel is one of exactly 4 colors red (1,0,0) green (0,1,0) blue (0,0,1) black (0,0,0) I'm trying to modify Unity's default sprite shader to use those colors (besides black) as a key to change to other colors. For example, any pixel that's red should become RedColor. My first attempt was fixed4 RedColor fixed4 BlueColor fixed4 GreenColor fixed4 frag(v2f IN) SV Target fixed4 c SampleSpriteTexture (IN.texcoord) IN.color fixed4 modColor modColor.rgb RedColor.rgb step(1, c.r) modColor.rgb BlueColor.rgb step(1, c.b) modColor.rgb GreenColor.rgb step(1, c.g) modColor.rgb c.a return modColor This worked. The problem was it was very jagged. In exporting the image and being compressed in Unity I think some pixels had multiple colors but the shader simply would set the color to the last matching color. So I tried to modify it to not reset the color if the next color matches, but instead blend between any colors present in the pixel weighted by their contribution. Here was my second attempt fixed4 frag(v2f IN) SV Target fixed4 c SampleSpriteTexture (IN.texcoord) IN.color float total c.r c.b c.g we set the total to 1 if it's 0 so that we don't divide by zero when the color is black total step(total, 0) c.rgb RedColor.rgb c.r BlueColor.rgb c.b GreenColor.rgb c.g c.rgb total c.rgb a return c This also worked and the jaggedness went away everywhere except the border of black and nonblack colors. So then I tried getting rid of the total and it was perfect fixed4 frag(v2f IN) SV Target fixed4 c SampleSpriteTexture (IN.texcoord) IN.color c.rgb RedColor.rgb c.r BlueColor.rgb c.b GreenColor.rgb c.g c.rgb c.a return c It's perfectly blended between any of the pixels. But I don't get why. I was dividing by the total so that the color values wouldn't go above 1 and it would blend between them. For example if a pixel had both red and blue present it would be adding the 50 of RedColor's rgb value and 50 of the BlueColor's rgb value. So when I didn't divide by the total it appears nothing changed besides blending between black and other colors. This implies to me that I never had any pixels that actually had more than one nonzero color component to them (or else I could would be getting white colors at those pixels). But if that's the case, why did switching from the first step function approach to a blend approach even do anything? This is my first foray into shaders so it's entirely possible I'm doing something terribly, but I just want to wrap my head around what's going on and why. So I definitely appreciate any help ideas.


Do I need a server if I only want to upload data to a DB? I'm currently creating a game where people get some kind of reports for their game performance on a website. Let's say, you log in, play the game, the system gathers your performance data and this is being sent to a database so that it can be read and interpreted by an external website later. For this, I'm using a firebase real time database and it's working fine by now. I'm pretty noob with unity and I have read and watch tutorials on the internet where people actually create a server to achieve this but do I really need a server when the only thing I need to do is to post data to a database based on users? This isn't really a multiplayer game, but there is some kind of information which is shared for example sometimes I need to get those data in order to get high scores and that kind of small information, but that's it. I'm using unity webgl and firebase for the moment, and everything is working fine, but then why people always create a server for this? PS sorry for my bad english


Using a Wii remote as main controller? I would like to use a Wii remote to control my player in my 3D game. So far I have the arrow keys and mouse to move and look but I want the Wii d pad to move and accelerometer data to look around. I have downloaded Unity Wiimote 1.1 and the demo works fine. In my game I have imported the Unity package for the Wii remote but I'm not sure what script goes where, attached to what, how to call particular functions. They are mostly C scripts. There is no documentation with the Unity Wiimote 1.1 and as I'm a newbie, I'm clueless on what to do. Or is there a simpler method to getting the Wii remote to be the main controller?


How to change Unity's display settings resolution? Unity displays in poor quality on my computer (the software itself), I was wondering how to change resolution display settings?


How can I find if a GameObject is not exist in the Hierarchy? var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0) tempSelections selections for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) transformSelection new List lt Transform gt () for (var i tempSelections.Count 1 i gt 0 i) var selected tempSelections i if (GameObject.Find(selected.name) null) GUI.enabled true else GUI.enabled false if (GUILayout.Button("Undo last selection if deleted")) transformsCount TransformSaver.LoadTransform().Length PlayerPrefs.DeleteKey("transform") For testing I'm deleting one of the GameObjects in the tempSelections List But then I'm getting exception in the editor on the line if (GameObject.Find(selected.name) null) Since the GameObject have been deleted it can't access the GameObject. MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.


Bullet physics C script Is imparting force on rigidbody objects I have recently made the simplest gun and bullet script that I could and it works amazingly, except for one problem that I've found. When I attach it to a game object with a rigid body the force of the bullets move the object back with quit a bit of force. But what I can't seem to figure out is why the bullets are imparting force on the object at all. The bullets do not have a rigid body component. The way my guns work is with two scripts, one which acts as a simple spawning point when a key down event is given and what ever object you give it to spawn. The second script is applied to the bullet itself which causes the bullet to have motion through transform.Translate with a speed variable. The best example I can give of this is when I attached two guns to the default unity jet and when I fired, it had enough force to move the jet back against its thrust speed. I really would appreciate any help with this so I can move on with my project. I will provide the code bellow for the two scripts. Thank you public class Shoot MonoBehaviour public GameObject bullet void Update () if (Input.GetKey (KeyCode.Mouse0)) Instantiate(bullet, transform.position, transform.rotation) public class MoveBullet MonoBehaviour public float speed 1f void Update () transform.Translate (0, 0, speed)


Character doesnt move along with his rotation Decided to change my character movement from transform.Translate to a rigidbody movement, the only problem is that my character is not moving to where he is facing, also it falls really slowly in the Y axis. Heres the code related to the movement float moveHorizontal Input.GetAxis("Horizontal") rotSpeed float moveVertical Input.GetAxis("Vertical") speed rb.velocity new Vector3(0, 0, moveVertical) transform.Rotate(0,moveHorizontal, 0)


Unity How to manage a large amount of prefab variations? The project that I'm working on demands the ability for game designers to be very flexible when balancing, customizing items, etc. The most difficult requirement to meet at the moment is that they want to drag drop, say, a weapon prefab onto a weapon field in some game entity component and from there be able to tweak the prefab's parameters. If I provide some tools that create derived prefabs at such moments, then we'll end up with possibly hundreds of pretty much same prefab variations and also loose the ability to edit the initial prefab and transfer the changes to derivatives. What I'm starting to consider is introducing a "Data Map" structure in every entity that requires high level of parameter customization. Every parameter would be set through methods like Set GetFloat("key", "value"), Set GetFloatArray, Set GetInt, etc. So basically a dictionary that maps a string to a predefined set of data types. When a prefab of such entity would be drag dropped into a field of another component, an editor tool would separate the "Data Map" from the prefab, allow the game designer to tweak the values of the keys and eventually serialize it to json. During runtime uppon instantiation of a prefab with a "Data Map" a manager would check the deserialized overrides and override the "Data Map" with the tweaked values if needed. Though to me this sounds overly complicated and maybe some of you had a similar situation and came up with a simple solution? Maybe it's worth trying the ECS approach? Thanks. An example Let's say there are prefabs Axe, Sword, Bow with a bunch of parameters configured, say Damage, Durability, etc. There are many other components that can accept a weapon prefab and once it's dropped, the designers want to have "on the spot editing" say, okay, for this situation here the Axe prefab needs to be a little different and have Damage 3. Creating a new prefab means that the link to the initial Axe prefab is lost and there are now two Axe prefabs that need to be managed this is the problem we're trying to address.


How to avoid overwriting a value in Unity? I'm working on a Tower Defence style game, and wondering how best to handle the quot resources quot part. I have multiple enemies on screen at a time, and when an enemy dies, it updates a resource that allows the player to build more towers var tower Instantiate(buildables 0 , center, Quaternion.identity) var controller tower.GetComponent lt TowerController gt () controller.OnKilledEnemy (sender, args) gt int.TryParse(goldAmount.text.Replace( quot , quot , quot quot ), out var curr) curr args.gold goldAmount.text quot curr n0 quot But if 2 enemies die in the same frame, wouldn't the value there miss an update? What ways are there in Unity C to mitigate this problem?