just download first assetbundle In the Start of my scenes I call the method that downloads the assetBundles for that scene. The problem is that it only downloads the first assetBundle from the list, the second does not download it. My code is Note The Debug that shows the url shows the correct url both times, first http mihost.com assetbundles asset1 and then http mihost.com assetbundles asset2. However, in the Debug that shows the assets 'added' in both cases it shows the name only of those in asset1 public virtual IEnumerator LoadBundleFromServer() var AssetPathOnServer "http mihost.com assetbundles " var assetBundleNames new List lt string gt () assetBundleNames.Add("asset1") assetBundleNames.Add("asset2") for (int i 0 i lt assetBundleNames.Count i ) var currentAssetBundleName assetBundleNames i var url AssetPathOnServer currentAssetBundleName Debug.Log("url " url) var request UnityWebRequestAssetBundle.GetAssetBundle(url) yield return request.SendWebRequest() if (!request.isHttpError amp amp !request.isNetworkError) var asseBundle DownloadHandlerAssetBundle.GetContent(request,) Debug.Log("count assets " AssetNames.Count) for (int j 0 j lt AssetNames.Count j ) string assetName AssetNames j AssetBundleRequest asset asseBundle.LoadAssetAsync lt AudioClip gt (assetName) yield return asset AudioClip myClip asset.asset as AudioClip if (!assetDictionary.ContainsKey(assetName)) assetDictionary.Add(assetName, myClip) Debug.Log("added " assetName) asseBundle.Unload(false) else TODO aqui hay que mostrar un error Debug.LogErrorFormat("error request 0 , 1 ", url, request.error) public abstract List lt string gt AssetNames get


AudioClip is empty saving recording from Microphone EDIT I updated the code to what I have currently. I'm not sure why but, the editor and my platform complained when I put the WWW in a co routine, it seems to load the audio clips to the object but I cannot play them. In a script attached to the object I wait until the Audio Clip is loaded before I try to play it. So I am trying to record some Audio through the microphone and then save an AudioClip to the disk as a .wav file and also save the filepath as a playerpref and then later I can come back and load the string into a url but, for some reason the Audio Clip doesn't get loaded properly as I can see that there is an audio clip on my audio source in runtime but, it has no name and it has no sound on it. However, when I press play in the inspector I can hear my sound I am using SavWav.cs to save my audio clips to .wav files. Here is the url(filepath) I am sending to my load method string filename string.Format( "CapturedAudio 0 n.wav", Time.time) string filepath Path.Combine(Application.dataPath, filename) Here is the method I am using to get the AudioClip private void SpawnObject(string savedNames, Vector3 savedPositions, Quaternion savedRotations) GameObject cubeToSpawn Instantiate(cube, savedPositions, savedRotations) WWW www new WWW("file " savedNames) cubeToSpawn.GetComponent lt AudioSource gt ().clip www.GetAudioClip(false, false, AudioType.WAV) The obj is just a cube with an AudioSource attached to it that I instantiate prior to calling this method above. The filepath works fine for saving but, for some reason it doesn't want to load the audio clip. Any help would be greatly appreciated.


Unity, Pixel Perfect and Scaling I am totally stuck on with pixel perfectness of the game. I have tried a few pixel perfect camera assets, but they have lots of issues considering scalability. is it normal that these cameras zoom in and out, instead of scaling the camera screen when using different resolutions for the game. Because this is a huge problem for me, cause i need to make a game for aspect ratio of 16 10, and every resolution that has the same aspect ratio is needed to scale it correctly keeping the pixel perfectness. The ortographic camera size is dependent of screen width (width PPU 2) So it always zooms in or out with different resolutions. Question is Is there a way to make it scale the game sprites instead of zooming the view?


Creating placement grid in Unity I'm fairly new to C and Unity, so I don't really know much about it. I want to create an RTS like game where you have a huge grid that the whole world is placed on. Then you can place houses, walls etc on the tiles just like a lot other RTS games (i.e. Age of Empires, Stronghold Series etc). How would I go about this in Unity? I could imagine having some Terrain World manager that handles all the models and objects that you can interact with etc. And probably a lot of prefabs too with the different items, soldiers and so. So if anyone have any smart way of doing this or maybe a link to a tutorial explaining, then the help would be greatly appreciated.


Is there a way to hardcode a JSON file into a Unity build? I'm currently creating an external tool to generate dialogues that are exported as JSON files. The idea is that after you create a dialogue (as a JSON), my main Unity project reads that file and generates a dialogue. Right now it works just fine, but the JSON is an external file that you can modify even after compiling the game (of course). Is there a way to actually "hardcode" that JSON file so that the game doesn't need to find and read the file every single time it plays?


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)


How can I get my player's character to slide along a rail? I am creating a snowboarding game and would like my player to be able to jump on a rail and move along it if it lands on it. I have no idea how to approach this. I have already tried using ray casts and waypoints but nothing works. I need to make sure the player moves along the rail, from any point that the player jumps onto it e.g. if they land in the middle of the rail they keep following its curve from that point. The rails are not straight and have curves on them. How can I get my player to be able to jump on a curved rail like this, and start sliding from the point they jumped onto it?


How to rotate a 3D character on top of a plane with an isometric picture on it How to calculate the angles of the 3d charater so that it fits into the isometric environment projektet on a 2d plane? Also, how do you calculate the rotation of my character? What I want to achieve Describing the scenario


Unity crashes if there are more than 4 terrains please can you help me with the issue that I face, that is, I decided to create open world game by creating several terrains and connect them together in Unity and firstly respective size of the terrains was 500X500 then I decided to add more terrains to make game world bigger and once I added the 5th terrain in the scene, Unity simply crashed. Later, I thought what if I increase the sizes of terrains rather than create more new terrains then the sizes of originally created terrains were changed from 500X500 to 800X800 and again Unity crashed. Please guys help me out with that and how to overcome that and I am just trying to create game without using any ready plugins and, say, try to create the game on my own. Thank you for your attention))).


Why do I get this warning when using a null conditional operator? In the OnTriggerEnter2D function of my Bullet script, I have the following code private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag("Enemy")) var enemy other.GetComponent lt Enemy gt () enemy?.Death() The reason for the null conditional operator (the question mark) in enemy?.Death() is because the Death function actually destroys the Enemy component script, so it suppresses an error when the bullet hits the enemy again. It's supposed to be shorthand for if (enemy ! null) enemy.Death() The code works the error is suppressed. However, the IDE that I'm using, Jetbeans Rider, gives the following warning '?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity object. What does that mean exactly? Should I continue using the null conditional operator?


How to create button prompts for interactable objects in Unity? I have a class of objects tagged as interactables that my player can interact with when within range. When my player is near them, I want to display a button prompt at the bottom of the screen, along with a description of the type of interaction possible (for example, "inspect", "use", etc.). I want to account for the possibility that the player might be within range of two or more of them at once, and thus allow him to toggle through them, displaying their button prompts in turn. If my player interacts with something which generates a text box or other modal, I want the button prompt to disappear, but to return when the text box or modal is closed. Any advice on how to go about achieving this? I've done it in the past in different engines, but I have always been unhappy with how convoluted my method was. I'd like to hear how others might tackle this. Given how common this kind of thing is in games, I'm surprised I haven't found a good tutorial on it yet. You can be as general or as specific as you'd like in your answer.


How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?


how to prevent call on OnValidate() when running game I need OnValidate() to be called only when I am designing my level (placing game objects at their respective positions and setting properties before running the project). But I don't want it to be called when I run the project. I can manually comment it out, but that will take a lot of time, since I have several OnValidate() calls. How can this be done, if it is possible?


Open website URL from image marker using ARCore in Unity How can I open a website URL from an image marker using ARCore in Unity? I am trying to build an AR app using ARCore in Unity. I have ten images and ten url links to websites, I need to link the ten images with those ten url links. When I scan the image with the phone's camera, I want the URL to open directly. I've done image tracking with video before, but now I want to do image tracking linking to a URL.


Terrain Navmesh build, rebuild smaller pieces of the bigger navmesh terrain. UNITY when the area is very big and AI characters are required to walk a larger distance, it would be beneficial to have the large navmesh ready for finding a path. when we change the height of the terrain in runtime small areas of the terrain should be updated. so the buildnavmesh method is kind of an overkill. and the localnavmesh builder as a large type would be inefficient. how do we dynamically change a small part of a larger navmesh? advice or help would be highly appreciated.


Panning value of 2nd GameObject's AudioSource is not initializing I'm making a prototype and stuck in a problem where two GameObjects swap but there values of panStereo of AudioSource is not initializing from a float array which contains all the default values of panStereo of all the GameObjects in a scene panningArray new float Inventory.bowlsManager.BowlPanningValues.Length for (int i 0 i lt Inventory.bowlsManager.BowlPanningValues.Length i ) panningArray i Inventory.bowlsManager.BowlPanningValues i Selectable false SelectedBowl.GetComponent lt AudioSource gt ().spatialBlend SelectedBowl2.GetComponent lt AudioSource gt ().spatialBlend 1 iTween.MoveTo(SelectedBowl, iTween.Hash( quot position quot , temp2, quot time quot , transitionspeed)) iTween.MoveTo(SelectedBowl2, iTween.Hash( quot position quot , temp, quot time quot , transitionspeed)) SelectedBowl.GetComponent lt Renderer gt ().material SubsituteMaterial SelectedBowl2.GetComponent lt Renderer gt ().material SubsituteMaterial int SelectedBowlIndex Array.FindIndex(Inventory.allBowls.ToArray(), x gt x SelectedBowl.GetComponent lt Bowl gt ()) int SelectedBowlIndex2 Array.FindIndex(Inventory.allBowls.ToArray(), x gt x SelectedBowl2.GetComponent lt Bowl gt ()) print(Inventory.bowlsManager.BowlPanningValues SelectedBowlIndex2 ) print(Inventory.bowlsManager.BowlPanningValues SelectedBowlIndex ) val1 BowlPanning(SelectedBowl2 , panningArray SelectedBowlIndex ) val2 BowlPanning(SelectedBowl , panningArray SelectedBowlIndex2 ) Here is my bowl panning function public float BowlPanning(GameObject BowlRequire,float value) BowlRequire.GetComponent lt AudioSource gt ().panStereo value return BowlRequire.GetComponent lt AudioSource gt ().panStereo


