How can I move the object back to his original position after the object reached the target? InteractableItem target private void Update() if (target ! null amp amp target.name quot kid from space helmet quot ) objToThrow.transform.position (target.transform.position objToThrow.transform.position).normalized 2f Time.deltaTime if(Vector3.Distance(objToThrow.transform.position, target.transform.position) lt 1f) objToThrow.transform.position (objToThrow.transform.position target.transform.position).normalized 2f Time.deltaTime The object is moving to the target but never moving back. This IF is not working good if(Vector3.Distance(objToThrow.transform.position, target.transform.position) lt 1f) My guess is that the problem is that when the object distance is less then 1 he try to move back but then he is not less then 1 anymore. but anyway it's not working. I want to move the object to the target then wait 1 second at the target and then to move the object back.


How to see which mouse button was pressed (Unity Input System) I have switched my game to use the new Unity Input System, and I want to know which mouse button was pressed when an action is called. Here's how it's set up Whenever one of these three mouse buttons are pressed, the MouseButtonClicked action will fire. I want to somehow know which one of these buttons was pressed from this single action, rather than making 3 seperate actions for 3 seperate mouse buttons. I have tried reading the values from InputAction.CallbackContext context but I can't seem to get a proper value from the mouse button which was pressed. How can I do this?


Unity Instantiate GameObject from client on Network I am building a game where a weapon shoots prefab bullets. I am trying to make this a multiplayer game, so the bullets need to be spawned into the Network. What happens right now is that if I shoot a bullet from a host, the bullet is shot, but doesn't appear on the client screen. If I shoot the bullet from the client, the bullet doesn't appear on either screen. In fact, the function CmdShoot() isn't even called, as the Debug.Log("Hello") is not called. Here is the current code public class Gun MonoBehaviour private GameObject bulletPrefab void Update() if (Input.GetMouseButtonDown(0)) owner.GetComponent lt PlayerSetup gt ().CmdShoot(bulletPrefab, transform.position, owner.name, GetComponentInParent lt Weapon gt ().angle) public class PlayerSetup NetworkBehaviour void Start () Disable components if not local player Command public void CmdShoot(GameObject bulletPrefab, Vector3 position, string playerName, float angle) Debug.Log("Hello") GameObject bullet Instantiate(bulletPrefab, position, Quaternion.identity) bullet.name "bullet " playerName bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) Vector3.right bulletPrefab.GetComponent lt Bullet gt ().force) Destroy(bullet, 10f) NetworkServer.Spawn(bullet) Edit This piece of code doesn't work either, gives the same result. No error, but the function is also not called. The Input is detected though void Update() if (Input.GetMouseButtonDown(0)) CmdShoot() Command void CmdShoot() Debug.Log("Shoot") GameObject bullet Instantiate(gunComponent.bulletPrefab, gun.position, Quaternion.identity) bullet.name "bullet " transform.name bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(GetComponentInChildren lt Weapon gt ().angle, Vector3.forward) Vector3.right gunComponent.bulletPrefab.GetComponent lt Bullet gt ().force) Destroy(bullet, 10f) NetworkServer.Spawn(bullet)


Finding a moving target in a maze I'm making a game that is a bit of a mix of snake and pacman. Basically, two players go through the maze and each time they pick up a piece of candy, a cube is added to their tail. If one player touches the other's tail, he steals that piece for himself and the game is over when one player has all the pieces. Right now they both move randomly unless there's a piece of candy one space away that is not their tail. I'm trying to find a method algorithm (preferably a different method for each player) for both players to target avoid the other player. Any advice?


The tile cursor is not on the same tile I selected Here is the image, when I select the tile I want to paint, it paints in the correct box where I want it to be but the white cursor should also be in the same box but it is 2 units to the left? This really makes it difficult to paint the tiles. I'm a beginner in unity and can't seem to fix this problem ( Thank you for your help!


How to enable and disable scripts on a Game Object? This worked briefly yesterday, I believe I did something to mess this up. All my inputs that I put in are correct therefor, it must be the code. I want to switch players. While the red cube's script is enabled and can move under the movement script I want the blue cubes movement script to be disabled and vice versus. Can you give me some insight into what I'm doing wrong? Please and thank you!! using UnityEngine using System.Collections public class PlayerMovementScript MonoBehaviour public float speed 2f public float height 2f public Component playerMovement public GameObject redCube public GameObject blueCube void Start() var bc blueCube.GetComponent lt PlayerMovementScript gt () bc.enabled !bc.enabled Update is called once per frame void Update () if (Input.GetButton ("Right")) transform.Translate(Vector3.right speed Time.deltaTime) if (Input.GetButton ("Left")) transform.Translate(Vector3.left speed Time.deltaTime) if (Input.GetButton ("Jump")) transform.Translate(Vector3.up height Time.deltaTime) var bc blueCube.GetComponent lt PlayerMovementScript gt () var rc redCube.GetComponent lt PlayerMovementScript gt () if (Input.GetButton ("Switch")) bc.enabled !bc.isActiveAndEnabled rc.enabled !rc.enabled


Avoiding GC Allocation in Unity UNet API I'm trying to profile the game using Unity Profiler, I can see in the Hierarchy tab that there's an 18.3 KB correlated to NetworkIdentiry.UNetStaticUpdate(). I guess this has happened inside the Unity UNet API, is there a workaround to avoid that to happen? and why an internal Unity calls can cause GC?


How to calculate a direction that will turn a parent so that a locally rotated child is faced in a given direction? Imagine an old sailing ship with cannons they're pointed out at 90 angles from the ship's hull, so in order to fire them, you have to turn the whole ship so that the cannons are pointed at the target. I'm hoping to figure how to calculate quot where to point the ship so that the cannons are aimed correctly, quot but for any possible cannon angle (not just 90 ) in 3D space. I'm an experienced dev but a total 3D newb, so this vector stuff is wrinkling my brain. This is what I have right now, calculated from the child's (cannon's) gameObject Vector3 directionToAim (transform.localRotation (transform.position target.position)).normalized It's working for side facing weapons (like the sailing ship), but for forward facing weapons it turns the parent in the opposite direction, directly away from the target. If I invert it to (target.position transform.position) the forward facing weapons work fine, but the side facing weapons face the opposite way. Also, my vague understanding is that it's better to use Quaternions for this, rather than Vector3, is that right? Can someone help me grasp how these parent child rotations can be calculated?


How is the density of a collider determined? I read here that, once determining the density of a Buoyancy Effector, "Colliders with a higher density sink, those with a lower density float, and those with the same density appear suspended in the fluid." However, I did not find a density field in my CircleCollider2D. What I found is that If I increase the mass of the attached RigidBody2D, then the body sinks into the fluid since apparently its density increases. If I keep the mass but decrease the size of of the circle collider, then again the body sinks into the fluid indicating that its density increases. So my conjecture is that the density is calculated by the mass of the rigid body, divided by the volume of the collider. But I did not find the formula in the Unity manual. Is this correct?


Quaternion.AngleAxis smallest value? If I'm using an angle with a value of somewhat below 0.1 degrees in Quaternion.AngleAxis, the quaternion will not apply a rotation at all. Why is this?


Separate data tables for different item types? I have two types of items in my game, consumables, and equipment. For my database, should I store them in two different tables, or all in one big items table?


Unity ad does not show I have imported the advertisement package from the package manager, turned the ads service on, and added a script string gameId quot correctGameId quot bool testAds true void Start() Advertisement.Initialize(gameId, testAds) void Click () if(Advertisement.isInitialised) Advertisement.Show() This Click function is called from a button's OnClick event. Every time I play in the editor and click the button, nothing happens. How can I make my advertisement show?


Automated Unity iOS command line build on Mac I am doing the iOS builds for a group of Unity (Unity3d) game developers. After pulling the latest git updates, I start up the Unity editor on my Mac and choose "Build Settings", select the iOS target platform, press Build, specify a destination folder and that is it. Can this exact process be done automatically via the terminal prompt?


How to handle levels in Unity3d I m making a top down 2d game in Unity3D for Android based smartphones. Currently I have two scenes a preloader and the game itself with all the stuff I need packed into one scene file. Also there is a very simple game state manager in my scene. My question now is Is it better to script all the levels within one scene file or should I seperate them into unique scene files? I m just asking because basically the levels are very similar to each one only the background and the sprites are different. Is there a problem with memory management if I use one scene only?


Controlling a balance wheel using a Unity script I am working on a small demonstration project with Unity like this (screenshot from footage below). I don't want to use Unity physics, which is too heavy. I plan to create a rotation function with ratio params for gears. But I am not sure how to control the balance wheel rotation like that video, I tried animation tools which is hard to make the acceleration like real physics.


Unity doesn't show always the score I don't know if this issue is in Unity or in my script, the score work well in scoreText, but in the scorePanel its show before last score like it showing 1 rather than 2 the issue doesn't always appear its appear just in specific moment when my score and player die nearly in same time, so here is my script. AddToScore is called with InvokeRepeating, scoreText who show me the correct score, it works well void AddToScore() score scoreText.text score.ToString () mySound.Play() This is when my player Die void OnCollisionEnter2D(Collision2D other) Time.timeScale 0 Die () void Die () Pause.SetActive (false) Panel.SetActive (true) GameOverPanel.SetActive (true) GenerateObstacles.HighScore () And here is the HighScore from GenerateObstacles public void HighScore() if (score gt highScore) PlayerPrefs.SetInt ("highScore", score) highScore PlayerPrefs.GetInt ("highScore") scorePanel.text score.ToString () highScorePanel.text highScore.ToString () else if (score lt highScore) highScore PlayerPrefs.GetInt ("highScore") scorePanel.text score.ToString () highScorePanel.text highScore.ToString () Here is a paint to understand


problems with imported texture I have done a texture in GIMP and imported it in Unity but for some reason the texture appears to be squashed in the sides. Image done in gimp And here is what happens in Unity