How to get dynamic RigidBody rotation tilt on uneven platform? I have a rigid body with PolygonCollider2D which has some complex circular shape and I'm using uneven platform. Im using Following code to move the object forward CharacterRigidBody.velocity new Vector2 (speed, CharacterRigidBody.velocity.y) Problem The rigid body keeps on rotating when it moves forward. I want the character to move without rotation on asymmetrical platform(above).But i don't want to freeze rotation because i want the character to tilt when climbing or decending platform. My RigidBody2D config(I'm using unity 5.1.2) Can collider do anything with this problem?


Main camera transform.forward becomes up and down when looking from above The camera script is a 3rd person orbit camera, when I look straight it does what it supposed to do which is walk in the direction the camera is pointing, but when the camera is looking down from above the player, the camera's forward is now up. This means when I press W to go forwards I go into the ground and when I press S it goes upwards. Here is my movement script private void FixedUpdate() float x Input.GetAxisRaw("Horizontal") float z Input.GetAxisRaw("Vertical") Vector3 moveDirection Vector3.zero moveDirection Camera.main.transform.right moveDirection Camera.main.transform.forward moveDirection.y 0 Rotation if (x ! 0 z ! 0) anim.SetBool("Walking", true) if (x ! 0) transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.4f) else transform.localEulerAngles new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z) else anim.SetBool("Walking", false) Moving if (Input.GetKey(KeyCode.LeftShift) amp amp !idle) anim.SetBool("Running", true) rb.position z Camera.main.transform.forward Time.deltaTime runSpeed rb.position x Camera.main.transform.right Time.deltaTime runSpeed else anim.SetBool("Running", false) rb.position z Camera.main.transform.forward Time.deltaTime moveSpeed rb.position x Camera.main.transform.right Time.deltaTime moveSpeed while I'm asking, the movement script gets doubled when two keys are pressed, how do I fix it while keeping the same functionality of my current movement script?


How to prevent an object with high velocity from passing through a collider? Consider a simple 2D platformer. I have a BoxCollider2D on the player object and a TilemapCollider on the ground below(grid). I created a quot jump quot script for the player through which the player object jumps and comes back to the ground, clean. But when the player object goes relatively high and comes down with a high velocity, it doesn't collide with the ground(grid) instead it goes right through the tilemap collider and into the void. How can this behaviour be prevented?


Unity Collision Difficulties (How do I make a ground in unity with lots of pieces that doesn't have poor collision?) So I'm working on this game that I came up with the idea for while watching the Unity Roll a ball tutorials. So it's probably important to note that I'm extremely new to game design and I don't have a whole lot of experience in programming. So the game idea that I had is a lot more complex than what it should be for someone who's pretty much completely new to game design, so I guess I'm trying to break it down into smaller bits until I have enough experience to build it into a cohesive game. Currently what I want to work on is a game where you play as a sphere rolling down a plane with open edges so you can fall off. There are walls that you have to avoid, and if you run into them it will take away from the space between the walls and the edge of the plane. I guess I was sort of thinking of having a sort of similar visual style as bastion in that sense. The way I thought I would go about this is to break the plane up into smaller squares and then do some programming so that when you run into the walls the smaller squares at the edge of the plane fall off. Though before I could even get to programming I ran into a big problem. Because of the way Unity physics work and the way I built the ground, the player collision with the ground is god awful. When I was just testing it with some basic controls the ball would roll all choppy and if I picked up enough speed it would start to jump. I assume this is because it's colliding with all the edges of the grid system that I built. Does anyone know of any way I can program the edges to not interact with the player? Or if there's a better way to go about doing this?


How do I get my fish to face the right way? I'm making this 2d collecting game in Unity where you collect fish. However I can't get them to face the direction they are going. I've asked on some Discords and got no answer. Thanks in advance. Here's is the video of the fish. And here's the code using System.Collections using System.Collections.Generic using UnityEngine public class NewBehaviourScript MonoBehaviour public float minY public float maxY public float minX public float maxX public float speed public float maxZ Vector2 targetPosition Start is called before the first frame update void Start() targetPosition GetRandomPosition() Update is called once per frame void Update() if ((Vector2)transform.position ! targetPosition) transform.right (Vector2)targetPosition transform.position Vector2.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) else targetPosition GetRandomPosition() Vector2 GetRandomPosition() float randomX Random.Range(minX, maxX) float randomY Random.Range(minY, maxY) return new Vector2(randomX, randomY)


What is the proper way to handle data between scenes? I am developing my first 2D game in Unity and I have come across what seems an important question. How do I handle data between scenes? There seems to be different answers to this Someone mention using PlayerPrefs, while other people told me this should be used to store other things like screen brightness and so on. Someone told me that the best way was to make sure to write everything into a savegame everytime that I changed scenes, and to make sure that when the new scene loads, get the info from the savegame again. This seemed to me wasteful in performance. Was I wrong? The other solution, which is the one I have implemented so far is to have a global game object that isn't destroyed between scenes, handling all the data between scenes. So when the game starts, I load a Start Scene where this object is loaded. After this ends, it loads the first real game scene, usually a main menu. This is my implementation using UnityEngine using UnityEngine.UI using System.Collections public class GameController MonoBehaviour Make global public static GameController Instance get set void Awake () DontDestroyOnLoad (transform.gameObject) Instance this void Start() Load first game scene (probably main menu) Application.LoadLevel(2) Data persisted between scenes public int exp 0 public int armor 0 public int weapon 0 ... This object can be handled on my other classes like this private GameController gameController GameController.Instance While this has worked so far, it presents me with one big problem If I want to load directly a scene, let's say for instance the final level of the game, I can't load it directly, since that scene does not contain this global game object. Am I handling this problem the wrong way? Are there better practices for this kind of challenge? I would love to hear your opinions, thoughts and suggestions on this issue. Thanks


Lightmapper artifacts I really don't understand why this is creating these kinds of artifacts. I'm starting to think something is wrong with Unity. There are clearly no overlapping faces on the Model. There is enough of a margin to remove all chances of bleed. Yes the lid is a seperate object but any UV's of the lid and it's box are not overlapping. Thix odd pixelation occurs no matter the quality. It happened all the time sofar here and there and it forced me to replace a few objects in older projects. No idea what causes it. Really sick and tired of this. Edit when I rotate the crate by 90 degrees the artifacts appear on the adjacent side of the cube. From the perspective of the camera it would be the same side. So clearly it's not the UV's or anything. Lightmap settings Object Import settings


Refactoring out asynchronous webrequests to an interface I have a Unity project with UnityWebRequest calls in it. They are all working correctly, but I'd like to refactor them out (they are implemented pretty badly at the moment). The way I would like to do this is with a WebRequestSender class that implements an IWebRequest interface. Each call would return a WebResult object that I can use. public class WebResult public long ResponseCode get set public bool IsError get set public string Value get set public static WebResult Success(long responseCode, string value) return new WebResult IsError false, ResponseCode responseCode, Value value public static WebResult Failure(long responseCode) return new WebResult IsError true, ResponseCode responseCode, I'm having trouble understanding how to implement the interface, as these calls are asynchronous. Ideally, in the script when I need to make a call, I would have one line, like so WebRequest.Login(form) and that would return the result. I'm not sure what I have to add for it to wait for the call, or however it is executed. public interface IWebRequest WebResult Register(WWWForm form) Do I need to alter the return object so it allows for asynchronous calls? Or do I have to change the implementation the call of the implementation? As for my implementation, it doesn't work. The return statement on the Register function isn't called (even if it was, I'm not sure the return object would be populated?) Sample below public class WebRequestSender MonoBehaviour, IWebRequest private const string REGISTER URL "http localhost 51044 api Users Register" private WebResult webResult public WebResult Register(WWWForm form) StartCoroutine(MakeWebCall(REGISTER URL, form, (UnityWebRequest webRequest) gt RegisterDelegate(webRequest))) return webResult private void RegisterDelegate(UnityWebRequest webRequest) if (webRequest.isHttpError webRequest.isNetworkError) webResult WebResult.Failure(webRequest.responseCode) else webResult WebResult.Success(webRequest.responseCode, webRequest.downloadHandler.text) private IEnumerator MakeWebCall(string url, WWWForm form, Action lt UnityWebRequest gt finishDelegate) using (UnityWebRequest www UnityWebRequest.Post(url, form)) yield return www.SendWebRequest() finishDelegate(www)


Drag Object to Collide Unity Please help, I am developing a 2D game for a school project and I want to drag the apple to the think box then when it collides, the apple will go back to the original position then it will add 1 point to the score. I'm just new to Unity. So please help


Unity Game objects in scene load incrementally and not at the same time I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images. In order to load this data in the scene, I make a lot of UnityPlayer.UnitySendMessage(GameObject,Function,Params) calls to many C scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc. Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly. How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?


Unity not opening in Ubuntu I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens. These are my system specifications. I was running Unity on the same computer, several months ago, using Windows. Model Thinkpad R500 Processor Intel Core 2 Duo CPU P8600 2.40GHz 2 RAM 2Gb DDR3 RAM Storage 155Gb HDD Graphics Card ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX Why is it doing this? Is there a problem with the latest build? What should I do to fix it?


how to automate the game testing? I am new into this field of testing. I just developed a basic game using unity engine but i want to test it. I have checked with selenium but i don't know how to get the value that is being returned which has the information of the action that is being performed in the game. If i am able to get the value then i will be able to take necessary action accordingly.


How do I prevent inappropriate ads from appearing in my game? My game implements Unity ads, and is designed with a universal audience in mind. As such, I would prefer not to have 18 ads (or even 13 ads depending on the circumstances) appearing in it, especially since it would appeal to younger audiences as well. My question is then, how do I prevent age inappropriate ads from appearing? Is there a way to simply set the age limit or content restrictions on Unity ads? The only setting along those lines that I can find is the COPPA toggle, and that would cause other issues (not to mention that it wouldn't do anything to the ads). I've looked in the dashboard for a while, and I've tried to research it beforehand, but the fact that they've shifted to a centralized services page, redirected all the old links (breaking them in the process), reorganized the settings in the dashboard, and 404d their FAQ post on the topic doesn't help either. Blocking ads based on a rating would work too, as I would have to get one because I am publishing to Google Play. Edit The second link only 404s some of the time. I just happened to get it every time before asking this question. Bad luck, I guess.


UNITY Prevent 3D Text Render Trough All Object Without Shader im tired of those answer i found trough search engine that just keep saying " the trick is to modify the shader " without thinking because they want to gain reputation , in my case , i have 2 3D text , one of them using special font and the other one using default font , and the shader to prevent the text render trough all object from http wiki.unity3d.com index.php?title 3DText is not working and giving weird white square plus i don't want to change from default Arial font because i want to make them look different , i also cannot use sprite as background because i need to change their color trough script to give some effect , this is my picture showing my problem If the picture is not clear , go here https i.stack.imgur.com hLqC9.png The menu dropped is at Z 100 while the background is at Z 20 , as you see , the text is rendered while the other not ( such as the border , ect ). And this is the picture when my special font without using the shader If the picture is not clear , go here https i.stack.imgur.com vbrQ1.png Now the picture of my special font using the shader If the picture is not clear , go here https i.stack.imgur.com hMAR2.png Is there any possible way to prevent the text rendered without shader change the background to sprite ? Im sorry if this already asked somewhere , i just cannot find it at search engine ( neither here ) .


Material tiling and offset in unity Ambiguity What exactly is the difference between Tiling the material and Offset of material? Need to do I need the material to be repeated n times on the object where I need to set the value of n via script.How do I do it? It seems to happen through Tiling(tried via inspector) but again what is difference between mainTextureOffset and setTextureOffset? Tried Following is the line of code that I tried to repeat the texture n number of times on an object(repeat across the width of object), but it does nothing significant that I can see.


Fixed distance between character and ground whatever slope value I am working on character moving on any ground meaning whatever slope degree ,the result i got is the character does not moving on just shake in his place the following the code i wrote public float speed 1 bool isMoving Transform childPosition Rigidbody rb private void Start ( ) rb GetComponent lt Rigidbody gt () Update is called once per frame void FixedUpdate () if (Input.GetAxis("Horizontal") gt 0) rb.velocity new Vector3(1f, rb.velocity.y, rb.velocity.z) else if (Input.GetAxis("Horizontal") lt 0) rb.velocity new Vector3( 1f, rb.velocity.y, rb.velocity.z) else transform.position transform.forward Time.deltaTime speed detectRoad() private void detectRoad() Ray ray new Ray(transform.position, transform.up) RaycastHit hit if (Physics.Raycast(ray, out hit)) transform.rotation Quaternion.FromToRotation(transform.up, hit.normal) transform.rotation if (hit.distance lt 0.6f) transform.position transform.up Time.deltaTime else if (hit.distance gt 2f) transform.position transform.up Time.deltaTime This animated gif is about what I want


A way around the deprecation of AppInvite in Unity I was using FB.Mobile.AppInvite, but according to the Facebook documentation, it is deprecated. So, how could I send an app invite?


I'm trying to write a randomly patrolling AI for my 2D Platformer I'm trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat quot sentient quot enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving. The problem is, it doesn't seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don't occur as frequently. I need to know what I've done wrong here. Thanks. void Update() RNG behaviour Random.Range(0,3) jumpSpeed Random.Range(1,5) clock timer Time.deltaTime time private float waitTime 2.0f private float timer 0.0f void MoveRandomizer() if((Mathf.Round(timer waitTime)) 0) if(behaviour 0) movingRight false if(behaviour 1) movingRight true if(behaviour 2) rb.velocity new Vector2(rb.velocity.x, jumpSpeed)


Missing UI options in Inspector window when I import FBX files I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files. In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well. This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.


How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?


How to find the angle of an arc for reflection I am using the following code to calculate points for a circle arc drawn with a Line Renderer. for (int i 0 i lt pts i ) float x radius Mathf.Cos(ang Mathf.Deg2Rad) float y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLine.positionCount i 1 arcLine.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts How can I change the angle ang to create a reflected arc along the line P1P2 as in the image below? Please note that totalAngle represents the portion of the circle that is to be drawn between 0 and 360.


How do I handle parallel lines when looking for intersections? I'm using the following method to determine the intersection point of two vector2 public static Vector2 LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2) Get A,B,C of first line points startPoint1 to endPoint1 float A1 endPoint1.y startPoint1.y float B1 startPoint1.x endPoint1.x float C1 A1 startPoint1.x B1 startPoint1.y Get A,B,C of second line points startPoint2 to endPoint2 float A2 endPoint2.y startPoint2.y float B2 startPoint2.x endPoint2.x float C2 A2 startPoint2.x B2 startPoint2.y Check if the lines are parallel float delta A1 B2 A2 B1 if (delta 0) throw new System.Exception("Lines are parallel") Return the intersection point return new Vector2( (B2 C1 B1 C2) delta, (A1 C2 A2 C1) delta ) Currently the method throws an exception for parallel lines but I don't like the idea to wrap every call of that function in a try catch. Is there a better solution for this? I can't return null because Vector2 is a struct. Maybe somthing like the following? public static bool LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2, out Vector2 intersectionPoint)


I want a variable field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid? I want a field I declared (float attackRange) to be only declared when inheriting class set "bool haveLongRangeAttack" is set to true. I wanted to use Compiler Directives for this purpose. Here is the code I wrote using UnityEngine public abstract class Enemy lt T gt MonoBehaviour where T Enemy lt T gt SerializeField protected bool haveCloseRangeAttack false, haveLongRangeAttack false if haveLongRangeAttack true SerializeField protected float attackRange 1f endif SerializeField protected GameObject mainCharacter null protected GameObject enemy null protected virtual void ChasePlayer() if(haveCloseRangeAttack) ... else if(haveLongRangeAttack) ... I don't know if it is right way to of do what I want or using Compiler Directives so please review my code and tell me if there is a problem, or if there is a better way. It was before 6 months when I started writing code, and C was my first language. I am trying to learn new things concepts and writing at my own style. So there will be another way (maybe more efficient) if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me... TY for taking time . ! PS There is no compiler directives tag in Tags section. Maybe it will be useful to add this tag.


Maya Single Model with different animation I am newbie in Maya and would like to clarify some implementations in Animation. I know how to create simple animations in Maya. These animations are exported to Unity3D (as .fbx with controllers) to use in my application. I want to know whether it's possible to attach different animations to one model. For example, let's say, I have an arrow mark model and I want to show different animations for the model like moving left, moving right, moving up, moving down, etc. So that, when I export, I'll get one model Arrow.fbx and different controllers LeftAnimController, RightAnimController, etc. Is that achievable? Or I need to create different Arrow mark model with it's own controllers. Any help will be appreciated. Thank you.


Unity Unable to blend 2D Light renderers I've followed the documentation on Unity regarding 2D lighting. It said to turn on Alpha blending in the options. But this is how it turns out If Alpha blending is off If Alpha blending is on I'm not entirely sure why it's turning black. These are my settings for the 2D light I've checked my layers, specifically the tile map floor, and it's on the Default layer. I just want my lights to blend well.


Unity Modify basic dissolve shader graph to dissolve from bottom up I have this dissolve shader made in shader graph which works fine, however I would like it to dissolve from bottom up, how would this be done?


pivot of a 3d model outside its mesh after importing into Unity3d as you can see, the pivot is outside my mesh. I want to use the pivot for rotating around, for that I need to set the pivot to the real quot rotating point quot . I know that there's the SetPivot script, but it only works with pivots inside meshes. This mesh is part of an object which contains several meshes, I created it with Wings3d. The problem appears with .obj and .3ds as file extension. 1.How can I fix this? 2.Is there a possibility to define a second pivot which can be used in scripts to quot rotate around quot (maybe a vector3 which can be set in quot Designer quot )?


Enabling Unity GUI drawtexture permanently? I'm trying to get an image to show in Unity based on a certain criteria. I would like the position of the image to be randomized every time on play. However since GUI.DrawTexture shows the image for a single frame only, I end up with the image flashing across the screen in random areas. I would the first location to be randomized and the image to remain still there. Any advice on how to perform this will be greatly appreciated. Code void OnGUI() if(HP gt 0.9f) GUI.DrawTexture(new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300) aTexture)


C in Unity with dependencies I am currently creating a c program to eventually use in Unity. This c program contains references to libraries like OpenCV and dlib, referenced with a include statement which calls in other files, which are installed on my machine. My question is How do you compile your c project so that it runs in Unity completely self contained? i.e no reference to external files are needed, and all that are references are included within the program. Is there a specific tool to use, or a useful tutorial on the net? Thanks for the help.


How to set emission level through C I am willing to change emission level through code without affecting its color. (i.e., changing the brightness number shown in the box at the right side of the inspector, while keeping the emission color unchanged) I have tried this so far, but I don't know how to use my value variable to update the material public class EmissionColourChange MonoBehaviour Material thisMat Color c public float value void Start () thisMat GetComponent lt Renderer gt ().material c GetComponent lt Renderer gt ().material.color thisMat.EnableKeyword( quot EMISSION quot ) value c.r void Update () thisMat.SetColor( quot EmissionColor quot , new Color(c.r,c.g,c.b))


Unity sprite rig affecting performance I created a simple sprite rig using the skinning editor provided by the new 2D Animation V2 package. But it causes a huge FPS drop when added to the scene. Methods such as SpriteSkin.LateUpdate generates significant amount of garbage as shown in the picture See the spike shown on the CPU profiler when the rig is being enabled The rig is not even animated. I also checked the other sample rigs provided by Unity and they also performed in a similar fashion. Is this normal? I'm targeting mobile, so anything that can be done to avoid or improve the situation will be helpful. I'm using 2d animation v2 2.0.0 preview.2 in Unity 2018.3.8f


Get the length of an animation from the Animator How do find the length of an animation that is included in the Animator attached to a GameObject?


Why the MoveTowards make the transform moving nonstop? In the Update in the else part, I'm trying to move the transform up from its current position on the exit more up by offset. When the flag bool exit is true I want the transform to move up more by the offset for example if the offset is 7 then move up on the Y more 7. but it's moving up non stop. I tried to like this with exitPosition variable for storing at exit but still, it's moving up non stop. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Testing MonoBehaviour public float speed public float offset private bool exited false private Vector3 exitPosition private void Start() Debug.Log( quot Position quot transform.position) private void OnTriggerExit(Collider other) if (other.name quot Cube quot ) Debug.Log( quot Exited ! quot ) exitPosition new Vector3(transform.position.x, transform.position.y offset, transform.position.z) exited true private void Update() if (!exited) transform.position Vector3.up speed Time.deltaTime else transform.position Vector3.MoveTowards(transform.position, exitPosition, speed Time.deltaTime)


Unity3d AudioSource is not playing if gameObject is removed after play was started I am not able to play my audio source if I deactivate the panel where the AudioSource is attached to AFTER it. audioBtnEnter tmpBtnGeneral.GetComponent lt AudioSource gt () audioBtnEnter.Play() tmpBtnGeneral.SetActive(false) I would totaly understand if this would not be possible tmpBtnGeneral.SetActive(false) audioBtnEnter.Play() But why does the first code not trigger the audio play? Is this a race condition problem?


How can I create a copy of an object in Unity? I'm new to unity. How can I make some copies of my GameObject in Unity by scripting? I have tried this by the way public GameObject stone 3 void Start () for (int i 0 i lt 10 i ) Instantiate(stone 3, new Vector3(i 2.0f, 0, 0), Quaternion.identity) I can't really understand why it's not working.


Unity3D, How do I press one key and then cant press another key while the one is pressed? I am making a horror game, and I want to press a key to look up while I am idle, that i've done but if I press the W key it stands in idle but floating forward. How can I disable the W key while I press the F key to look up ? Everything works fine I can press F and the LookUp Animation is being played and if KeyUp on F the Animation goes back to Idle. My problem is if I am in LookUp Animation when I press F, I can also press W to go forward but its floating not walking. I want to deactivate this function so I can just press F when I am Idle. Thanks for help. my Script public float speed 10f public Rigidbody rgb public Animator anim bool walk false Use this for initialization void Start () rgb.GetComponent lt Rigidbody gt () anim GetComponent lt Animator gt () Update is called once per frame void Update () float move Input.GetAxis ("Vertical") anim.SetFloat ("Speed", move) if (Input.GetKey (KeyCode.W) walk true) rgb.transform.position new Vector3(0, 0, 1) speed Time.deltaTime Debug.Log("Walking") else walk false Debug.Log("Idle") if (Input.GetKey (KeyCode.F)) anim.SetBool("LookUpIdle", true) rgb.transform.position transform.position else anim.SetBool("LookUpIdle", false)


Is it possible to have a point light cast shadows but no reflection? I'm working in Unity 5.3.6. I have a point light that is simulating sunlight from a window. It looks great, except the floor reflects a bright white circle. I want the floor to reflect other lights in the room, just not this one. Is this possible?


How to make Rigidbody.AddForce less delayed in Unity3D? I'm trying to make it so that when the player in my game moves left or right, he lightly jumps from his current position to his new position. The way I have it set up now, the jump occurs once he has arrived at his new position. What can I do to make it so that the jump happens sooner so that it appears that he jumps to his new position? Here is the code I have that controls that part of his movement if (Input.GetKeyDown(KeyCode.LeftArrow) amp amp transform.position.x gt minXPos) targetPos new Vector3(transform.position.x xIncrement, transform.position.y, transform.position.z) rb.AddForce(Vector3.up jumpForceTwo, ForceMode.Impulse) transform.position Vector3.MoveTowards(targetPos, transform.position, speed) isHorizontalingLeft true else if (Input.GetKeyDown(KeyCode.RightArrow) amp amp transform.position.x lt maxXPos) targetPos new Vector3(transform.position.x xIncrement, transform.position.y, transform.position.z) rb.AddForce(Vector3.up jumpForceTwo, ForceMode.Impulse) transform.position Vector3.MoveTowards(targetPos, transform.position, speed) isHorizontalingRight true Here is a video showing what is happening (sorry it's blurry) https youtu.be rPewtb8QywE


How to randomly generate biome with perlin noise? I want to generate a procedural world using perlin noise. As expected, my terrain is generating with a repetitive patern. I'd like to add biomes, zones separated with higher or lower amplitude to simulate mountains or plain. I first thought I could randomly select rectangles of verticesof random sizes and then give them bigger amplitude to simulate mountains. The problem with that is that It wont seem natural, since I will only have rectangle biomes and also I don't know how to make it so the mountains would connect with the plain to avoid things like this Here is my script public int size 10 public float amplitude public float frequence void GenerateTerrain(float amp, float freq) Mesh meshy MeshRenderer meshRenderer GetComponent lt MeshRenderer gt () meshRenderer.sharedMaterial new Material(Shader.Find( quot Standard quot )) MeshFilter meshFilter gameObject.GetComponent lt MeshFilter gt () List lt Vector2 gt uv new List lt Vector2 gt () Vector3 vert new Vector3 size size List lt int gt tri new List lt int gt () List lt Vector3 gt norm new List lt Vector3 gt () meshy new Mesh() for (int i 0, x 0 x lt size x ) for(int z 0 z lt size z ) float y Mathf.PerlinNoise(x amp, z amp) freq vert i new Vector3(x, y, z) i for (int i 0 i lt vert.Length i ) norm.Add( Vector3.forward) for (int x 0 x lt size 1 x ) for (int z 0 z lt size 1 z ) int i size x z tri.Add(i) tri.Add(i 1) tri.Add(i size) tri.Add(i size 1) tri.Add(i size) tri.Add(i 1) for (int i 0 i lt vert.Length i ) uv.Add(new Vector2(vert i .x, vert i .z)) meshy.vertices vert meshy.triangles tri.ToArray() meshy.uv uv.ToArray() meshy.normals norm.ToArray() meshFilter.mesh meshy void Update() if (Input.GetKeyDown( quot u quot )) GenerateTerrain(frequence, amplitude)


Prevent Animation Tab from changing the position of an object I am quite new to Unity. I am using the latest version. When I try to make a door open animation, it goes well with rotation. But when I add the position property it takes it to the Vector3(40,12.5,7.5) instead of (10,2.5,15) at the first frame. I try to change the value but it reverts after I write.


Custom build failure callback I've been working on some custom build scripts, which will manipulate the references of certain MonoBehaviours. I'm using IPreprocessBuildWithReport to do the manipulation, and I want to reset the references when the build completes. Even if the build fails, I want to do the operation, but I want to do some additional stuff if it fails. I'm also using IPostprocessBuildWithReport and IProcessSceneWithReport as well. I've tried putting a Debug.Log in OnProcessScene and OnPostProcessBuild. I'm building without JAVA path defined, for Android, or without the Keystore password, which fails the build. The IPreprocessBuildWithReport correctly prints the Debug, but the others don't. Is there any class or interface which has a callback for Build Failure which I can use? I've tried to get the summary from the BuildReport in OnPreprocessBuild, but the result is always returning Unknown. Edit I would also like to make the same changes if the Build was cancelled, rather than just if it was failing. Platforms Windows, Android Unity 2019.3.7f1


In Unity , How to clear instantiated object when I call the function? Here is a function I call out am UI element public void LoadCurrentItem(ItemType t) List lt Item gt itemList SessionManager.singleton.GetItemAsList(t) if (itemList null) return if (itemList.Count 0) return GameObject prefab (t ItemType.consumable) ? eq left.inventory.slotTemplateUD eq left.inventory.slotTemplateLR Transform p eq left.inventory.slotGrid int dif iconSlotCreated.Count itemList.Count int extra (dif gt 0)?dif 0 for (int i 0 i lt itemList.Count extra i ) if (i gt itemList.Count 1) iconSlotCreated i .gameObject.SetActive(false) continue IconBase icon null if(iconSlotCreated.Count 1 lt i) GameObject g Instantiate(prefab) as GameObject g.SetActive(true) g.transform.SetParent(p) icon g.GetComponent lt IconBase gt () iconSlotCreated.Add(icon) else icon iconSlotCreated i icon.gameObject.SetActive(true) icon.icon.enabled true icon.icon.sprite itemList i .icon icon.id itemList i .item id It might seem less informative, but my question is simple and stupid I want to destroy my GameObject g that instantiates prefab before it instantiates prefab so that I can refresh GameObject g to create eq left.inventory.slotTemplateUD or eq left.inventory.slotTemplateLR How can I achieve this goal?


How to simulate an elastic force, using Hinge Joint ? I've a bucket connected to a rope. I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope. How can i do that ? Thanks


How can i add a description of gameobject when click on the gameobject? I have this DetectInteractable working script attached to Player (FPSController). I'm using tag to detect interactable objects, each object i want to be interactable i change his tag in the editor to "Interactable". ( Maybe there is a better way to do it without using tag ? It's working but many told me not to use tag. ) I'm using Raycast to hit a gameobject detect if it's "Interactable" and if it does i display on the gameobject his name. For example "Security Door" or "Screen Monitor" or "Surveillance Camera" Now i want to do that if i hit a gameobject with the raycast and it's "Interactable" if i will click the mouse left button it will display a description text description about the gameobject. But this time i want to use some gui box so it will be in front of the screen in the middle and not on the gameobject. The problem is that i need to create a script for every "Interactable" gameobject and make that if i click on a button it will display a description. Then how do i make the script and how can i make that when i attach the script to each gameobject it will make in the inspector a box of text so i can enter and type there the description of the item(GameObject) ? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public Canvas canvas public Text interactableText private RaycastHit whatObjectHit private RotateObject rotateobj private void Start() rotateobj GetComponent lt RotateObject gt () private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (rotateobj.rotating false) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true interactableText.gameObject.SetActive(true) interactableText.text whatObjectHit.collider.gameObject.name print("Hit ! " whatObjectHit.collider.gameObject.name) else image.color Color.white interactableText.gameObject.SetActive(false) print("Not Hit !") else image.color Color.white public class ViewableObject MonoBehaviour public string displayText public bool isInteractable


Save Script Doesn't Save Item Variables I've been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player's itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don't receive any errors or warnings in the Console. Here is my script to the Saving System using System.Collections using System.Collections.Generic using UnityEngine using System using System.Runtime.Serialization.Formatters.Binary using System.IO public class InventorySave MonoBehaviour Public variables for inventory and health private GameObject itemHolder private ItemInformation myItemAmount Initiates before the first frame void Start() Gets components for the player variables itemHolder transform.gameObject myItemAmount itemHolder.GetComponent lt ItemInformation gt () Function that will be called when player saves game from pause menu public void SaveGame() Creates file to store variables BinaryFormatter bf new BinaryFormatter() FileStream file File.Create(Application.persistentDataPath quot SaveData.dat quot ) SaveData data new SaveData() Gets the player data data.itemSave myItemAmount.itemAmount Writes player data to file and encrypts it bf.Serialize(file, data) file.Close() Holds data that is to be saved Serializable class SaveData Variables for save file public int itemSave


How can I develop and publish a game when I don't have the money to buy a brand new computer? I'd like to complete and publish a game made with Unity, but given the fact that the cost of a brand new computer represents a significant part of my yearly income, I don't have enough money to buy one. My ultimate goal is to publish the game on iOS. Aside from generating more revenue upfront, what are my options? Notes from the moderators We've made this question canonical, so we're looking for non specific options (e.g. please avoid targeting specific regions, or suggesting to buy specific models, etc.) we'd like to help future visitors coming from all over the world, for the years to come.