How can I keep the drawn lines instead deleting them? using System.Collections using System.Collections.Generic using UnityEngine public class DrawLines MonoBehaviour private Transform startMarker, endMarker public GameObject waypoints private float speed 2f private float startTime 0f private float journeyLength 1f private int currentStartPoint 0 private LineRenderer lineRenderer public void StartInit() currentStartPoint 0 SetPoints() lineRenderer GetComponent lt LineRenderer gt () lineRenderer.startWidth 0.2f lineRenderer.endWidth 0.2f void SetPoints() startMarker waypoints currentStartPoint .transform endMarker waypoints currentStartPoint 1 .transform startTime Time.time journeyLength Vector3.Distance(startMarker.position, endMarker.position) void Update() if (waypoints.Length gt 0) float distCovered (Time.time startTime) speed float fracJourney distCovered journeyLength Vector3 startPosition startMarker.position Vector3 endPosition Vector3.Lerp(startMarker.position, endMarker.position, fracJourney) lineRenderer.SetPosition(0, startPosition) lineRenderer.SetPosition(1, endPosition) if (fracJourney gt 1f) if (currentStartPoint 2 lt waypoints.Length) currentStartPoint SetPoints() else if finished, disable lineRenderer and this script lineRenderer.enabled false this.enabled false Each time it's drawing a line between two waypoints but then the line is deleted and then it's drawing a new line between the next two waypoints. Instead I want it to draw one line between all the waypoints. And to keep the line in the end not to delete it.


How to develop VR PC games without a Head Mounted Display of my own? I am an intermediate student of Unity 3D, and I am not able to purchase heavy and expensive equipment like Oculus Rift, HTC Vive, or other models that are not available in Pakistan. So I'm wondering how I can develop VR games without these peripherals.


How to deal with inconsistent network delay caused by packets arriving at different times in the frame? I'm developing a multiplayer game that does not have prediction. It implements client side interpolation. The problem with this is that input delay can be perceived. I've measured the various times involved in calculating the delay(packet arrival time, server respond time, time spent interpolating), and it seems about 50ms is spent on interpolating(correct), and 60ms is spent on ping and what I can only assume to be unfortunate message arrival time. The ping is 18ms, which leaves 42ms. If the message arrives at the server immediately after the server has finished reading it's incoming messages this frame, we suffer at least a 16ms delay(at 60fps) that wouldn't be there if the message arrived right before the reading. If this happens with both the server and the client, the delay really adds up, especially at lower frame rates. How can posts like this http pastebin.com ekk07PKn claim to have exactly 50ms delay with 0 ping if this is an issue? If it's relevant, this is being developed with Unity3d and the Lidgren networking library in C . I've moved the server snapshot writing to a different thread with a lock around the game world update method. This helped a lot, but from what I understand moving the reading to a different thread won't help in the same way, because the client won't be able to use the new information until the next frame anyway.


In Unity UNet How do you properly spawn a NetworkPlayer ? In Unity UNet How do you properly spawn a NetworkPlayer? Right now, I'm doing it like this from inside a NetworkManager derived class public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) NetworkPlayer newPlayer Instantiate lt NetworkPlayer gt (m NetworkPlayerPrefab) DontDestroyOnLoad(newPlayer) NetworkServer.AddPlayerForConnection(conn, newPlayer.gameObject, playerControllerId) This code snippet works pretty well and both clients can communicate with each other. However, there are a few little issues that arise only on the host In Unity's hierarchy view on the host, there are only two NetworkPlayer instances. Shouldn't there be four NetworkPlayer instances on the host? Two client instances and two server instances? If so, do you have any ideas what could cause the missing NetworkPlayer instances? The two NetworkPlayer instances have both, their isClient and isServer flags set to true. But only one of the has it's isLocalPlayer flag set. Now I wonder if this behavior is as intended? And if so, how do you distinguish between the client and the server instance of a NetworkPlayer? Two player behavior If the remote client sends a Command that changes a SyncVar on the server, then on the host, the SyncVar hook is called only on the NetworkPlayer instance that represents the remote NetworkPlayer. The SyncVar hook is not called on the host's "isLocalPlayer NetworkPlayer" instance. Shouldn't the SyncVar hook be called on both NetworkPlayer instances? Any advise is welcome. Thank you!


Unity3D Problem Temporarily Stop Players Movement When Playing a specific Animation This is my first time in Unity3D and programming so forgive me if i'm a bit vague on this. I'm working on my own project in Unity3D but I couldn't get the player to stop moving when I press the key. I avoided using the GetButton since it triggered the animation to play twice. After bout 2 hours, I still can't find any answer to my problem. Can someone help me please? Here's part of the code of the the player script. if (Input.GetButtonDown("Fire1")) animator.SetTrigger("AttackSword") Debug.Log("Animation called") if(!animator.GetBool("AttackSword")) Move(inputDir, running) If you would like me to add the full code of the script, let me know.


Car simulation, motor torque and brake torque combine problem I am creating a custom wheel collider in Unity. Every thing is fine now (suspension, collision, friction) except one problem that i cant get my head over for last 3 weeks. So now i have a car (one wheel only), it stand on top of a hill, then i apply a brake torque enough to make it stand still, after that i apply a motor torque that less than max brake torque, my question is how the car behave?. In my opinion, that if sum of motor torque (roll down hill direction) and gravity torque(friction force radius) greater than the max brake torque will cause the car to roll down hill, and it remain stand still if motor torque (roll up hill direction). I really need help! So i have mT(motor torque), bT(max brake torque), fT(max ground torque), rT(residual torque) if ( mT gt bT ) rT mT bT if ( rT gt fT ) wheel spin up with sign(mT) ( rT fT ) ground force sign(mT) fT radius else wheel roll without slipping ground force mT radius else rT bT mT if ( rT gt fT ) wheel slow down to 0 with sign(omega) ( rT fT ) ground force sign(velocity) fT radius else wheel roll without slipping ground force sign(velocity) ( bT sign(velocity) mT) radius All torque sign are on top.


How to activate GearVR Menu in my own Unity Apps? So in normal GearVr Apps, which you can download from the marketplace, you can activate the GearVr Menu to control brightness etc. with a long click on the back button. But this does not work for all of my apps which I made with Unity for the GearVr, is there something special I have to import into my project?


Iterating through all animator layers in Unity Mecanim I'm aware of how SetAnimatorLayerWeight works, I'm looking for a way to iterate through all layers of my controller at runtime. I've four layers and expect more, and need to update them at once, in essence, what I'm trying to do is something like this. To clarify The code below is boilerplate of what I'm trying to do. void SetCurrentWeaponLayerWeight(int index) animator.SetLayerWeight(index, 1) foreach(AnimatorLayer l in Animator.Layers) if (l.index ! index) animator.SetLayerWeight(l.index, 0)


Having player names over models in 3d space I wanted to have in my multiplayer game, the players name's over their models, however I am faced with the question of how? Should I create a new Canvas object for each game model or just use 1 main canvas and move their names around relative to position in 3D world space? My aim is to have an open world game.