combining multiple materials into one material (Unity) I am confused with how should I texture my character. I am using blender for modelling. And while my model is too complex I dont want to use uv map techniuqe. I can get what I need with using seperate materials. Therefore I assign different materials to different meshes in Blender then import it to Unity. Therefore I have lots of different material in one model and I think it increases draw call. What can I do to combine these material into just one. I thought baking would be sollution but while my character is dynamic I can not get a good result.


How move camera where i look? I am try make simple flying camera. Without character. But than I press forward camera moving to another direction. void Update() horizontalInput Input.GetAxisRaw("Horizontal") verticalInput Input.GetAxisRaw("Vertical") var mouseX Input.GetAxis("Mouse X") var mouseY Input.GetAxis("Mouse Y") var trm Camera.main.transform if (horizontalInput ! 0 verticalInput ! 0) trm.position moveSpeed new Vector3(horizontalInput, 0, verticalInput) var rotateValue new Vector3(mouseY 2, mouseX 2, 0) trm.eulerAngles rotateValue trm.rotation Quaternion.Euler(rotateValue) Than I press 'W' camera moving to left... I understand that it is necessary to coordinate the motion vectors and camera rotation. How best to do it?


Reusing tilemap segments I'm wondering how I can incorporate reusable tilemap segments in my workflow. For example I construct a room out of my tile palette, and I want to reuse this room in multiple places. Is there some way to "prefab" a section of a tilemap? I haven't found such a thing. Or perhaps I should just prefab the whole tilemap, and use multiple tilemap objects within one grid? Won't that introduce significant overhead? What if I want to prefab a section of a tilemap with some additional, non tilemap objects?