Best way to connect multiplayer users with each other (matchmaking) on a low powered server? OK so I am using unity to make a multiplayer game, but I'm not sure how to connect players with each other over the internet. Unlike other questions, this isn't a general problem of working out how to do UPnp or using unity's matchmaking server. My issue is that my server that I would use is a simple low powered pc (running normal windows 10, no idea how to use windows server). I think it is powerful enough to match players with each other, but not to host more than one or two actual games. The other issue is that I have a residential internet connection with a dynamic ip that changes every few months. However the speed should be ok (150Mb s download, 20Mb s download). Also, I'm not planning to spend money on a monthly basis for a server (like unity's matchmaking service) as I plan to spend as little as possible (So far I've paid 12 to Microsoft for a dev account and I've received a 200 voucher from them so my current spending is 189!) So my question is should I use my server (would it work), are there any online services that are very cheap to use, or is there another way to make this work? Only other thing is I could use the free 20 users at once on unity's matchmaking, but would this limit be too small? EDIT just for information, my game is a simple tank shooter. I was thinking about limiting the amount of tanks in a game somewhere around 8 20. The bullets in my game are physical objects with rigidbodys and they move at a slower speed (if you've ever played tank trouble, it looks like that). The world is in 3D. There is a potential for there to be up to a hundred bullets in a scene at once at the worst. After hosting a LAN world with 7 players connected for about 20 30 minutes, windows reports the data usage being around 3 4MB.


How to not move my character when they collide using Unity and Box Collider? I'm trying to get my characters near to each other so they can attack the other one, but when the player character or otherwise gets near they are pushed to the other direction when they collide. How to prevent that happen so they won't move when touching each other? This is the player objects The Treant objects I what I want is that they collide and can't move through each other and stop moving. But this keep happen gif of my treant getting pushed away Can someone help me with this issue?


How can I my homing missile avoid walls (2D)? Okay, I have the homing missile implemented. It will follow the player, but I want it to avoid the walls. I tried out A but I want to make my own. I need some help plzz.


Detecting when a car is out of the track I am completely new to Unity 3D, just started to follow some tutorials y'day. I am trying to build a 2D car racing game as a part of my learning (time beating, no opponents). I have a racing track as texture (repeating). My problem is knowing when the car is outside inside the track (I wouldn't prefer to limit it to the track boundaries). What I have tried after searching around I read somewhere about Mesh Colliders so I added a mesh collider to the track (with 'Convex' and 'Is Trigger' checked , to be honest I don't know what Convex is, but I couldn't check 'Is Trigger' w out checking 'Convex'). Added OnTriggerExit and OnTriggerEnter methods to the Track script (the script that scrolls the track) hoping the two would be called each timer the car goes out of the track or gets back in. Apparently the two methods aren't called at all, Would someone please help. Thanks.


Converting to JSON String with JsonUtility.ToJson I am working on converting and displaying the JSON String with unity. I have done coding for it using UnityEngine using System.Collections using LitJson using SimpleJSON using System.IO public class TestDelete MonoBehaviour JsonData json void Start() Data2 data new Data2() Payload2 data2 new Payload2() data.command "state" data.payload new Payload2() text "wwwwwww", image "hello" data2.option new Option () A1 "k", A2 "J" string dataValue data data2.ToString() string json JsonUtility.ToJson(data,true) P(json " t n") Use this for initialization void P(string aText) print (aText " n") System.Serializable public class Payload2 public string text public string image public Option option System.Serializable public class Data2 public string command public Payload2 payload System.Serializable public class Option public string A1 public string A2 This code of working fine.But with the output Iam having problem.The out is displayed as follow "command" "state", "payload" "text" "wwwwwww", "image" "hello", "option" "A1" "", not getting displayed "A2" "" not getting displayed the string value A1 and A2 is not getting displayed.What will be the issue with my code.Can anybody help me sorting out this issues


Unity "static" references I have been researching this for 2 days now and I cannot seem to find a proper response. I am trying to figure out a good way to store constant variables within my game. Basically, does it make more sense to create a singleton script that holds all my prefabs inside it so I can easily access them and instantiate through the game? Or does it make more sense to keep all my assets inside the Resources folder and then call Resources.Load throughout the game (or through a Static class that holds references to all the resource paths and loads the resources on start up) I have the same question regarding variables used within runtime. Would it be better to run through the Static class that is holding all these prefabs through the Resources folder? Or would it make sense to also hold these values inside the singleton. Thank you!


Determine where is player facing up, down or left right I have a player object who can rotate(face using mouse) up, down left right and can face straight. I am willing to know that how to determine that where is camera facing? Either it is looking up or down?? while the player is continuously moving in a up down surface.


How can I tell how much of a "scratch card" has been revealed? I have developed scratch card effect.I am now working on reward system, so my question is how will I go on and implement logic which will let me know that the object behind scratch card is now visible??


canvas not found in game view with unity I am working on a GearVR app with Unity3D.I have an environement and I have placed a canvas in the scene.I have set the canvas Render mode to "World Space".But when I runned my project,the canvas is getting displayed on the scene view,but in the game view the canvas is not getting on the scene.But whereas in the camera view its showing the canvas.What will be the issue?. When I set me canvas Rendere mode to Screen Space Overlay the canvas is getting displayed in the scene but as the lookup change,the canvas is also moving along with the camera Can anybody please help me out.


SerializedPropertyBindings NullReferenceException Using Unity 4.6.1 Pro Visual Studio 2013 Pro, c Team Foundation Connected to git vc Windows 7 Premium Building 2D iOS app (2D set up) Details Periodically, this error is occurring. There is no pattern to invoke this error so far. I then found this on the official Unity forums Strange error showing up But, I would like to avoid creating an entirely new project and re importing everything, since it is getting to become a slightly large project. I do remember deleting an asset out of the file directory(not in unity), on accident, so this may be the issue. Is there any way to clean wipe fix this issue, w o doing a fresh project and import? I appreciate the guidance.


Strange I'm getting exception but the scripts in the exception message are not exist on my pc. What should I do? I'm using unity version 2019.2.5f1 personal I searched on my hard disks the entire pc and none of the scripts in the exception message are exist. And the exception is happens only sometimes. When I stop the game in the editor by pressing the play button the exception is show sometimes and sometimes not. I tried to close and open over agai the unity editor and the project. Still strange. MissingReferenceException The object of type 'ReflectionProbe' 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. UnityEditor.ReflectionProbeEditor.OnPreSceneGUICallback (UnityEditor.SceneView sceneView) (at C buildslave unity build Editor Mono Inspector ReflectionProbeEditor.cs 651) UnityEditor.SceneView.CallOnPreSceneGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 3359) UnityEditor.SceneView.DoOnPreSceneGUICallbacks (UnityEngine.Rect cameraRect) (at C buildslave unity build Editor Mono SceneView SceneView.cs 1935) UnityEditor.SceneView.OnGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 2320) System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object parameters, System.Globalization.CultureInfo culture) (at lt 599589bf4ce248909b8a14cbe4a2034e 0) Rethrow as TargetInvocationException Exception has been thrown by the target of an invocation. UnityEngine.UIElements.UIR.RenderChain.Render (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRChainBuilder.cs 238) UnityEngine.UIElements.UIRRepaintUpdater.DrawChain (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 66) UnityEngine.UIElements.UIRRepaintUpdater.Update () (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 54) UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTree () (at C buildslave unity build Modules UIElements VisualTreeUpdater.cs 72) UnityEngine.UIElements.Panel.Repaint (UnityEngine.Event e) (at C buildslave unity build Modules UIElements Panel.cs 637) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 240) UnityEngine.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 78) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules IMGUI GUIUtility.cs 179)


Make handlers visible on scene load In my dev enviroment I have a couple custom handlers I want to always be visible. I have already figured out that I can do this by deriving a class from Editor, linking it to the desired component type, and then appending the render method to SceneView.duringSceneGui (in OnEnable(), as the target gameobject information will be available there). However, this appending now only happens once a specific gameobject carrying the component has been selected. Is there a way I could have the Editor's OnEnable() method properly trigger on opening a scene, for all relevant gameobjects, without manually selecting them first?


Unity Controlling animation by switching between a GameObjects children I bought an asset the other day containing an Atlas of character parts (head, hairs, clothes, body parts). It's great and allows me to tint each piece any color I want. However, The artist decided to devide up the character like this Each child is a fully setup character, facing a certain direction, with an Animator attached to it, inside each Animator Controller you find this Some sample animations, pretty self explanatory. However, I have never worked with sprites like this where its several parts, the entire character is maybe 30 40 parts (allowing for some fun animations). I'm used to making Blend Trees (on a single GameObject) and have one animation for each direction. The best solution for controlling these animations I could think of was something like this private void AnimControl() call in update if(direction ! directionLastFrame) do not run method if we are moving same direction standing still if (direction.x 0 amp amp direction.y 0) directionLastFrame direction left else if (direction.x lt 0.5f amp amp direction.y 0) currentCharacterDirection.SetActive(false) set current gameObject (which is a character facing a certain direction) inactive currentCharacterDirection character.leftDirection change to correct direction currentCharacterDirection.SetActive(true) set gameobject active again anim currentCharacterDirection.GetComponent lt Animator gt () set the animation controller to the new gameObject directionLastFrame direction set the new direction to check for right else if (direction.x gt 0.5f amp amp direction.y 0) currentCharacterDirection.SetActive(false) currentCharacterDirection character.rightDirection currentCharacterDirection.SetActive(true) anim currentCharacterDirection.GetComponent lt Animator gt () directionLastFrame direction down else if (direction.y lt 0.5f amp amp direction.x 0) currentCharacterDirection.SetActive(false) currentCharacterDirection character.downDirection currentCharacterDirection.SetActive(true) anim currentCharacterDirection.GetComponent lt Animator gt () directionLastFrame direction up else if (direction.y gt 0.5f amp amp direction.x 0) currentCharacterDirection.SetActive(false) currentCharacterDirection character.upDirection currentCharacterDirection.SetActive(true) anim currentCharacterDirection.GetComponent lt Animator gt () directionLastFrame direction anim.SetBool("Moving", playerMoving) I mean it works, but feels wrong? Anyone that can think of a better Idea here, worried this might be too slow. setting an object to active inactive too often.


How to make an enemy spawner that selects from a list of potential enemies? (Unity) I'm just making a practice version of a basic 2D RPG, but I'm trying to build a spawner kind of object that could be scaleable across the entire game. That is, there would be multiple types of enemies, and each instance of such a spawner would have a specific set of enemies that it would spawn. I'm sure the answer is very simple, but I'm at the beginning stages of all of this. I guess really I just want a simple list that I can attach to my object and add the enemy names to it so that it can draw from that to figure out what they would spawn.


Collider for Unity Line Renderer I have several line renderers that are using as gas pipelines. A user can select one end of the pipe and attach it to one connector. Now the problem is some pipes (line renderer) are overlapping and penetrating with each other. Is there any way to avoid penetration using colliders so they look realistic?


One Android app, dynamic load several Unity games I'm a newbie in this unity world, exciting about everything in it. Days ago I came up with this idea One day someone finds this android app, naming "Blahblah Game Engine" or anything else. This app has to be very small, containing only some simple activity and Unity runtime, without further resources related to any specific game. He installs it and sees an android activity, maybe a webview, showing a list of unity games the server currently hosting, produced by the very same Blahblah company. Then he clicks on one and this "Blahblah Game Engine" loads the game build via network, starts an Unity activity, without prompting an installing dialog. He can exit the current game whenever he likes, returns to the previous game list, and plays another, all working well in one app's lifetime. In a word, the user experience is very much like how we play games on www.kongregate.com with pc browsers light weight app, mutiple games in one list, all loads via network, playing right away and installing less. Any game that listed in this app should not be installed as a standalone android app, it should be part of the "Blahblah Game Engine", stored as a file inside data folder of "Blahblah Game Engine", run as an activity of "Blahblah Game Engine". Is it possible with Unity 5, both technically and legally? If I were to start this "Blahblah Game Engine" project, should I choose Unity 5 personal or pro licence?


Can I Create A Windows Package to Submit to the Window Store using the Mac Version of Unity 5.3? Note New to App Development. I'm using a Mac for building my three 3D puzzle apps with Unity 5.3.2. I want to create Windows versions to sell in the Windows Store. I attempted to transfer the package for one of our apps to the Windows version of Unity but it was a pure hot mess. A lot of the alignment of text and images was skewed really bad. We have not used Windows in approx. 10 years so for all practical purposes we are brand new Windows users. The last OS we used was XP. The laptop we just purchased runs Windows 10 Home. I can create a Windows executable (.exe) file from the Mac version of Unity that executes my 3D puzzle app perfectly just like the Mac version. However I found out that I had to submit a special package to the Windows Store. The instructions that I found so far for this assumes that you are using the Windows version of Unity. I do not plan to be a full time app developer so the idea of trying to learn Visual Studio for me is a waste of my time. I would prefer creating the Windows package for the Windows Store using the Mac version of Unity. Is this possible? I could not find instructions in the manual or from search on what options need to be set to do this. I'm thinking it can be done since I was able to create a Windows exe file using my Mac version of Unity. I would like to create Windows Store packages for both 8.1 and 10.