Unity Game objects in scene load incrementally and not at the same time I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images. In order to load this data in the scene, I make a lot of UnityPlayer.UnitySendMessage(GameObject,Function,Params) calls to many C scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc. Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly. How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?


Creating a game with in game programmable AI I am looking to make a game where the player can access an in game terminal and then use this terminal to write AI logic in a programming language such as C or C , then they can compile the code and apply the AI to NPC characters. Of course if the code failed to compile error free then it would not be applied to the NPC. Mostly the code would be function calls with a few basic constructs available like int, float, bool etc. My question is how could I achieve this in say Unity or another game engine. Would I need to use a scripting language such as LUA or Python to create the AI or could I be done in real time on a separate thread in Unity somehow?


Material is flickering in Unity I'm trying to make a grid like, light up floor using Unity's Shader Graph. However, I am having an issue where the lines are flicking after a really short distance when the camera is moving. The shader graph is below. How can this issue be prevented and what is causing it?


In the new InputSystem of Unity, how to detect the keyboard and the mouse "as the same input device"? I'm trying to use the PlayerInputManager of the new InputSystem (preview 7) and my keyboard and mouse are being detected as separate devices. I'm not saying that it is wrong, but it is not useful at all and I would like to know how to fix it. As shown in this video, the PlayerInputManager has the ability of Instantiating new players when they press a button of their controller. This is almost exactly what I need, but it is not perfect. All works fine using controllers but if someone wants to join using the keyboard mouse, "they won't be able". When a key is pressed in the keyboard, a player joins, and when the mouse is used, another player joins (despite the fact that in that game youn need both to control a character and neither one of the spawned characters would be playable). So my question is how can I configure the InputSystem so that only one player joins when either a keyboard or mouse is used and it reads the input from both devices? Maybe it is simply a missing feature, but I think that it would be nice if you could achieve what I want because a lot of times the keyboard is used alongside a mouse. Thanks in advance!


Unity Pixel Perfect Camera Adjusting the Viewport Rect? I am trying to make a pixel perfect Tetris style game. I have the pixel perfect component attached and have tried playing with settings such as Crop Frame and Stretch Fill. It seems to override any setting made to the 'Viewport Rect'. The problem here is I want to control where the play area is shown on the screen. For example I want the single player game to be somewhere near centre (although preferrably slightly off to the left). But when they play 2 Player mode I want the P1 playarea to be near left, and P2 area at the right. The screens below shows some of the settings I tried. The 3rd screen shot shows the play area approaching what I want, but I am unable to move it left to right for example (Im unable to move it at all). (Also note, if I try leaving CropFrame and StretchFill unchecked my Camera Size value is also overridden). I even tried to 'extend' the Pixel Perfect Camera class but haven't been able to do that, I'm starting to wonder if this is just a limitation of using this component and perhaps I would need to write my own implementation of the pixel perfect camera to achieve the full control I need. UPDATE Actually I am able to extend the Pixel Perfect Camera class by 'using UnityEngine.U2D'. So far this is what I am trying whilst I wait in hope of further help (It seems like a lost cause extending the class, because I am not sure I can override much from it and cannot see the code. I can't find a way to set the Viewport X or similar). All the best everyone! Thanks for any help.


Unity is losing track of changes to Resources I have a Unity project, where I recently changed the names of a few files in my Resources folder. This is relevant because I have code that looks like this internal void LoadItems(string names) var items Resources.LoadAll lt TileBase gt ("Tiles Items") var itemMap items.ToDictionary(m gt m.name.ToUpperInvariant()) items.Clear() items.AddRange(names.Select(n gt itemMap n.ToUpperInvariant() )) The AddRange call is currently throwing an exception, because the incoming data is expecting the new names to be present, but itemMap for some reason still contains the old names. I've verified this in the debugger, and I've verified in Unity's file search that no file matching the old version of the name that's causing trouble here exists anywhere in the project anymore. And yet, when I run the project, (using the Attach To Unity And Run option from Visual Studio,) the old names still show up. If I go into Build Settings and tell it to rebuild the project, this code works correctly... once. Subsequent runs cause it to fail, going back to the old names again, so it kind of feels like Unity is actively trolling me at this point. The old data has to be cached somewhere, but I'm not sure where or how to fix it. Anyone know how I can resolve this?


Cost of Unity Local Multiplayer VS Unity Online Multiplayer I know that making multiplayer games in Unity costs money because of the servers that are used in connecting the players. So basically its free upto 20 CCU and then it increases as per the CCU. Its true for the online multiplayer games. But for local multiplayer games(LAN), should it cost the money for using it? Because we converted one of the devices in the local as the server and we don't need their servers. So am I thinking right ?? Or I am going wrong somewhere? Just wanted to be clear about how to make a local multiplayer and not an online multiplayer. Also wanted to ask if Photon supports local multiplayer? Basically I am confused about how to make offline local multiplayer game.


SceneManager.GetActiveScene() return 1 when Debugging active scene in editor I'm trying to use the new SceneManagement since Application.LoadLevel is obscelete and I've read that we need to put it like this. using UnityEngine using System.Collections using UnityEngine.SceneManagement public class UI MonoBehaviour private Scene activeScene SceneManager.GetActiveScene() Use this for initialization void Start () Debug.Log (activeScene.name) Update is called once per frame void Update () public void restartLevel() SceneManager.LoadScene (activeScene.buildIndex) The Debug.Log show " 1" and it should be "0" and throw this error in console Scene '' ( 1) couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded. The Scene is added in the build setting too by the way. Seems that it can't return me the good index and even with the activeScene.name, still returns NULL. I miss how Application.LoadLevel was easier and more robust that this new way...


Glow shader limited by the texture area I'm working on a glow shader (for 2D engine Futile relying on Unity). It works OK but the effect is limited by the texture area. Except from adding a lot of empty pixels around the textures (which would result in un optimized too big texture atlases), is there a better solution to cope with this problem? I'm quite new with shaders so maybe this is a classic problem with some well known solutions, maybe I'm not searching with the right keywords.


Unity UI, how to hide on play I have created a menu on Unity using the built in UI components,I can't create this on a seperate scene because I used the toggle button, which basically when you click it, it spawns a specific object (I have 4 of these toggle buttons). I have completed making the menu on the my current scene. My problem is that when I start on runtime, the menu appears in front of the first person character controller, and when I move the mouse to click the toggle, the camera controller follows the mouse movement. How do I fix this? Also when I click all of the toggle buttons, I want the UI to dissapear, so it isn't shown when I am playing the game because atm when I click the toggle buttons, the actual buttons stay on the screen whilst I am navigating around the scene, is there any way to make this invisible?


Directional light causes an FPS drop I have only one object in the scene and it is lit with a directional light. It uses the mobile diffuse shader. The issue is that on iPhone 4 the FPS drops from 42FPS to 11FPS when the directional light is enabled. Rendering is set to forward rendering and there are no other light sources. Shadows are not enabled. Scene stats give a total of five draw calls, 3k tris and 2.6k verts. Having a single directional light should not have that kind of effect on FPS. What could cause this FPS drop?


How can I randomly generate objects inside of a Complex Area? In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool.


Hide move the Particle Effect panel on the Scene view window The problem for example is if I want to drag the particle system object to the bottom right corner of my view, then it goes behind the Particle Effect panel. Is there any way to do hide or move this panel in editor mode and or in runtime mode?


camera.render reads a file in the middle of a gameplay Why does camera.render read a file in the middle of a gameplay? This causes a lag in my game


How do I make a game object appear on the other side when it leaves the screen? I'm doing an assignment for a course and what's required is to include a moving asteroid in the game that starts moving in a random direction and when the asteroid leaves the bottom of the game window it should re appear at the top of the game window ,so I wrote the script for warping and I applied it to the asteroid and a ship in my game ,then built it to WebGl game. the warping worked fine in the editor for both the ship and the asteroid, while it only worked for the ship in the built game, and I can't figure out what's wrong this is the script (ScreenUtils gives the borders of the screen) float Radius void Start () Radius GetComponent lt CircleCollider2D gt ().radius void OnBecameInvisible() Make the ship wrap Vector3 position transform.position if (position.x Radius gt ScreenUtils.ScreenRight position.x Radius lt ScreenUtils.ScreenLeft) position.x 1 if (position.y Radius gt ScreenUtils.ScreenTop position.y Radius lt ScreenUtils.ScreenBottom) position.y 1 transform.position position


How to implement 3d maneuver gear physics in unity? I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here. How do I go about implementing 3d maneuver gear physics from attack on titan anime? What is it? In case you don't know, here's a brief link about 3d maneuver gear. A brief commentary about 3dMG It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about. My Approach so far I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific. The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry. So any general idea would be greatly appreciated.


Should I package and sell my game on the unity3d asset store? I'm trying to figure out if I should refurbish and refactor a game I and some friends have made. It's released on kongregate and wasn't a super hit but I feel there's a lot of interesting techniques and solutions going on that new or intermediate developers would like to see. The only thing that's holding me back is that I don't know if people are interested in it at all. Would you be interested in buying the source code and assets for this game? Check it out and you'll see that there's a lot of things happening in the game. If we packaged it and sold it, we would of course tidy it up a bit which would involve more work so I would really appreciate your honest opinion. We've looked around and haven't found actual released games in the unity3d asset store. Maybe we just didn't look enough though. We're thinking of setting a price tag of between 150 and 200 . What's your opinion on this price? And in general, what's your opinion on selling assets and source code? Should I be wary of any legal implications (like my customer licensing my stuff and then forbidding me from selling it)? I posted this over at UnityAnswers as well but I know I rather go here for gamedev questions so I'm hoping other unity devs will drop by here too. Edit Reconsidering after getting some great advice we'll probably rip out the assets only and market those as space stuff or something. We'll then market the assets with the help of some free classes of code showing off some of the examples that were hard for us to do when we were (more) beginners. The unify wiki might benefit from having some of the code that we've done and that isn't all that hard but a bit tedious. If we actually "finish" the game (it is indeed an asteroids spinoff and was never intended to be anything else, apart from some sandbox modes we've been experimenting with) we'll probably sell it with a decent price tag for an indie game like this.


How can I use websockets in a Unity WebGL project? There are plenty of good Websocket APIs for C , but I run into trouble when targeting Unity WebGL due to this restriction described in the Unity documentation No direct socket access Due to security implications, JavaScript code does not have direct access to IP Sockets to implement network connectivity. As a result, the .NET networking classes (ie, everything in the System.Net namespace, particularly System.Net.Sockets) are non functional in WebGL. The same applies to Unity s old UnityEngine.Network classes, which are not available when building for WebGL. If you need to use Networking in WebGL, you currently have the options to use the WWW or UnityWebRequest classes in Unity or the new Unity Networking features which support WebGL, or to implement your own networking using WebSockets or WebRTC in JavaScript. How can I work around this restriction for networking in my Unity WebGL game?


Fragment shader coordinates Displacing pixels and texCoord problems I'm trying to create a shader that creates a displacement on an object, slicing horizontally the sprite. These is an example of the atlas I'm using and the effect I'm trying to achieve I tried to achieve this creating a fragment shader, that would read the Y coordinate of the texcoord, and depending on the height, displace it horizontally. But I found two main problems 1) If my atlas had more rows of sprites, I can't really tell at what height I'm drawing the sprite in the fragment shader. Since values of texcoord go from 0 to 1 relative to the atlas being use, the more rows I have, the smaller values should I choose to create the horizontal cut. Is there any way to know the position inside the drawn? 2) The problem is similar to the previous point. When displacing the pixels horizontally, if the displacement is too big, I end up sampling the sprite next to the one being rendered. The idea is for it to loop back the the begining of the sprite. If I had the width of the sprite, I could tell how to do so, but using texcoord alone is just not posible. How can I do this?


How to search for a visible player? I've an enemy static tank with a "rotable" cannon turret. I would like to rotate it in the player's direction . How to implement it ? I've thought something like void Update SearchForPlayer() RotateTurret() I don't know how to implement a sort of radar function. Thanks


Unity2D Don't Destroy On Load UI button I have a UI button as a child under my background canvas. What I want to do is to save the button through out scene, I tried using DontDestroy OnLoad but It saved ay canvas and everything under my canvas, rather than saving just the button. Anyway this is my DontDestroyOnLoad script void Awake() DontDestroyOnLoad(transform.root.gameObject) Thank you. )


Layers in Unity won't drag I'm trying to rearrange my layers in Unity but I can't seem to drag them. When I try to do this I'm in edit layers under the heading sorting layers and I click on the symbol and try to drag it but it won't move. I also tried restarting Unity twice but it won't resolve the problem. Could someone help me with this?


Unity IVRRenderModels 006 SteamVR Error I get this Error in Unity when I imported SteamVR "Failed to Load IVRRenderModels Interface Version IVRRenderModels 006" I looked after on it but nothing really solved the problem. Why is this happening and what could be the solution?


How do you use SoundManager for multiple player games over the network? I have created a basic sound manager according to this unity tutorial (https unity3d.com learn tutorials projects 2d roguelike audio). However, I need it to work for multiple players over the network, and it doesn't make sense for them all to be playing the same sounds. E.g. If a player loses, it should play the gameover sound, but the other player(s) should remain in the game and continue playing the game sound. But the current behavior is that once a player loses, everyone gets the gameover sound. By the tutorial, I currently use a single instance within the SoundManager class. I think I need multiple SoundManager instances, each associated with a client. What's the best thing to attach the SoundManagers too? Or is there a different best practice for managing sounds for multi player games? Here's the code for my sound manager using UnityEngine using System.Collections public class SoundManager MonoBehaviour public static SoundManager instance null public AudioSource effects public AudioSource music void Awake () if (instance null) instance this else if (instance ! this) Destroy (gameObject) DontDestroyOnLoad (gameObject) public void playSoundEffect(AudioClip clip) effects.PlayOneShot (clip, 1f) public void setBackgroundMusic(AudioClip clip) music.clip clip music.Play ()