How can I prioritize the call order of decoupled scripts? I have a player with many individual components that each handle a behavior such as jump, block, attack, duck, etc.. None of the scripts know about one another. Each listens for a specific input to fire. Some behaviors share the same input depending on the characters state such as ok the ground, in the air. I'm running into issue where the wrong behavior will fire that has shared input (down attack instead of down attack being held down for x seconds). I'm looking for advice on how to manage these behaviors and have more control over what can happen when. I've tried resolving this issue by creating a method that will disable other behaviors temporarily while completing the action and I've changed the script execution order. I thought about adding a discrete player state and restricting what behaviors are able to be performed at any given time but this increases the complexity quiet a bit.


Missing Reference exception when accessing a GameObject in Unity I have been making a C script that attacks the player in Unity. However, with the following code I got the following error message "The object of type 'GameObject' has been destroyed but you are still trying to access it. Here is my code using System.Collections using System.Collections.Generic using UnityEngine public class attackPlayer MonoBehaviour GameObject Enemy GameObject Player void Start () Enemy GameObject.FindWithTag ("Enemy") Player GameObject.FindWithTag ("Player") void Update () var heading Enemy.transform.position.x Player.transform.position.x if (heading gt 0.0f amp amp heading lt 5.0f) Explode () void Explode() var exp GetComponent lt ParticleSystem gt () exp.Play () Destroy (gameObject,exp.main.duration) Destroy(Player) void OnCollisionEnter2D (Collision2D col) if (col.gameObject.tag "Player") Explode ()


IgnoreCollision while Dodging Colliding I'm working on a mechanic to allow the player to dodge through enemies. However I'm running into the issue where the player is only able to dodge through enemies while their already dodging when they collide with the enemy. I want this to work both ways, as in, when their colliding with the enemy, they should be able to dodge through then. Here's what I've been trying void OnCollisionEnter (Collision col) STOP ENEMY FROM MOVING PUSHING if (col.gameObject.tag "Enemy") Debug.Log("Collided with " col.gameObject.name) target col.gameObject target.GetComponent lt ZombieController gt ().mRigidbody.isKinematic true IGNORE DODGING COLLISION WHEN ALREADY COLLIDED if (isDodging) Physics.IgnoreCollision(col.collider, GetComponent lt Collider gt (), true) IGNORE DODGING COLLISION if (isDodging amp amp col.gameObject.tag "Enemy") Physics.IgnoreCollision(col.collider, GetComponent lt Collider gt (), true) It just doesn't seem to work when the player has already collided with the enemy. Hopefully all that made sense.


smooth look at only on x and y i'm using the script down below to make my camera look at mouse x and y position, and it has a limitation for my camera rotation.the problem is the way my camera rotates is not smooth at all.is there any way to make it smoothly look at position on x and y? rotationX Input.GetAxis("Mouse X") sensitivityX rotationX Mathf.Clamp(rotationX, minimumX, maximumX) rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp(rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY , rotationX, 0)


Generating a sprite using a list of points I am trying to dynamically generate a sprite in Unity to visualize a list of points. What I've got so far is creating a small Texture2D object and then trying to override the geometry static SpriteRenderer SpriteRendererFromPoints(SpriteRenderer spriteRenderer, List lt Vector2 gt points) var texture Texture2D.whiteTexture spriteRenderer.sprite Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f)) Sprite sprite spriteRenderer.sprite sprite.OverrideGeometry(points.ToArray lt Vector2 gt (), sprite.triangles) return spriteRenderer I am adding this SpriteRenderer and a PolygonCollider2D to my gameobject and the instantiate it like this GameObject meshObject new GameObject() PolygonCollider2D polygonCollider meshObject.AddComponent lt PolygonCollider2D gt () PolygonCollider2DFromPoints(polygonCollider, points) SpriteRenderer spriteRenderer meshObject.AddComponent lt SpriteRenderer gt () SpriteRendererFromPoints(spriteRenderer, (from point in points select new Vector2(point.x, point.y)).ToList lt Vector2 gt ()) Instantiate(meshObject) It all runs fine but when running this, the sprite is nowhere to be seen Any help as to what I'm missing here or alternative ways of accomplishing this would be much appreciated.


How to parent object to empty when looked at I am making a fps in unity. I have an empty parented to the camera for the gun, and I want to be able to pick up and drop guns found in the scene. Does anyone have a simple c script that would allow the player to look at the gun on the ground, press a key and have it be parented to the empty? I would also like for the player's old gun to drop on the floor where the one being picked up was and un parent from the empty when the new gun is picked up. If you want an example I guess you could say it is like halo where you can go around and pick up new guns. I am not looking to make an inventory, just a simple script where you can swap your weapon.


Why does unlocking cursor with keyup behave the same as unlocking it with keydown? To understand the difference, let me review a bit about the behavior of GetKeyUp and GetKeyDown with the following code snippet. void Update() if (Input.GetKeyDown(KeyCode.Escape)) Debug.Log("Escape Key Down") if (Input.GetKeyUp(KeyCode.Escape)) Debug.Log("Escape Key Up") Right after pressing the Esc key (and holding it), a message "Escape Key Down" is produced. Later right after releasing the key, a message "Escape Key Up" will show. The behavior does make sense. Now I apply this for toggling (locking unlocking) the mouse cursor. Here is my code snippet. void Update() if (Input.GetMouseButtonDown(0)) Cursor.lockState CursorLockMode.Locked Cursor.visible false if (Input.GetKeyUp(KeyCode.Escape)) Cursor.lockState CursorLockMode.None Cursor.visible true Right after clicking the left mouse button, the cursor becomes invisible. However, right after pressing down the Esc key, the cursor becomes visible again. The expected behavior is that the cursor will be visible right after releasing the Esc key rather than right after pressing the key. Question How to fix this abnormal behavior?


MissingComponentException There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it When I run my program I keep getting MissingComponentException There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it.Even though I have attached it as you can see In the script I am trying to edit the text of the Text Mesh like this private int count public TextMesh countText Use this for initialization void Start () count 0 counterText gameObject.GetComponent lt TextMesh gt () counterText.text "Count " count.ToString() What I want is to count the cans that have been shot, so what I do next is void OnCollisionEnter(Collider other) if (other.gameObject.CompareTag("Can")) other.gameObject.SetActive(false) count count 1 counterText.text "Count " count.ToString()


Some meshes are visible in game view while others are not I have a FPS character in unity. The FPS character is divided into a few different pieces (upper arm, lower arm, hand, fingers, etc). I exported it from blender, so I'm using the camera that got converted from the blender camera. For some reason, the mesh is not showing up in the game view camera vision. I did a little bit of testing and found out that If I move the camera away, the mesh shows up, so the mesh isn't invisible or anything I put a version of the character that I imported from blender earlier as a test(different rest pose and less animations attached to it) in the same location as the FPS character, and attached the same animator to it. When I did that, you can see the earlier version but not the newest one The same thing happens even if I change the camera The camera has a field of view of about 67, and a focal length of 18. Near is set to the lowest value possible. Both characters are visible in scene view, just not in game view.


Enemy doesn't fire at player My script looks pretty good but it says Target variable has not been assigned value. public GameObject AntagonisticElement public GameObject Target public float bulletSpeed public float enemySpeed public float bulletDestroyTime public GameObject explsn public GameObject bulletPrefab public Transform bulletSpawn Vector3 pos public float min 20 public float max 10 public int MaxCounter public int CounterStatus int numberofEnemy Use this for initialization void Start() Update is called once per frame void Update() if (CounterStatus lt 0) if (numberofEnemy lt 3) Vector3 creationPoint transform.position creationPoint.y 0.5f Instantiate(AntagonisticElement, creationPoint, transform.rotation) CounterStatus MaxCounter numberofEnemy else CounterStatus transform.LookAt(Target.transform.position) if (Vector3.Distance(transform.position, Target.transform.position) gt min) transform.position transform.forward 4 Time.deltaTime if (Vector3.Distance(transform.position, Target.transform.position) lt max) shootAt() void shootAt() Instantiate(explsn, bulletSpawn.position, bulletSpawn.transform.rotation) var bullet Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) bullet.GetComponent lt Rigidbody gt ().velocity bullet.transform.forward bulletSpeed


Anchored Unity text ...not anchoring! I've added some text to a unity UI and set both the achor and pivot to the top right corner as shown here When I start this in debug in unity the text looks fine What's weird is that when I build the app and run it as an executable as a host (this is a multiplayer networked game) the text also looks fine. But when I start a client instance the text doesn't appear. I debugged and paused the game in unity in client mode and noticed that the text object is miles away from where I'm expecting it to be (and as a result doesn't show on the camera). You can just about see the black line on the below image which is my level and the text anchored miles up and right of the level. It seems like I've done something stupid here but I can't work out what s EDIT Leo's answer was correct conceptually, but here's how I implemented the suggestion. Created an empty game object GameStateManager in the hierarchy Add a GameState script to the manager with a network identity Added my 'RemainingTime' property to the game state script and put the SyncVar attribute on it Put logic in the game state Update method to update the remaining time Added a ClientTimer script to the text object (mono behaviour), which retrieved the GameState from within the clients copy of the game state manager. In the update method of the client time, get a reference to the Text object and set the .text property to the value of the remaining time. I'm not sure if this is correct, but it does seem to work, and now the ClientTimer script isn't networked, which resolved the issues with placement of the text.


Bad Viewports Using Unity with Google Cardboard VR on iOS I'm using unity 2017.3.1f1, building for an iPhone SE. I'm able to build the google HelloVR scene, available from the Google Cardboard VR unity package. However, in the end result, the cameras are giving the wrong display. They aren't lined up to create stereoscopic vision at all, and the image appears distorted. Here is an example of the output https i.imgur.com Y4pqdiy.jpg Is there a default setting in the Google Cardboard VR package that can be changed to fix this?


Unity3D) Is there a way not to draw line renderer if vertex pos is zero? I make a curved line with line renderer. and a sphere move along it. i want to draw a line only behind the sphere. so i do something like this. lr.positionCount 256 while (delta lt time) lr.SetPosition(i , curPos) yield return new WaitForFixedUpdate() and the problem is, because of i set the size of Positions 256, if time is short, there are zero vectors in position. so line renderer draw meaningless line. is there a way to set PositionCount dynamically like List? or any good way to not draw if positions are zero?