Raycasting from 3D object to UI canvas! I have a world space canvas in front of the player and I want to shoot a ray towards an enemy (in the direction of the enemy) and create and object where Raycast hits the UI canvas. I know that the physics engine doesn't interact with UI elements and event system is not the answer for me since it depends on pointer events and their position. So how can I do this? If possible, I would like to draw the ray or the line as gizmo to see if it's working. My Current Code is this void OnDrawGizmos() foreach (AeroplaneAiControl item in GameObject.FindObjectsOfType lt AeroplaneAiControl gt ()) Gizmos.color Color.magenta Gizmos.DrawLine(transform.position, item.transform.position) Vector3 Direction transform.position item.transform.position RaycastHit rch Ray r new Ray(transform.position, Direction) Physics.Raycast(r, out rch) if (rch.collider ! null) Gizmos.color Color.cyan Gizmos.DrawLine(transform.position, rch.point) Gizmos.DrawSphere(rch.point, 0.1f) it draws the magenta line but not the cyan line and no spheres.


Handling RPG (rocket launcher) launcher and rocket In my game, the player has an RPG (rocket launcher). Using this launcher, he can shoot a rocket. When shown in the inventory, the rocket is stuck in the launcher. Also, when the user walks, the rocket is stuck in the launcher, and the RPG (the combination of launcher and rocket) is placed on his back. Now when the user shoots, the rocket leaves the launcher, and the launcher pulls the player into a little spin to simulate a recoil. Since the rocket and the launcher are stuck together most of the time, I was thinking that I should have a main game object named "RPG" with the 2 meshes "launcher" and "rocket". Most of the time, they would be stuck together. When the user launches the rocket, I would change the position of the rocket in order to simulate it flying away. When it has exploded, I would make the rocket mesh invisible. I was really proud of that plan until I noticed that the recoil will move the rotation and position of the RPG (launcher). Imagine the recoil of a pistol The recoil will cause the pistol (and the hands) go up a bit. Now when I do this with the launcher, the rocket will change its flight path. That would look unrealistic. Can somebody tell me how this is commonly dealt with? Thank you!


How to orient hands(or spine) to always look at some target? I am building an FPS game in Unity 3D everything was going cool but when I tried to implement aiming for the rifle everything just broke. 1) I have an IK setup which triggers when you equip weapon, this IK only calculate the hand position and orientation needed to hold the gun and after that the IK system disables itself, basically I am using IK for getting the proper hand position on different guns. 2) Once hands are positioned correctly on the gun then I rotate the hands(or spine, which will rotate hands and head with it) with the mouse to look up, down, right and left. 3) Handgun is very easy to handle, equip it and rotate the arms, arms are almost straight along the z axis so I just rotate them on the y axis to aim upward and downwards. 4) With the rifle, I can calculate the hand position and rotation to hold the rifle easily but (because static animation pose of holding he rifle is little oriented to make the player little realistic) when I rotate arms they rotate weirdly. I checked in the editor by changing the y axis of the rotation and found that only y axis can't rotate the arm the way I want and to rotate it that way other axis must change their values. I searched a bit and found that it is a situation called as Gimbal Lock which is very common with euler rotations, I tried many things but still can't fix it. Original Code leftArm.transform.localEulerAngles new Vector3(leftArm.transform.localEulerAngles.x, leftArm.transform.localEulerAngles.y (currentCamRotX offset), leftArm.transform.localEulerAngles.z) rightArm.transform.localEulerAngles new Vector3(rightArmFPS.transform.localEulerAngles.x, rightArmFPS.transform.localEulerAngles.y (currentCamRotX offset), rightArmFPS.transform.localEulerAngles.z) It works great with Handgun but not with Rifle. I read about and tried following but in vain Method 1 Failed var target camera.GetChild(0).GetChild(0) var direction target.position rightArmFPS.position var toRotation Quaternion.FromToRotation(rightArmFPS.up, direction) rightArmFPS.rotation Quaternion.Lerp(rightArmFPS.rotation, toRotation, Time.deltaTime 5) Method 2 Failed var targetForward target.position spine.position targetForward.Normalize() var rotAxis Vector3.Cross(Vector3.forward, targetForward) var angle Mathf.Acos(Vector3.Dot(Vector3.forward, targetForward)) Mathf.Rad2Deg spine.eulerAngles rotAxis angle What I am looking for now is if someone can point me what topic I should be looking in(because my poor maths skills are really getting me and I often use very poor workarounds for what could be solved easily with maths or physics), pseudo code to get me started or anything that might help me resolving this issue. I know there are bunch of other ways to achieve what I am looking for and I have tried many of them like using IK to position hands and then moving the guns up or down or having animations for each gun aiming up or down but honestly each method has it's own drawback(or its just me who is too noob for these things). I followed this solution Orienting a model to face a target and many others, you might find it duplicate but none of the post on the internet has solved my problem(it is second day and I still can't figure this out). Hope you understood the question and thanks for reading this )


Is it possible to use true Blinn Phong lighting on Unity Android IOS? I've noticed that the Unity's Legacy Shaders Specular shader does not work on mobiles due to the lighting model being incompatible. I then tried using the Mobile Bumped Specular shader, but this shader does not support non directional lights. So I tweaked the mobile specular shader to remove the noforwardadd argument, but I noticed that specular highlights are improperly positioned for non directional lights, even after removing the halfasview interpolateview argument. Does Unity even support non directional specular highlights on mobile devices?


How to make a fade effect on the Unity's scrollView? I have a basic ScrollView, with some additional scripts so it snaps to the nearest element (focusing on it). When I perform the scroll, it looks like this What I need to achieve is to fade the part which is currently going off the screen. Like when I'm scrolling left, the right panel is coming in, and the left one fading out Is there any built in option for this? I'm opened for any ideas!


Hotkeys to toggle draw view in Unity Using Unity (2109.1.3f1) is there a way to switch the scene view's Shading Mode Draw Mode from Wireframe to Shaded? (eg. press 4 for Wireframe, 5 for Shaded) I've looked in the Shortcuts Editor, but "Wireframe" doesn't appear in any list of commands, and I don't see anything under the Scene Visibilty or Scene View Categories that look appropriate either. The docs only describe how to toggle this through the Scene view control bar, but it seems silly that it wouldn't be possible to map that operation to a key combination.