How to add only 1 value in a list in the Update function when a GameObject is active for many frames In my C script, I get the active gameobjects during play mode. Those gameObjects that are active are 1 First, I get the ones that the application has selected randomly 2 and then after the first ones get disabled (setActive(false)), I get the selected gameObjects which are those that the user has pressed using their button. So basically the application is The user hears a sound being played (here I set active the gameObject that has that sound) and then after some frames, the sound gets disabled and then the user needs to press a button in screen to make a choice depending on the sound (here I set active the gameObject that has the button) and then I disable that game object after some frames. Now every time one of those gameObjects gets selected, I try to add to my list some sort of value (lets say 1 in this case). But what happens is that I only manage to add the value in the Update() function but in this function I do not get only 1 value added in the list every time I get the first gameObject selected but because it updates every frame, this value gets added for like 125 times in the list until this gameObject gets diselected and the next gameObject (the one that holds the button) get active. if (DogSelected.activeSelf amp amp NoCarSelected.activeSelf) enable true if (enable) DogLionSelected.Add(0) NoCarCarSelected.Add(0) enable false if (DogPressed.activeSelf amp amp NoCarPressed.activeSelf ) enable true if (enable) string data new string scene.name.ToString(), "0", "0", "0", "0", "1" orientationStringWriter.Write(string.Join(delimiter, data) " n") DogLionPressed.Add(0) NoCarCarPressed.Add(0) PrimaryCorrectIncorrect.Add(1) enable false Ideally, I would want to 1 Hear the sound (gameObject is active) add only 1 value in list until the gameObject is deselected. 2 Then do the same thing for the gameObjects that hold the button. So when that gets selected add only one value in the other list until this gameObject is deselected. Then do the same process 72 times (because the number of trials in this application is 72). Can anyone give me any advice how to achieve this? Thanks


Add singleton to an existing gameobject in Unity via script I did notice that if I assign scripts that generate singleton classes (for my managers), to an empty game object, everything works fine. Now I would like to start the scene with the empty game object, attach the main game manager singleton, and in the game manager singleton I would like to attach to it the other manager singleton classes. Although I am not sure how you actually do so. Do you run addComponent to the main game manager, and they will be attached to the existing gameobject? The gameobject that I use for the main gamemanager is set to not be destroyed on load the doubt is if I should run addComponent on the scripts, or create a reference from the gamemanager script and instantiate it from there. I did look for examples on the subject, but the only thing that I found is the reference to add a script to a game object and I am not sure if that's actually what is supposed to be done.


Create a normal map using a script? Unity I don't have a software that can create normal maps from an image so I usually make a grayscale image and then let unity make the normal map from that image. But I can't save the image to use for later, Instead I have to convert it to a normal map every time I use it. So how would I make a normal map from a greyscale using a script? i prefer c but js works fine.


Angle between start and current rotation I'm facing problem of the operations on rotations. I have a wheel with a start rotation of (0, 0, 0). The player has to rotate wheel 270 degrees in Y axis either left or right. During the rotation slider should indicate progress of the rotation. For example if player rotated 135 degrees in right direction, slider is 50 filled to the right. The thing is that I'm not sure how to get the value of which the player rotate the object. For example when I start rotating right my angle changes from (0, 0, 0) to (0, 359, 0). How can I resolve this issue so it knows that change from (0, 0, 0) to (0, 359, 0) means player rotated only 1 degree?


Why is perlin noise generating flat terrain in Unity? I am trying to generate terrain using perlin noise however the terrain being generated is a plateau. Here is the code that I'm using var xlength 65.0 var ylength 65.0 var scale 4.1f var heights new float xlength, ylength function Start () for (var i 0 i lt xlength i ) for (var j 0 j lt ylength j ) heights i,j Mathf.PerlinNoise(Time.time i xlength scale 1000,Time.time j ylength scale 1000) i j gameObject.GetComponent(Terrain).terrainData.SetHeights(0,0,heights) What am I doing wrong here?


How to do pixel per pixel modeling in unity3d? So generally I want to have api like pixels.addPixel3D(new Pixel3D(0xFF0000, 100, 100,100)) (color, position) where pixels is some abstraction on 3d sceen objet.So to say point cloud. It would have grate use in deep space stars modeling... I want to set each pixel by hand (having no image base or any automatic thing)... So point is modeling something like Or look at alive flash analog here How to do such thing in unity?


Effect culling on uneven terrain I'm trying to integrate a "ground particle" effect (like a fire circle or similar) in Unity3d, however since i'm using uneven terrain as my terrain mesh, the effect gets culled behind terrain parts that above it. To better ilustrate it I created an image as attachment I want for the effect to always be displayed regardless of it's "depth". How can this undesired effect be avoided resolved properly ?


How to reset the score to 0 when reloading the game? My scoring system uses DontDestroyOnLoad to persist between scenes public class ScoringSystem MonoBehaviour private int score 0 public void Correct(int number) If correct add score score score number void Start () score 0 void Awake() DontDestroyOnLoad(transform.gameObject) public int GetScore() return score Here is another script that I should include a description about public void iniTag() jawab true Time.timeScale 0 GameObject objek1 GameObject.FindGameObjectWithTag("Benar1") GameObject objek2 GameObject.FindGameObjectWithTag("Benar2") GameObject objek3 GameObject.FindGameObjectWithTag("Benar3") GameObject objek4 GameObject.FindGameObjectWithTag("Benar4") if (objek1.transform.parent.tag "Jawab4" amp amp objek2.transform.parent.tag "Jawab3" amp amp objek3.transform.parent.tag "Jawab2" amp amp objek4.transform.parent.tag "Jawab1") PanelBenar.SetActive(true) buttonNext.SetActive(true) GameObject.Find("QuizManager").SendMessage("Correct", playerScore) void Start () if (GameObject.Find ("QuizManager") ! null) ScoringSystem scoringSystem GameObject.Find ("QuizManager").GetComponent lt ScoringSystem gt () gameObject.GetComponent lt Text gt ().text scoringSystem.GetScore().ToString () else Debug.Log("No Scoring system found. To test scoring system start from the front page scene")


Can't get the current animation state name (hash or .IsName) to work I have some hard times trying to get the current animation state name in Unity, to perform specific actions while I'm in a certain state. I want to know when I'm the "ThoughtsStill" state, I only have the default layer (Base Layer) To do this, here is what I tried AnimatorStateInfo curr state animator.GetCurrentAnimatorStateInfo(0) if (curr state.shortNameHash Animator.StringToHash("ThoughtsStill")) Debug.Log("I'm in ThoughtsStill state"). which is not working. I also tried with IsName() method but it is not working too (both tried to compare "Base Layer.ThoughtsStill" and "ThoughtsStill"). I'm certain that I'm going in this ThoughtsStill state but I don't know why I can't get it. Do you guys have any ideas or leads? Thanks !


Move circle inside semi circle based on external object I have a circle that I'd like to move around in semicircle with it's location following an external object. I can get the direction the circle should be facing with something like this Vector3 targetDir X.transform.position circle.transform.position How can I stick the movement of the circle inside a semicircle?


How to add or increase speed on every 500m distance of player? I'm a a beginner, creating an endless runner game. I want to increase speed as the player completed the distance and on every 500 meter speed should be increased. Anyone have an idea of how to implement this kind of logic? speed 10 as soon as player reach 500 m distance speed should be incremented it should be continuous process on every 500m My code public class Score MonoBehaviour SerializeField GameObject ground SerializeField AudioClip clip SerializeField Transform player SerializeField public Text LiveScore SerializeField public GameObject gameOver SerializeField public bool runningScore true public Text finalScore public Text Highscore, bestScore float distance ball Ball Start is called before the first frame update private void Start() Ball GetComponent lt ball gt () PlayerPrefs.DeleteKey("HighScore") Highscore.text "Best " ((int)PlayerPrefs.GetFloat("HighScore", 0)).ToString() bestScore.text "Best " ((int)PlayerPrefs.GetFloat("HighScore", 0)).ToString() Update is called once per frame void Update() distance player.position.z 500 if (runningScore) LiveScore.text distance.ToString("0") Highscore.text LiveScore.text if (runningScore false) float score float.Parse(LiveScore.text) finalScore.text "Score " LiveScore.text if (PlayerPrefs.GetFloat("HighScore", 0) lt score) PlayerPrefs.SetFloat("HighScore", score) Highscore.text "Best " score.ToString() bestScore.text Highscore.text AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position) else if (score lt PlayerPrefs.GetFloat("HighScore", 0)) bestScore.text Highscore.text while (distance gt 500) Ball.speed 5


How to implement Microwave Signals in Unity? I need to implement microwave signals for object detection in Unity. I know there are raycast sensors in Unity, but can microwave signals be simulated or can a proxy of microwave signals be created in Unity using the raycast sensors?


Calling functions that needs to be on update() So I have a function DialogueRun() for a Dialogue System that changes the line on the dialogue box whenever you click. Which means it has to be in Update(). My test works so far but my next problem is how to make the whole dialogue box only appear whenever I click on a character. I tried making the characters as buttons and it does make the dialogue box show up whenever clicked, but it won't change the dialogue lines because that function has to be in an update method. I'm looking at OnMouseDown() right now but the result will be probably the same. Any ideas? public void DialogueRun() dialogueBox.SetActive(true) dialogue.text textLine nextLine if (nextLine lt textLine.Length 1) if (Input.GetKeyDown(KeyCode.Mouse0)) nextLine 1 else counter dialogueBox.SetActive(false) return


Using unity Rigidbody 2D gravity, how to add to velocity? I am creating a top down game, and have an object I want to create a small bouncy illusion for. Since I dont have anything to collide with I'll have to do it with Scripts. Without Unity I would probably do something like function fall () this.vertical speed this.vertical speed GRAVITY if (this.vertical speed gt TERMINAL VELOCITY) this.vertical speed TERMINAL VELOCITY this.vertical position this.vertical position this.vertical speed However in Unity we have the Rigidbody 2D, so I want to somehow use that for this. if I set rigidBody.velocity new Vector2(1, 0) speed delta , it gets a constant speed, and ignores gravity. How can I add gravity? i.e I want to create a curve like


How to make an illusion where the contents of a 3D shape change based on which face you look through? I remember coming across a Unity 3D tutorial where there was a technique where the contents of a 3D shape change based on which face you are looking at, similar to this screenshot from Antichamber What is this techique called? And how do I implement it into a Unity 3D project? Thanks in advance.


How to create fog effect over specific tiles in dungeon game I'm working on a game in unity and I have areas the player cannot enter blocked off by game objects that are animated sprites that are supposed to look like fog. They don't look that great and I'd like to try something a little more complex, but as a beginner with Unity I don't know where to start. I'd like to make a fog effect that surrounds the tiles that are blocked (Similair to this asset I found. But I only want it to be seen over specific tiles.) I also looked into something like a darkness emitting light, but haven't found anything that works. Here is a picture of the scene hierarchy.


Calculating price increases in a virtual economy I'm trying to design a method to have price increase depending on the number of items bought from shops in my game. I'm fairly new to coding and I am struggling to figure out how to program the increase in price when buying multiple items. Currently the price increase is a percentage increase based on the quantity of items in store, however if I buy 5 items, all 5 items will be charged the same. How can I get it so each item is charged at a different price? I also need a reasonable inflation system, right now my code just determines a price increase based on the percentage of items remaining, but it's very simple and easy to exploit. It looks like this 30 2 28 1 (28 30) 0.07 0.93 1 0.07 1.07 10 1.07 10.7 Rounded up Price 11 I'd like to make this more complex also.


Avoiding overlapping UI Images When an enemy dies in my game, it drops an item on the ground. Enemies may drop multiple items. Currently, the item will always drop a set distance directly below the origin of the enemy when it dies. Therefore, if multiple items are dropped, I only see the most recently dropped item on the ground. Moreover, each item has a UI label clamped to some offset distance above the item. As such, I only see the UI label of the "most recently" dropped item. Because every item dropped by an enemy drops at the same physical location, and because I haven't added code to deal with this kind of thing, the physical game objects overlap with each other and the UI labels of those items overlap with each other. My question is pretty general. What are the best ways to modify my code such that 1) If multiple items are dropped, there will appear to be multiple game objects on the ground (Close enough to the origin)? 2) The UI labels attached to each item will appear as close as possible to that item without overlapping with the other items' UI labels? I would appreciate direct assistance or references that deal with this kind of thing. Thanks.


How to access random material in a renderer besides first without cloning any materials except accessed one? Clones only first material renderer.material Clones all materials in the same renderer renderer.materials 0


Is there a way to check if an object is currently colliding with anything? I need to test from another Script on a different GameObject, whether a particular GameObject is colliding with anything (in particular using trigger). So, for my purpose, I don't need OnCollisionEnter OnTriggerEnter events, but I need something like this if ( myObject.isOnCollision ) do something How can I do this?


Odd behavior in Unity 5.1 2d project prefabs I am very worried something is corrupt in my project. I am making a 2d top down rogue like and am currently using prefabs to generate enemies from. I have started running into an issue where I get a null reference error when trying to iterate a collection of enemies after doing anything on the prefabs, even just selecting one in the editor. If I drag any of the enemy prefabs into the scene then immediately delete it I am fine until I touch a prefab in the inspector again. at one point I was getting "iHasError" 6 times with no info but the unity reinstall fixed that so far I have tried Deleting the library folder Doing a Reimport All Uninstalling and reinstalling Unity Reloading the project from a few days ago Removed a bunch of animations added this weekend Commenting out everything I had done recently in the Enemy script Googled for a couple hours and looking for things that seem similar My prefab is structured Gameobject Sprite Renderer Enemy (Script) About 500 lines Animator (simple 2 sprite swap animation) Does anyone have any ideas? Mike B


How to 9 slice meshes? So let us assume I have a 3D model of a window and I would like to stretch it like a 9 sliced sprite. How would you go by doing 9 slice on meshes? All I found online was about quads. What about more complicated meshes?


How do I get light to go through a window texture in Unity? I'm having trouble with the lighting (I have windows and the light wont go through). How do I get the light to proceed through the glass?


Creating a static 2D background at runtime I'm using unity for a 2D game. We have a lot of props for grass, plants, flowers, etc that are static and always in the background. I'd like to optimize the background and reduce the drawcalls as much as possible by making a big image with the final result of the background. The idea would be to draw on a texture all the elements in the background, and then use this texture as the background. This way a single element has to be drawn. How can I create these background texture at runtime, so it is generated as soon as the scene is loaded?


Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?


Unable to add button in Unity I am wanting to add a button to my scene in order to mute unmute music. I can add the button to my scene, but it's not appearing on the UI. I can't see it anywhere, not on the scene nor the game when running. Below is a screenshot of the editor. You can see the button in front of the camera and in front of the scene itself, but it doesn't appear. I can't actually see a button, just a 'move' control'. Things I have tried Changing the 'Layer' of the button to default Adjusting the z axis (I've tried 0, 1 5, 1 5) Giving the Image (Script) a material inside the Inspector The button has text, which isn't visible either. I could create a sprite and do a raycast, but that seems like overkill just to do a simple click action. Any ideas?


Unity3d Detect a collision between an image and a sphere So, I just realized, an image with BoxCollider2D wont detect any collision with Sphere with SphereCollider. I tried adding a BoxCollider to my image, but it behaves in a weird manner (The Canvas position keeps shifting) So, I can see the only way for it to work is adding a 2D Collider to the sphere? Is there any other better way to solve it? Adding a 2D Collider to the sphere wont cover the whole area


How do I find the face of an object? I'm working on a build mode but the thing of it is the player is able to deform meshes. Part of my build system includes having "snap" points thus I need to be able to find the face and recenter the snap point on deformed meshes. So, how do I find the face of an object and the center of said face? Also how would I find the center? To clarify The end goal is to keep the snap point positioned properly with the face that has been deformed manipulated.


Unity, errors when using Quaternion.Euler to copy rotations In the game I'm creating I have a square that rotates around a parent point, I want the square to always aim upright however (think of a rotating platform). What I've done is simply use child.transform.rotation Quaternion.Euler(0.0f, 0.0f, gameObject.transform.rotation.z) This rotates the child object in the opposite direction so that they're always aiming in the right direction. Except it doesn't, there is some error that piles up with bigger rotations. For example at 90 the child object will be rotated 90.77 instead which is very noticeable given that the game has a grid of sorts and when objects are not aligned to it they instantly pop out. So my question is, is there any way to avoid this error?


Servers do not remove spawned prefab after disconnection I built a multiplayer game with the Unity UNET. For doing this I bought a VPS server. Everything works fine. But sometimes when players want to quit the game, the servers do not destroy him from the scene!!! amp the other players still can see him in the scene till the servers being restarted and ran again!! For quitting the game I wrote this code NetworkManagers.singleton.client.Disconnect() Destroy(NetworkManagers.singleton.gameObject) For more explanation, this is my ConnectionConfig for server amp client MinUpdateTimeout 15 ConnectTimeout 1200 DisconnectTimeout 2000 PingTimeout 500 NetworkDropThreshold 50 OverflowDropThreshold 50 AckDelay 32 AcksType 1 MaxSentMessageQueueSize 150 Why this happening?! Did I miss something?! amp how can I avoid that?!


How to create a 2d procedural spline based road with 2 edge colliders? I am trying to make a top down 2d spline based road that is procedurally generated and endless. The aim is that the player starts inside the road and has to navigate the road and if he touches any of its edges he quot dies quot and the game reloads. I have looked at various resources online for help but can't seem to find the answer. I have tried using the Path creator tool (by sebastian lague) and followed his YouTube series and I have even tried to use Unity's 2d sprite shape asset. The issue is, with the Path creator tool, I am able to create the road procedurally, but I can't figure out how to add multiple edge colliders on its boundaries. The same issue is there for Unity's sprite shape asset except with that, I don't know how to generate the road also (procedurally) and I can't find any tutorial or resource that explains how to do so. Can someone explain an easy way to achieve this (also, it has to be procedurally since my goal is to make it endless)?


Unexpected Behavior Calling method on MonoBehaviour before Start() is called I'm implementing object pooling, though that's not the issue, and a bit confused about the order of operations between Monobehaviours. In the InitGame() method of MyGameManager, I call SpawnEnemy() on the EnemyManager singleton. What I would expect to happen (but is not happening) is for the Awake() method in EnemyManager to be called, then the EnemyManager Start() method, and then and only then, would SpawnEnemy() be called. What actually happens is that EnemyManager Awake() is called, then MyGameManager calls SpawnEnemy(), and when that's done, EnemyManager's Start() method is called last. The docs say, Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. I'm guessing that while my EnemyManager is Active, it is not Enabled, and thus it's Start() method is not called until after the call to SpawnEnemy(). I found it surprising that a method can be called on an object before Start() is called on that object. I can work around this situation by simply including the line gameObject.SetActive(false) in my EnemyManager's Awake() method, and thus the SpawnEnemy() method will find and spawn an object from the pool, but it would be helpful to have a deeper understanding of when Start() is actually called. I've read the docs and whatever I could find, but don't feel like I fully understand. Here is the Manager Singleton designed to easily create XxxxManager classes using UnityEngine public class Manager lt T gt MonoBehaviour where T MonoBehaviour private static T sharedInstance null public static T sharedInstance get if ( sharedInstance null) sharedInstance Object.FindObjectOfType lt T gt () if ( sharedInstance null) Debug.Log("Can't find " typeof(T)) return sharedInstance public virtual void Awake() ... An EnemyManager class using System.Collections using System.Collections.Generic using UnityEngine public class EnemyManager Manager lt EnemyManager gt static private List lt EnemyManager gt enemyControllers public EnemyManager SpawnEnemy(Vector3 location) foreach (EnemyManager controller in enemyControllers) if (controller.gameObject.activeSelf false) controller.gameObject.transform.position location object available controller.gameObject.SetActive(true) return controller Debug.Log("Not enough enemies available in pool.") return null public override void Awake() if (enemyControllers null) enemyControllers new List lt EnemyManager gt () enemyControllers.Add(this) If we SetActive(false) here, we DO get the desired behavior gameObject.SetActive(false) lt base.Awake() protected void Start() wake up and disable self If we SetActive(false) here, we do NOT get the desired behavior gameObject.SetActive(false) lt And I'm using these classes in MyGameManager using System.Collections using System.Collections.Generic using UnityEngine public class MyGameManager Manager lt MyGameManager gt private EnemyManager enemyManager public override void Awake() enemyManager EnemyManager.sharedInstance base.Awake() private void Start() InitGame() void InitGame() enemyManager.SpawnEnemy(new Vector3(0, 0, 0))