Changing CharacterController's height causes jittering issue in Unity As title said changing height of Character Controller causes jittering issue. For example when I reduced the height of CharacterController, it seems CharacterController was floating at each frame and it keeps falling to the ground. Opposite situation has same issue, different is collider is actually already passing the ground so it just push up the object by physics engine. (I saw some similar issue with Terrain, in this case it's worse, it just falling through the terrain) Anyway someone told that I have to change center of CharacterController too, with foot offset(I don't know what exactly that is), so I tried to change the center of CharacterController when resizing height but it still have same problem, nothing different. This is the code that I'm using void Update() if(Input.GetKeyDown(KeyCode.LeftControl)) isCrouched !isCrouched float newHeight isCrouched ? crouchingHeight originalHeight controller.height Mathf.Lerp(controller.height, newHeight, Time.deltaTime smooth) Vector3 newCenter isCrouched ? new Vector3(0, 0.2f, 0) Vector3.zero controller.center Vector3.Lerp(controller.center, newCenter, Time.deltaTime smooth) float newCamPos isCrouched ? origCamPos.y 0.2f origCamPos.y Vector3 newPos new Vector3(cam.localPosition.x, newCamPos, cam.localPosition.z) cam.localPosition Vector3.Lerp(cam.localPosition, newPos, Time.deltaTime smooth) Is there a way to rid off that jittering issue while changing height of Character Controller? Any advice will very appreciate it.


Unity AR Ground Plane Detector I need to check a "ground plane" to put objects over it without a marker, using Unity. Right now I'm using Vuforia, but the Ground Plane on Vuforia only works on some devices, I tested on mine and my mother's Android phone, both modern and from different brands, didn't work. So it's not an option, because many many people couldn't use it. Same with ARCore, asked me to install some sort of Google Services AR, which the download is locked for my phone. Is there any way to use Unity with some kind of ground plane detector that many phones can "read" it? Any API, code, anything different that I didn't try yet? Thanks!


Does it make sense to export and use skeletal animation as sprites? As tools like Dragonbones, Spine lets you export animations as both sprite atlas and skeleton data (JSON binary), I'm not sure which format to use when importing to Unity. I have few concerns Will there be any differences between the quality of the animations, when imported as atlas vs skeleton data? Any other pros and cons, using one over the other? If I use a sprite atlas, I don't have to depend on a third party runtime though. It is for mobile, so performance is also a concern.


Converting shader to ShaderGraph Is there a way to convert the below piece of shader code to shader graph? I am not sure how to find float2(i, i) in shader graph. fixed4 frag (v2f input) SV Target float2 res MainTex TexelSize.xy float i offset fixed4 col col.rgb tex2D( MainTex, input.uv ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb 5.0f return col


Ease Rotate RigidBody2D toward arbitrary angle I'm trying to make a rigidbody2D circle return to an orientation after a collision. But there is a weird behavior I do not expect it always orients to the same direction. This is what I call in FixedUpdate() rotationdifference halfPI rigidbody2D.rotation rigidbody2D.AddTorque (rotationdifference ease) I would expect this would rotate 90 degrees (1 2 Pi Radians) off of the neutral axis. But it does not. In fact it performs exactly the same as rotationdifference rigidbody2D.rotation rigidbody2D.AddTorque (rotationdifference ease) What is going on? How would I be able to set an angle I want it to ease towards, and then have it ease towards it when its not colliding with some other force? Edit For those who want to try this themselves, here is a MonoBehavior. Apply it to a sprite with a rigidbody2D. I have a boxcollider going througha field of pegs like in pachinko. using UnityEngine using System.Collections public class MarchingMovement MonoBehaviour public Vector2 speed new Vector2(50, 50) public float ease 0.01f private float rotationdifference private float halfPI 1.57079632679f Use this for initialization void Start () rotationdifference 3.0f Update is called once per frame void Update () void FixedUpdate() 5 Move the game object rigidbody2D.velocity speed rotationdifference halfPI rigidbody2D.rotation rigidbody2D.AddTorque (rotationdifference ease)


Getting the rightmost point of gameobject How do i determin the point on a gameobject that is most to the right (highest x value).


How to fold a view from 2 3D cameras in Unity? I need to combine view from 2 or more 3D static cameras. Let's say I have 3 humans standing in line side by side. The first camera is viewing the left person and the left half of the middle person. The second camera is viewing the person on the right and the right half of the middle person. Now I need to see the whole middle person. Any ideas how I can do this? I don't need to see code or some finished implementation, I just need some ideas, because I can not find anything on this.


How to get what button was clicked on? Other contexts in which this was done I'm sure have been answered for this kind of problem before. But this has thus far been a 2 week long impasse of wittling down all the other suggestions I've seen and not one has worked. I've got a prefab GUI with a singleton instance based script, which automatically disables itself at the start (I've tried commenting that out to see if that was it). The gui has a title text, body text, and 8 buttons. The script is meant to allow other scripts for interactive objects to safely access it and "start a conversation", using a coroutine. I created a script for the buttons that I attach to each, that when called should set a public bool to true, indicating it was clicked, this bool is polled among the buttons to see which button the user clicked. This is then return to the script which called the GUI, and the GUI closes or waits for the next piece of the conversation. I've set everything to be enabled, and removed anything that disabled the components. I've made sure that the buttons are higher in the hierarchy than everything else, to make sure nothing else was intercepting the clicks. I'm unable to get OnClick, OnMouseOver, OnMouseDown to be called. Debug messages never show. I've tried setting OnClick as part of the GUI where you select a function from the list, and inside of the button's code by adding a listener manually to the button. I've tried IPointerExitHandler, IPointerDownHandler, etc, also never seen anything come back from the methods. I've tried several other methods to date to get which button I clicked, such as ray casting when the mouse button is down and checking the name for the button's name, however it always passes through to the terrain. I've tried getting the button's rect and using Rect.contain with the mouse position to see if the mouse was over the button when clicked, but this never returns true. I'm really interested in seeing a working example where something like this has been done, so that perhaps if that doesn't work, I could at least start hunting down what might be causing a functioning example to fail, as I've no idea what's wrong at this point. Not to vent but this is very frustrating, and I feel it could be made so much simpler. Thank you all for any help you can give, you guys have been very wonderful with my short time here.


Why am I getting this "tag not defined" error? In the log, it says UnityException Tag car is not defined. at PlayerController.OnTriggerEnter (UnityEngine.Collider other) 0x00000 in lt filename unknown gt 0 I'm checking against the tag car when colliding, why does this happen? I have tagged the object, see picture below heres some code void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag("car")) error here more code


How to make a script's Gizmo toggleable in the Gizmos menu in Unity3D? I've implemented Gizmos for a few behaviours, and I'd like to make them toggleable in the Gizmos menu, just like the built in ones. Is this achievable?


How to iterate through the frames of an AnimationClip in editor mode I'm working on a 2D game, using spritesheets as the basis for four AnimationClips. (Every frame from the spritesheet is a keyframe in the animation.) I'm trying to step through the frames of these AnimationClips and programmatically create Collider2Ds which fit the dimensions of each frame. The problem is, I'm having an impossible time actually iterating through the frames. My character has an Animator component, with 4 different states. I've tried various inputs to my editor script, but the closest I've gotten has an AnimationClip as input private AnimationClip clip set in inspector private GameObject targetForColliders set in inspector void createColliders() Animation animation new Animation() AnimationUtility.SetAnimationClips(animation, new AnimationClip clip ) foreach (AnimationState state in animation) do useful things here Unfortunately, somehow the animation local variable is null, crazy as that sounds. I've confirmed that by both logging it and attempting to use it, which causes a NullReferenceException every time. I can't access the Sprite containing the spritesheet directly, because I've made manual adjustments within Unity to the keyframes (removing some, duplicating others) and I don't want to have to manually sync my colliders with the modified assets. Has anyone attempted to do something similar to this before? tl dr What's the easiest way to iterate through the frames of a 2D animation in an editor script?


Delete EdgeCollider issue In this program, When i draw a hill, a car can road on it's surface, and when I draw another one, the previous hill should remove. but unfortunately the previous edge collider looks still there. this is what i've done for delete this collider if(col) col.Reset() col null Destroy(col) unfortunately nothing works ) col.enabled false is also doesn't work this is the code i don't know what i have to do to disable the previous collision using UnityEngine using System.Collections using System.Collections.Generic public class LineFreeDraw MonoBehaviour private LineRenderer line private EdgeCollider2D col private bool isMousePressed private List lt Vector2 gt pointsList private Vector2 pointsArray private Vector3 mousePos Structure for line points struct myLine public Vector3 StartPoint public Vector3 EndPoint void Awake() Create line renderer component and set its property line new GameObject("Line").AddComponent lt LineRenderer gt () line.material new Material(Shader.Find("Particles Additive")) line.SetVertexCount(0) line.SetWidth(0.9f, 0.9f) line.SetColors(Color.green, Color.green) line.useWorldSpace true isMousePressed false pointsList new List lt Vector2 gt () void Update() If mouse button down, remove old line and set its color to green if (Input.GetMouseButtonDown(0)) if(col) col.Reset() col null Destroy(col) isMousePressed true line.SetVertexCount(0) pointsList.RemoveRange(0, pointsList.Count) line.SetColors(Color.green, Color.green) else if (Input.GetMouseButtonUp(0)) isMousePressed false Drawing line when mouse is moving(presses) if (isMousePressed) mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 if (!pointsList.Contains(mousePos)) pointsList.Add(new Vector2(mousePos.x, mousePos.y)) line.SetVertexCount(pointsList.Count) line.SetPosition(pointsList.Count 1, (Vector3)pointsList pointsList.Count 1 ) CarIsCollide() private void CarIsCollide() col new GameObject("Collider").AddComponent lt EdgeCollider2D gt () Collider is added as child object of line col.transform.parent line.transform if (pointsList.Count lt 2) return pointsArray new Vector2 pointsList pointsList.Count 2 , pointsList pointsList.Count 1 col.points pointsArray


Unlock levels using coins Unity I'm creating a game that has multiple levels. The first three levels are free but the others can be unlocked either using coins (collected during the game) or through IAP. For the coins, I'm using a binary formatter to store the number of coins. The reason I'm using BF is because it persits through all levels(so far this seems to work as the coin score is carried through to other levels). Here is code I have so far in the coinSystem public class CoinSystem MonoBehaviour public TextMeshProUGUI coinScoreText public int coinScore void Start() LoadScore() public void Save() coinScore coinScoreText.text coinScore.ToString() BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot TotalCoinScore.dat quot , FileMode.Create) CoinContainer coinContainer new CoinContainer() coinContainer.coinScore coinScore bf.Serialize(file, coinContainer) file.Close() public void LoadScore() if (File.Exists(Application.persistentDataPath quot TotalCoinScore.dat quot )) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot TotalCoinScore.dat quot , FileMode.Open) CoinContainer coinContainer (CoinContainer)bf.Deserialize(file) file.Close() coinScore coinContainer.coinScore coinScoreText.text coinScore.ToString() Serializable public class CoinContainer public int coinScore This is code that I use to add to the coinScore. public class Player MonoBehaviour Rigidbody rb public CoinSystem cs public bool dead true void Start() rb GetComponent lt Rigidbody gt () . . . . void OnTriggerEnter(Collider col) if (!dead amp amp col.gameObject.tag quot Enemy quot ) die() if (!dead amp amp col.gameObject.tag quot Coin quot ) cs.Save() So now in the level select menu, I want to add a button that once clicked should enable the user to unlock a particluar level if he has enough coins. For example, if a level requires 500 coins and the user has 600, then on clicking this button the level is unlocked and the total coins now available are 100. And if the number of coins are less than what is required to unlock a level then the user should not be able to unlock that level. I'm not sure how to implement this.


How to set ortho projection model view matrix without a camera? I'm trying to create the correct projection and model view matrix for rendering without a camera. orthoCamera is a camera I set up in the scene view. Using the orthoCamera projection matrix and modelView matrix works but I don't know exactly how to recreate these. My attempt is the commented code. not correct var projection Matrix4x4.Ortho( 512, 512, 512, 512, 0.3f, 1000) var modelView Matrix4x4.LookAt(new Vector3(512, 512, 5), new Vector3(512, 512, 0), Vector3.up) inverse? correct result var projection orthoCamera.projectionMatrix var modelView orthoCamera.worldToCameraMatrix GL.LoadProjectionMatrix(projection) GL.modelview (modelView) This is how I set the camera up in the scene.


How can I play an animation in response to an event? I've written a script to play an animation, but it starts immediately as my level loads. Instead, I want it only to start when triggered by some event or after a given timeout. How can I do this?


How to find asset by it's number? Don't know what this number means I need to find the asset that is displayed by this number inside my project. I guess this number means "GUID" but it's hard for me to understand what is it. Can you help me guys?


I accidently changed the cursor image in Unity In the Unity Editor I accidently changed the image for the mouse cursor in project settings player How can I restore it to the default, preferably not through programming?