Saving predesigned tilemap "rooms" and access them in script in Unity3D? I'm working on a top down rogue like in Unity3D, and I already have some kind of dungeon generation. The next feature I'd like to implement, is to predesign some kind of "event rooms" (i.e. boss fight rooms), so my algorithm could place them at random locations. Is there some kind of Unity feature for this, or I have to implement an editor script which could save and load tilemaps into and from scriptable objects?


Is there an established way to create a 2D XY NavMesh in Unity? Specifically, one in the empty space between colliders, rather than on an XZ plane (more or less) over the surface of a collider? Specifically this is because I have a drone, in a current project, which must follow a target. This target isn't always reachable by shortest path, and I'm currently experimenting with a number of algorithms to find a way to guide it around obstacles. I am on something of a deadline and would like to minimize my work, if I can. I recognize that there are cheats around this, like having it magically appear from off screen at a critical distance. I'm going to implement them in any case, but that's not what this question is about. Unity's NavMesh tools were initially alluring, but as far as I can tell they seem to require a very specific FPS like setup for this project, which I am in no way following. This feels unlike Unity Technologies, and particularly short sighted of them so before I go further, I would like to verify that I'm interpreting all of this correctly. For the sake of stability, I would like to avoid hack around solutions, if possible. All the same, they are welcome.


Finding x and z value in the direction of another object In my game you can drive a car and it has an arrow point to an object you need to drive towards. The arrow pops up above the car using the same x and z value as the car but adding 2 to the y value. What I am trying to do is push the arrow out a little bit toward the object it is pointing to. This way it looks like it is rotating in a circle around the car instead of rotating about it's own center point. This is what I am doing right now if (!(Vector3.Angle(car.transform.forward, obj.transform.position car.transform.position) lt 40f)) arrow.SetActive(true) temp car.transform.position temp.y car.transform.position.y 2f arrow.transform.position temp temp obj.transform.position temp.y arrow.transform.position.y arrow.transform.LookAt(temp)


Tile base Farm Simulation in Unity I am thinking of creating a sprite base 2d top down farm simulation game. The game uses tiles and I was wondering (conceptually) what is the best way to handle the farm tiles. Each tiles should have the following list of features. The player should be able to add seeds to each tile The player should be able to plant a variety of vegetables. Plants should have different stages of growth The player should be able to interact with each tile (dig, cover holes, water, add fertilizer, etc). The farm layout can have a variety of shapes (i.e. Not just a square (9 x 9) or rectangle (9 x 15) a shaped farm.) Currently I have a script that generates a square or rectangle shaped like farm, each tile is a sprite object with a 2D collider. I have come up with a solution for planting and the different stages of growth. However, it isn't the most elegant solution. My current solution is to create prefab for each plant. Then once a seed is planted onto a tile, create a plant object in the location of the tile (using it's vector position), and make the plant a child object to that tile. Each plant will have an age counter that increase when a new day is triggered. To show the growth stage swap the texture depending on the plant's age. My biggest problem with the implementation is that if the players farm is very large the game will have to create a hundreds object, which seem very taxing. Is that a different way achieve these features without the use of so many objects? If so, how would I implement it (conceptual of course). Thanks!


Screen transition effect like subway surfers I would like to know how can I achieve this kind of screen transition effect ? The effect is screen independent. https www.youtube.com watch?v Muh7QFisCfE t 01m57s


Clamping after forcing aspect ratio I'm using the following script to force aspect ratio of 16 9 https forum.unity.com threads force camera aspect ratio 16 9 in viewport.385541 It works perfectly. However now my game objects are allowed to move off the edges. The camera of the game is fixed, and never needs to move or scale. I have changed my code to WorldToViewportPoint for this but half my of character still goes off the edge. void Update() Vector3 pos cam.WorldToViewportPoint(transform.position) pos.x Mathf.Clamp01(pos.x) transform.position Camera.main.ViewportToWorldPoint(pos) private void FixedUpdate() Vector3 pos cam.ScreenToWorldPoint(Input.mousePosition) if (pos.x transform.position.x gt 0.5f) transform.eulerAngles new Vector2(0, 180) animateOgre(true) Vector2 move new Vector2(1, 0) rb.MovePosition((Vector2)transform.position (move speed Time.deltaTime)) else if (pos.x transform.position.x lt 0.5f) transform.eulerAngles new Vector2(0, 0) animateOgre(true) Vector2 move new Vector2( 1, 0) rb.MovePosition((Vector2)transform.position (move speed Time.deltaTime)) else animateOgre(false) My questions are How do I allow the whole character to stay within the Viewport? How can I clamp within the fixed update method rather than making a seperate update method. Is there anyway to prevent character from moving when the mouse is aligned up with the position of the character. Right now I'm using a hacky solution to find if the x difference is 0.5. (If i don't do this the character just moves back and forth when mouse stops)


Detect when an Oculus headset is stationary idle using transform.hasChanged I want to know how can I change in unity the thershold of the method below transform.haschanged At the moment it is so sensitive and it triggers with 0.00001 change in the camera. We have created an Interactive VR video in unity and we want that everytime the user doesnt use the oculus for 30 seconds, a trailer video starts to play! We have created the code below but even when the oculus is on the ground, still moves a bit (too sensitive) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Video public class Trailer MonoBehaviour public int timeOut private int timeOutTimer 0 private Quaternion gameObjectrotation private VideoPlayer videoPlayer public float dynamicRange 100f Use this for initialization public void Awake() Vector3 lastPos videoPlayer GetComponentInParent lt VideoPlayer gt () gameObjectrotation Camera.main.gameObject.transform.rotation InvokeRepeating("ScreenSaver", 0, 1.0f) public void ScreenSaver() timeOutTimer var wMinus gameObjectrotation.w dynamicRange var wPlus gameObjectrotation.w dynamicRange var xMinus gameObjectrotation.x dynamicRange var xPlus gameObjectrotation.x dynamicRange var yMinus gameObjectrotation.y dynamicRange var yPlus gameObjectrotation.y dynamicRange var zMinus gameObjectrotation.z dynamicRange var zPlus gameObjectrotation.z dynamicRange var cameraW Camera.main.gameObject.transform.rotation.w var cameraX Camera.main.gameObject.transform.rotation.x var cameraY Camera.main.gameObject.transform.rotation.y var cameraZ Camera.main.gameObject.transform.rotation.z if (cameraW gt wMinus amp amp cameraW lt wPlus amp amp cameraX gt xMinus amp amp cameraX lt xPlus amp amp cameraY gt yMinus amp amp cameraY lt yPlus amp amp cameraZ gt zMinus amp amp cameraZ lt zPlus amp amp timeOutTimer gt timeOut) Show video videoPlayer.gameObject.SetActive(true) videoPlayer.Play() else Hide Video videoPlayer.gameObject.SetActive(false) videoPlayer.Stop() videoPlayer.frame 1 if (cameraW gt wPlus cameraW lt wMinus cameraX gt xPlus cameraX lt xMinus cameraY gt yPlus cameraY lt yMinus cameraZ gt zPlus cameraZ lt zMinus) timeOutTimer 0 gameObjectrotation Camera.main.gameObject.transform.rotation Any help would be appreciated! Cheers


Unity Change Sceneview to camera view On selecting camera, I get the camera preview. In Unity, while editing the scene, I wish to switch in such a perspective view that is exactly visible by the main camera. Is there a short cut to change the view?


Why is this Mono Behavior in the animator? I'm looking through the 3D Game Kit from the asset store to accustom myself with the animator, and I'm just wondering what this is referring to. I was looking into controlling MonoBehaviors through the animation controller the other day and thought I had come to the conclusion that it couldn't be done directly, so what's this?


When to use a blend tree vs state machine for animation Im an experienced game dev hobbiest making my first game with 3d animated characters (in Unity) and am struggling to figure out when to use blend trees vs animation state machines. I understand both conceptually but have seen both blend trees and animation state machines used for character animation in a bunch of tutorials both from Unity and from other sources. I am not sure when why one is better than the other am hoping someone can point me in the right direction. My game is a 3rd person action rpg a'la WoW or KOTOR or Mass Effect (different systems I know but the perspectives and combat styles are kinda close at a high level). I have tons and tons of animations for attacks, blocks, feigns, deaths, walking, running, jumping, shooting etc but I am unclear on how to sequence them together naturally. I have seen blend trees used for locomotion which makes sense to me when trying to keep character motion fluid, but I dont understand how to go from that blend tree to an attack state and nothing I have seen so far has gone past locomotion (no attacks etc). Do I need to make blend trees from my motion states to attack death dodge states? Do I have more control using just state machines? Im a little cautious of state machines because of the transition bloat that is so common with them and because I suspect there is greater potential for janky animation sequencing without blending. I am planning to use the Unity character controller and write my own logic scripts to drive it. For the AI I will be using the built in nav mesh agents. Are character controller animations handled differently than the AI ones? Any insights would be more than welcome! Thanks


Rolling on collision I'm having a small issue where if I collide with another object (let's use a simple cube) with my player (this player is just a sphere), the ball will infinitely roll in the opposite direction and WILL NOT STOP. my code is as follows using UnityEngine public class PlayerController MonoBehaviour private Rigidbody rb private float moveHorizontal private float moveVertical public float moveSpeed Start is called before the first frame update private void Awake() rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() moveHorizontal Input.GetAxis("Horizontal") moveVertical Input.GetAxis("Vertical") private void FixedUpdate() MovePlayer() private void MovePlayer() Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement moveSpeed) I even changed the ForceMode to ForceMode.Impulse so be able to see what it was doing a little easier, and it is in fact slowly rolling away infinitely with no way to stop it. Both objects have a Rigidbody for them to be able to react to being hit. This is my first time messing with 3d. I tried to do something like this to make it not roll away on impact private void OnCollisionExit(Collision collision) if (collision.collider.gameObject.layer ! LayerMask.NameToLayer("Ground")) rb.velocity Vector3.zero But then if I want to jump on the cube (lets say the cube is an enemy and I'm jumping on it to kill it), then it acts very wonky each time it touches the edge of the cube and I haven't made it on top (again, because the velocity is being set to zero). I am all out of ideas and would love some input here! EDIT I now realize that the ball will slowly roll forever even without collision and just simply moving. I am very lost !


Why are my records duplicated when writing them to a file? I am writing data to a file every two seconds. I used InvokeRepeating and everything is Ok except that every record is saved 3 times in the file void Start() File.WriteAllText(filePath users, "timestamp" "," "id" "," "pos" "," "rot" System.Environment.NewLine) InvokeRepeating("SaveUsersTracking", 1.0f, 2.0f) void SaveUsersTracking() save this data every two seconds... File.AppendAllText(filePath users, System.DateTime.Now.ToString() "," "U1" "," "( 2.7, 1.3, 1.8)" "," "(0.2, 0.7, 0.2)" System.Environment.NewLine) My results look like timestamp,id,pos,rot 4 20 2019 8 09 47 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) 4 20 2019 8 09 47 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 47 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 49 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) 4 20 2019 8 09 49 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 49 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 51 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) 4 20 2019 8 09 51 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record 4 20 2019 8 09 51 PM,U1,( 2.7, 1.3, 1.8),(0.2, 0.7, 0.2) I don't need this record


Prevent keyframe interpolation in imported model animation in Unity I made first person model in blender. It also has animations in it. Most of animation works fine, but in some cases, Unity's keyframe interpolation makes wrong result. Note that animation was made by 60 frames per second in Blender. To explain my problem, you have to see my model As you can see there are two magazines. Each named Mag1 and Mag2 and Mag1 is the magazine that attached to the gun. Mag2 is always located very bottom of the screen so that it is impossible to see, except reloading animation. While reloading, first pull out the mag1 from the gun and put in the mag2 to the gun. And here is the trick, after mag2 is attached to a gun, hand put the mag1 somewhere, maybe magazine pouch. Anyway as soon as mag1 disappeared from the screen, it switches mag1 and mag2 immediately at only single frame. So mag1 is now move back to the gun and mag2 is also reloated to bottom. In Blender, it seems nothing wrong but in Unity is quite different. As soon as mag1 disappeared, it doesn't switched immediately and it moves smoothly animated so I can see that magazines were moved. I'm pretty sure that this happens maybe Unity interpolates keyframes. I already turned off Animation Compression option and resample curves, but still won't worked. This is the video that I made to explain my situation https www.youtube.com watch?v 7aew959ejL4 amp feature youtu.be Is there a way to "turn off" that interpolation? I want to disable it only that frame. Unity doesn't allow me to edit animation clip, so I just duplicate animation clip and change the option(I don't know what it called) to "Flat" and use that clip instead, but still have same problem. (Note that it wasn't easy because Unity doesn't show me the animation if I duplicate and modify it) I struggled this issue almost a year and still figuring out how to fix it, and I think it's time to solve it. Any advice will very appreciate it.


How can I change a variable value in specific time duration according to animation clip time length? I will change my question with more details to make it more clear In the Assets I created Animator Controller and Animation Named them both FPSController. FPSController is the object I want to animate it's rotation on the Z from 50 to 0 Then I opened the Animator window and dragged the Animation into the Animator window Then I opened the Animation window and recorded the clip The rotation on Z is going from 50 to 0 in 7 seconds. I'm rotating the FPSController on the Z from 50 to 0 This is the Animation part and this is working fine. The FPSController(player) is starting when the Z rotation value is at 50 and slowly move to 0. Now The game is start when the whole camera is blurry. For this I'm using Post Processing. Next step was to create a profile of the Post Processing called it CC and this profile I dragged in the Hierarchy to the FPSCamera In the FPSCamera I dragged to it a script name Post Processing Behaviour and then dragged to the script in the Inspector the CC profile This way the Post Processing effects affecting the camera view So to make it clear I'm rotating on the Z the FPSController by animation. And on the FPSCamera I'm using the Post Processing for making effects. This is how the game start. This is the game view screenshot. The game start when everything is blurry and the FPSController(player) is rotating to the right by 50 degrees Now the part of the animation of rotating the FPSController by 50 is working fine. While it's rotating the FPSController I want slowly by the same time in this case 7 seconds to change the blurry effect and make the picture clear once the animation end. The property of the Post Processing CC profile I need to change is the focalLength. By default I start it with the value of 300. And I need in 7 seconds to change it from 300 to 0. This is the script I ended with so far The script is attached to the FPSCamera using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DOFControl MonoBehaviour public PostProcessingProfile postProcProf public Animator anim private float clipLength private void Start() AnimationClip clips anim.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length InvokeRepeating("incrementSpeed", 300, 0.1f) void incrementSpeed() var dof postProcProf.depthOfField.settings dof.focalLength 1f postProcProf.depthOfField.settings dof I'm getting the animation clip time length 7 seconds. But the part with the InvokeRepeating is not working. I want to incrementSpeed the focalLength down from 300 to 0 by 7 seconds. Not sure if using InvokeRepeating is the right way at all.


Getting position of a coordinate on the surface of a sphere So I want to create a object B close to another object A, but I'm trying to avoid that A covers B I have thinking how to achieve that. Take a look of the following drawing I have been thinking in a solution in a math geometry way before searching for some Unity3D function to solve the problem. I have realise A and B would be on the same surface if the camera is within a sphere with radius c A. So I guess the solution can be related to get a point at a B at a distance A B from A on the surface of the sphere with radius c A. Does it has sense? Any other idea? How to do it with maths and Unity?


A coroutine to rotate one point around another by a given angle without referring to game object I need to rotate a point around another point (in 2D) by a given angle over a given duration, independent of game object (meaning that I've manually created the points and they're not positions from a game objects transform ) as shown in the image below where point B rotates to C by and angle e around A by with radius AB. Using a coroutine would be preferable. UPDATE Based on links provided by MichaelHouse I wrote the following methods to rotate a control point over time by a certain angle but it rather moves to a point (which is not the desired point) immediately to another point, not by the right angle. I'm not sure what I've done wrong. public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle) return angle (point pivot) pivot IEnumerator RotateControlPointWithDuration(Vector3 point, Vector3 pivot, float duration, float angle) float currentTime 0.0f float ourTimeDelta 0 ourTimeDelta Time.deltaTime float angleDelta angle duration how many degress to rotate in one second while (currentTime lt duration) currentTime Time.deltaTime ourTimeDelta Time.deltaTime Vector3 newPos RotatePointAroundPivot(point, pivot, Quaternion.Euler(0, 0, angleDelta ourTimeDelta)) points 0 new Vector2(newPos.x, newPos.y) yield return null IEnumerator runMovement() yield return new WaitForSeconds(2.0f) Vector3 point new Vector3(points 0 .x, points 0 .y, 0) Vector3 pivot new Vector3(points 3 .x, points 3 .y, 0) StartCoroutine(RotateControlPointWithDuration(point, pivot, 2.0f, 45.0f)) UPDATE 2 I've tried another approach using trig functions, but the point moves erratically before finally arriving at a point that seems to be the right point. Please see the code below IEnumerator runMovement() yield return new WaitForSeconds(2.0f) Vector2 pivot points 3 StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f)) IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle) float currentTime 0.0f float ourTimeDelta 0 Vector2 startPos points 0 ourTimeDelta Time.deltaTime float angleDelta angle duration how many degress to rotate in one second while (currentTime lt duration) currentTime Time.deltaTime ourTimeDelta Time.deltaTime points 0 new Vector2(Mathf.Cos(angleDelta ourTimeDelta) (startPos.x pivot.x) Mathf.Sin(angleDelta ourTimeDelta) (startPos.y pivot.y) pivot.x, Mathf.Sin(angleDelta ourTimeDelta) (startPos.x pivot.x) Mathf.Cos(angleDelta ourTimeDelta) (startPos.y pivot.y) pivot.y) yield return null


How to detect collision position and that position's texture color in Unity? I have a prefab and I use Circlecollider2D for physics operations. I want to detect the color of the contact position of the collided objects ? Is is possible by using Unity's collider classes ?


Difference between unity scripting backend IL2CPP and Mono2x IL2CPP is a Unity developed scripting back end which you can use as an alternative to Mono when building projects for some platforms. Note IL2CPP is only available when building for the following platforms Android AppleTV, iOS , Nintendo 3DS, Nintendo Switch, Playstation 4 Playstation Vita, WebGL ,Windows Store, Xbox One I have a project(unity 5.2) which has switched for Android deployment. I tried to switch my scripting backed from Mono2x to IL2CPP and its showing me that IL2CPP on Andriod is experimental and unsupported So, my simple question is that if it is still not supported then why the option has included, what is the fundamental difference between IL2CPP and Mono2x. Why I switched to IL2CPP scripting backend ? what are its pros and cons? I have also checked in unity 5.5.2 there is not IL2CPP option in windows platform deployment.