How can I deactivate and activate a button? I have a code that keeps a gameObject between scenes, the theme is that this gameObjecte has as a child a button, which I can change the linerenderer color, besides changing the image of the button according to the selected color and thus keep the data between scenes. then when I change to the next scene I deactivate the button with the meteodo "dehabilitar()" and in the others it is not necessary, then when I change to the next scene I deactivate the button and it is not shown, but when I go back to the next scene and call the function " habilitar() "the button is not displayed. If someone can help me in what I have bad in the code or what I lack? PS I did different methods to activate and deactivate the button but the same thing always happens and I leave it like that for a while. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI namesp ace DigitalRubyShared public class CambioColor MonoBehaviour public Button mybutton public LineRenderer p1 public LineRenderer p2 public Sprite colorRojo Color Rojo new Color(1, 0, 0, 1) public Sprite colorAzul Color Azul new Color(0, 0, 1, 1) public static int counter 0 public static bool estado false public static CambioColor estadoCambioColor void Awake() if (estadoCambioColor null) estadoCambioColor this DontDestroyOnLoad(gameObject) else if (estadoCambioColor ! this) Destroy(gameObject) void Start() mybutton GetComponent lt Button gt () p1 GetComponent lt LineRenderer gt () p2 GetComponent lt LineRenderer gt () counter 2 public void changeColor() counter if (counter 1) mybutton.image.overrideSprite colorAzul mybutton.image.sprite colorAzul p1.startColor Azul p1.endColor Azul p2.startColor Azul p2.endColor Azul if (counter 2) mybutton.image.overrideSprite colorRojo mybutton.image.sprite colorRojo p1.startColor Rojo p1.endColor Rojo p2.startColor Rojo p2.endColor Rojo counter 0 public void dehabilitar() if (estado false) mybutton.enabled estado mybutton.gameObject.SetActive(estado) estado true public void habilitar() if(estado true) mybutton.enabled estado mybutton.gameObject.SetActive(estado) estado false Update is called once per frame void Update()


Instantiation of a custom class I have a custom class named Stars class Star public int primaryID public string properName public string HIPID public string HDID public string HRID public string GLID public string BFID public decimal rightAscension public decimal declination public string magnitude public string colourIndex public int scale public int red public int green public int blue public bool isSimulated public double x public double y public double z public void setDetails(int primaryID, string properName, string HIPID, string HDID, string HRID, string GLID, string BFID, decimal rightAscension, decimal declination, string magnitude, string colourIndex) this.primaryID primaryID this.properName properName this.HIPID HIPID this.HDID HDID this.HRID HRID this.GLID GLID this.BFID BFID this.rightAscension rightAscension this.declination declination this.magnitude magnitude this.colourIndex colourIndex decimal deg2rad 0.01745329251994329576923690768489m this.isSimulated true Decimal datatype is used to make sure that values are very accurate and precise decimal degrees ra decimal degrees dec decimal radians ra decimal radians dec degrees ra Decimal.Multiply(rightAscension, 15) degrees dec declination radians ra Decimal.Multiply(degrees ra, deg2rad) radians dec Decimal.Multiply(degrees dec, deg2rad) Converted from decimal to double because the Math library cannot work with decimals float distanceStars 19113 this.x (distanceStars Math.Cos(decimal.ToDouble(radians dec)) Math.Cos(decimal.ToDouble(radians ra))) this.y (distanceStars Math.Cos(decimal.ToDouble(radians dec)) Math.Sin(decimal.ToDouble(radians ra))) this.z (distanceStars Math.Sin(decimal.ToDouble(radians dec))) public Vector3 getVector() return new Vector3((float)z, (float)y, (float)x) There are many of these stars and I want to instantiate them at run time void plotStars() int i 0 while (i lt (StarDataBank.Instance.NumOfStars)) string name StarDataBank.Instance.StarName i string HIP StarDataBank.Instance.StarIDHIP i string HD StarDataBank.Instance.StarIDHD i string HR StarDataBank.Instance.StarIDHR i string GL StarDataBank.Instance.StarIDGL i string BF StarDataBank.Instance.StarIDBF i decimal RA Convert.ToDecimal(StarDataBank.Instance.StarRA i ) decimal Dec Convert.ToDecimal(StarDataBank.Instance.StarDec i ) string Mag StarDataBank.Instance.StarMag i string ColI StarDataBank.Instance.StarCI i var star new Star() star Instantiate(ObjectStar, transform.position star.getVector(), Quaternion.identity) star.transform.parent StarObject.transform star.transform.localScale new Vector3(star.scale, star.scale, star.scale) i But I am experiencing a lot of errors. Unity isn't instantiating the Stars because it can't convert UnityEngine.Transform to Star Star doesn't contain definition of Transform Is there a way to assign a class as a gameobject?


How can I use spectrum data to calculate energy values of certain frequency bands? I'm working on a rhythm game, and need to detect beats in a piece of music. After all the research and reading through old posts in unity forum reddit etc., as far as I understood, I need to calculate the average energy, and if there is a sudden energy change spike, I want to register them as beats. So here's the thing as far as I understood public class something MonoBehaviour public AudioSource audioSource public float freqData new float 1024 void Start () audioSource GetComponent lt AudioSource gt () void Update () audioSource.GetSpectrumData (freqData, 0, FFTWindow.BlackmanHarris) Let's say I have this code in place. My sampling rate is at 48000 Hz. The array size determines the frequency range of each element. So with a size of 1024, my frequency resolution is 23.4 Hz. So freqData 0 represents the freq between 0 23.4 Hz. freqData 1 represents 23.4 46.8 Hz. so on and so forth. And I want to detect, let's say bass beats between 60Hz and 250 Hz. How can I translate this data into the average energy value for this frequency band?


Quixel asset to unity I downloaded asset from Quixel, I'm using Unity HDRP, the problem I am facing is how to properly create a mask map cause the asset from Quixel doesn't have metalness map where in HDRP mask map it requires channel R should be metalness map, and the base map requires RGB color and I've got diffuse map from the asset, to put diffuse map to the basemap slot the right way to do? I'm fairly new to the channel, so put it simple 1.How to pack channels for mask map if no metalness map in the asset, what to do with the empty channel 2.Is it right to put diffuse map to basemap slot? 3.What to do with the detail map in the maskmap , the same as to no metalness map provided in the asset. 4.Another question is heightmap, Unity provide pixsel mode and vertex mode, what is the consideration before choose the displacement mode, When I choose pixsel mode, the whole texture seems to be lowered down not the pixsel on the texture surface bumped or lowered down, it is the whole texture moved. Thanks for answering these!


How to access specific child indices (directly, not using tags or searches)? I have a game object whose prefab is structured a very specific way. It is a conveyor belt. I intend to arrange them end to end and animate them all at once using a script. Right now I am trying to get the normalized heading vector between two children, TargetStart and TargetEnd (see images below) You can see that both of these objects are children of the prefab's first child. Because all of these instances will be structured the same, I want to compute the heading for the conveyor belt by accessing the locations of these children by their indices relative to the parent (which sounds like it should be simple and should be more efficient than searching by name or tag). I am anticipating a structure like this (pseudo code) heading targetEnd's position targetStart's position vector3 heading gameObject.GetChild 0 1 .position gameObject.GetChild 0 0 .position vector3 direction heading heading.magnitude How can this be done? I would like to know this so I can access any child I need to for any object by the child's index.


Unity Mirror Network Transform not working I am having an issue with Mirror's network transform component in unity. Players cannot see each other move, and in the inspector window only the host's player moves (this is not updated to the connected player though). In the inspector window you see a sphere moving and facing in the direction of the connected player (I did not program this so it must be Unity trying to tell me something) as per the picture below. Any help is much appreciated as there doesn't seem to be anybody that I can find online with a similar problem. Thank you!


Edit existing editor inspector? I want to write custom inspector for one of my scripts. All I want to change is input method for one of the strings to popup (so instead of writing whole string everytime I choose it from premade list of strings, like enums, the list is different for every dialogue). But the thing is it's VERY long inspector with a lot of variables and rewriting everything just for this one input doesn't click for me. Other problem is that this string is nested deep in the serializable object arrays, it look like so I'm very happy with how default inspector shows all the fields, expect this one string I want to change. I tried playing around with SerializedProperty but no luck. If it comes to available options I populate public string array with the names in the inspector (every dialogue has different list of participants) so the options should vary between different dialogues. What's the best way to set options? Is there a way to do it without rewriting whole inpector on your own?


Is a mesh OK to use for grass if there will be 1000's of them across the terrain? Am creating a low poly game in Unity 3D for PC. The terrain is made in Blender, so it's a fixed size, but quite large for the player to explore. I want to add things such as grass and flowers, but am not sure the best practices are for creating those types of assets. Is using a mesh for small clumps of grass the wrong way to do this if there will be 1000's of them? I will likely be using the occlusion culling system Unity provides, but I'm not sure if I still need to look at doing things such as grass in a different way for performance sake.


Unity Create large Terrain with accurate raycast detection? I'm not using the Unity Terrain because it lacks certain features. Amongst them, you cannot tile them You cannot create concave walls or make holes in it No custom textures, no detail textures, awful sculpting tools... the list goes on and on. So I imported my own Terrain as a Mesh. The collision works perfectly, however raycasting onto the Terrain is horribly inaccurate. Unity seems to compress the Mesh Collider depending on distance to player. See the video linked below. Since Unity is (by my knowledge) the only Game Engine that supports convex colliders, how do other game engines create Terrain colliders? For a racing game or a RTS or RPG the colliders are no problem, but for a shooter it's unacceptable. Here's a video showing the problem https youtu.be coiFS6IT4wI I've researched long and hard and there seems to be no known solution for this. So my question remains, if it's possible at all, how can i create large scale Terrains for Unity? This problem makes it completely impossible for me to create outdoor scenes. There HAS to be some kind of solution. 1) Raycasting script Spread float spreadAmount Mathf.Lerp(spreadMin, spreadMax, burstTimer spreadThreshold) Current Spread lerps between spreadMin and spreadMax by burstTimer (increases per shot) int i 0 totalShotDamage 0 Buckshot sends 8 rays down the range. totalShotDamage gets total damage done by all rays. Needed for displaying damage text while (i lt bulletCount) Repeats Shooting Vector for bulletCount amount (needed for buckshot) Vector3 shootDirection shootOrigin.transform.forward Shoot Vector 100 accuracy shootDirection shootOrigin.transform.right (Random.Range( spreadAmount, spreadAmount)) Randomizes Vector horizontally, reduces accuracy shootDirection shootOrigin.transform.up (Random.Range( spreadAmount, spreadAmount)) Randomizes Vector Vectically, reduces accuracy Ray ray new Ray(shootOrigin.transform.position, shootDirection) Ray from Shoot vector RaycastHit hitInfo if (Physics.Raycast(ray, out hitInfo, 2000, shootLayerMask)) Sets range of gun amp sends ray Vector3 hitPoint hitInfo.point Point of impact with any object GameObject go hitInfo.collider.gameObject GameObject of impacted Object string targetTag hitInfo.collider.gameObject.tag Tag of GameObject of impacted Object addHitParticleEffects(targetTag, hitInfo, enableBulletholes) Add hitparticle effects based on Tag (IMPACTmaterial) damageEnemy(targetTag, hitInfo, damage, damageRollOff) Damage enemy i total bullet count (needed for buckshot) 2) Terrain Inspector Settings 3) LOD Settings There are no LOD Settings (yet). Individual Planes of the whole Terrain and objects on top of it simply pop in and out of existence depending on the Players position.


Insert 3d text to the front face of a cube GameObject I want to add a text to a cube in Unity. I have a cube which has a 3d text as a child. I am using the below UnityScript to write on the 3d text var countdown int 200 function Update() GetComponent(TextMesh).text countdown.ToString() I am trying to write show the text to the front face(or very close) of the cube but I am failing. EDIT My difficulty is to make the text appear in the front side face of the cube, like it is written on it. Attaching the text or the script to any object is not an issue My last failed try was to use the below lines var tm gameObject.AddComponent(TextMesh) tm.text countdown.ToString() Any ideas?


Enemies and item drops issue Disclaimer I'm relatively new to developing games so bear with me. In my scene I have enemies and when they die, they drop items. No matter which item is dropped, the same prefab (the physical representation of the dropped item) is instantiated. That physical orb on the ground may represent different items. It could be a pile of coins, a sword, etc. Depending on which item is dropped, I want its name to appear in a UI label attached to the top of the item. Basic ARPG stuff really. The problem I'm running into is that I can't seem to get the references right. DisplayItemNameLabel is a script which is attached to each item when it is dropped. I did it this way so each item can be in charge of its own UI label. ItemDrops is attached to each enemy. SpawnItem(Item item) is a function which is called when the enemy dies. The last relevant Monobehaviour script is the ItemData script which is attached to an Item Manager game object which is there from the beginning and persists forever. This class just defines the different items that are possible in the game. So basically the structure is that when an enemy dies, if the random number generated is within some range, then some item will drop. If (randomNumber lt 0.5) SpawnItem(itemData.coin) where SpawnItem(Item item) is something like... private void SpawnItem(Item item) itemDropped true nameOfDroppedItem item.itemName Instantiate(itemPrefab, transform.position offset, Quaternion.identity) Again, this is attached to each enemy. In the DisplayItemLabel script then, I would like to set itemNameText.text to that nameOfDroppedItem. But the DisplayItemLabel script is attached to each item. I don't think I can make each item a child of each enemy because enemies are destroyed when they are killed so the scripts would be destroyed. I also can't use GameObject.FindGameObjectWithTag("Enemy").GetComponent lt ItemDrops gt () because it wouldn't always grab the enemy I want. I thought maybe I could set the text in SpawnItem but it would have to reference the correct item, so I couldn't use GameObject.FindGameObjectWithTag... What should I do?


How do I restart an animation that is already playing using SetTrigger? I have set up a relatively simple example scene with one enemy. This enemy is controlled with an animation controller. In this animation controller, I have set up a trigger named "Hit". The enemy plays an idle animation, and when my hero character shoots him, I set the trigger "Hit" via script like this animator.SetTrigger("Hit") This causes the animation controller to react to it, and it transitions from "Idle Animation" to "Hit Animation" The hit animation is 3 seconds long. After it has completed, the animation controller will automatically transition back to the "Idle Animation". I would like make it so that the hero character can shoot the enemy even though he is already playing the hit animation. Let's imagine you use a machine gun to shoot him repeatedly quickly. However, when I call animator.SetTrigger("Hit") while the hit animation is already being played, nothing happens. As I currently understand it, this makes perfect sense as the Trigger triggers the transition from animation A to animation B, and if we're already at animation B, then there can be no transition. The transition will only kick in if the animation controller is currently playing the "Idle Animation" as it can then transition to the "Hit animation" What could I do to "restart" the hit animation? Thank you.


How can OnMouseDown in the parent object be triggered from the child placed on top of it? I am learning Unity from a book. The example is to create a 2D memory game as follows (viewed in perspective view). The green (background) at z 5, the purple diamond (front card) at z 0 and the red (back card) at z 5 for example. The front card is set as the parent of the back card in the hierarchy window. A box collider (2D) component and a script below are attached only to the parent. public class FrontCard MonoBehaviour public void OnMouseDown() Debug.Log( quot testing 1, 2, 3! quot ) When I play the game and click the back card, the OnMouseDown gets invoked. Question How can the OnMouseDown get invoked when I click the back card by considering the script is attached to the front card game object that is placed below the back card?


How do I make an object's y axis align with a Vector3? I have a golf ball on the ground, and from a raycast, I have the normal which gives me the slope of the ground by the ball. I have an object which is rendered on the HUD to show that slope to the player. I have a parent object rotated 90 degrees around X, so that the indicator's Z axis points up. This way I can do this Quaternion yRot Quaternion.Euler(0, CameraController.Instance.CachedTransform.eulerAngles.y, 0) Vector3 displayGroundNormal yRot groundNormal lieIndicator3DParentCachedTransform.rotation Quaternion.LookRotation(displayGroundNormal) This, as far as I can tell, takes the ground normal, rotates it around the y axis so that it shows the proper perspective given the camera's facing. Then it tells that parent object to look in that direction, which aligns its z axis with the rotated ground normal. This works, except the object I have also rotates around the y axis depending on the orientation of the camera. I thought that I was throwing that information away in the second step by keeping only a Vector3 aligned with the ground normal rotated for the camera position. So I want this Not this


Pass parameters from html page to start() function in unity3D webplayer application I want to pass a parameter from web browser to Unity3D web player as soon as it is loaded. I know that, as soon as the web player is loaded, the start() function is execute inside web player. So I want to pass parameter from web browser to this start() function.


Creating an efficient 2D mobile game background I am working on a 2D unity mobile game and would like some advice on how to save as much MB's as possible with my background images. I can either create 15 600 x 1000 png images through an image manipulation program and import them into unity, each image is roughly 300 kB's before building the project. Or I can import a base background image that i would use multiple times, and also import a sprite sheet with scenery, and just place the sprites on the background layer of my game scene. Note, if i choose the second option there will be 30 100 tree sprites, along with enemy and player game objects in view of the main camera at a time. I'm not sure if this second option will bog down the game, because of all the individual sprites on the screen at once.


Choosing random array indexes in Unity C I want to change a string by randomly choosing an index in an array, using the random.range command in unity. Bare in mind that I'm using strings here, not floats or integers. Here is a code example(not the real thing. I'm just coming up with this by example, but it still has the same meaning. I may make a few typo errors as a result) public string ChangingString ("") public string ExampleArray new string 2 void Start () ExampleArray 0 ("String1") ExampleArray 1 ("String2") void OnGUI () if(GUI.Button(new Rect(10,10,100,24), "Randomize text")) ChangingString (code to choose random string using the ExampleArray) GUI.Label(new Rect(10,30,100,20), ChangingString) EXTRA NOTE I'M NEW TO USING ARRAYS.


Other methods to save data than PlayerPrefs? I've been saving data using the playerPrefs option in Unity till now. Is there any better secure way of saving data for developing mobile games. Somes sites have mentioned encryption of data how do I approach that?


Interpolate object collision stuck in Unity I am working on a very basic test in 2D. The problem I am having is that, when my sprite collides with the ground, it is checking the event too frequently. The sprite stays in limbo, as it doesn't have a chance to leave the ground. By the time it does, the check tells it to turn around, resulting it quickly going up and down. I uploaded an example clip to YouTube. When contact is made, the sprite needs to change it's Y axis direction. How do I fix this? Please see my code, below void Update () hitWall Physics2D.OverlapCircle(wallCheckUp.position, wallCheckRadius, whatIsWall) if (hitWall) moveUp !moveUp if (moveUp) transform.localScale new Vector3( 1f, 1f, 1f) GetComponent lt Rigidbody2D gt ().velocity new Vector2(speed, GetComponent lt Rigidbody2D gt ().velocity.x) else transform.localScale new Vector3(1f, 1f, 1f) GetComponent lt Rigidbody2D gt ().velocity new Vector2( speed, GetComponent lt Rigidbody2D gt ().velocity.x) Here is my object


Unlock cursor through script I am using unity's default FPS controller script. My game switches scenes, and when it does I can't move the mouse. I know that this is because of unity's m mouselook's lock cursor is on. What I don't know how to do is turn that boolean to false through a different script.


In Unity how can I know which direction is the screen auto rotated? From the Screen.orientation description I get If the value is set to ScreenOrientation.AutoRotation then the screen will select ... automatically as the device orientation changes. This seems to imply that if the screen does auto rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation. If that's so, how can I know in which direction it has been auto rotated? Disabling the auto rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either. This should be cross platform, without including any kind of non C plugin. (the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)


Calculating the bounding box of a game object based on its children 2D game with Unity. Have a parent game object, with several children objects scattered all over the scene. I want to calculate the bounding rectangle of the parent game object. Let the black dots be the children objects. The red rectangle is the bounding box. I am not really interested in the position I only want the dimensions of such box. Of course, the bounding box should also consider the bounding boxes of the children... and so on. How can I achieve this? I heard that Renderer has a bounds property... but my parent object doesn't have a renderer. And when I put one, the value is 0 anyway.


What's the better approach, running multiple server builds on one instance or running one server build and managing matches in different rooms? We are building a racing multiplayer game using Mirror and Unity and we've been able to successfully run the authoritative server on AWS Gamelift and Playfab so far. Both providers are with the flexibility of running multiple server builds and mapping with different ports. So I think running multiple server build for different matches on one instance is a bit expensive in terms of server usage as compared to running one server and managing multiple matches in different rooms. But overall it seems to be a safer option to go with since build crash and similar issues will only happen on one match and other matches (servers) will be running fine on the same machine and also it's a bit easier to handle and scale. What's your opinion on this? It might be useful if you share any blog or resource to look at for scaling and managing servers on gamelift playfab. thanks!


How can I get my physically based sky to be blue all the way down? I'm rendering with a physically based sky. I want to get a very simple light blue background but below the horizon the sky becomes grey brown. How can I get it so that the sky is blue all the way down? As if the edge of the city was the edge of the world. I also want to make the blue sky brighter, especially at the bottom.


Size of .skp gets doubled after importing to Unity I have created a 3D model in SketchUp, and it is about 1.6Mb in size. After importing it to Unity, the size more than doubled to 4Mb. Why is that?


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.


Destroy the enemy only if the animation is played and touch the enemy I am using Unity. I want to attack an enemy with a knife. So I created an object (the knife) and put an attacking animation to it. Now I want to destroy the enemy only if the attacking animation is played and the knife touches the enemy. And if the animation is not played and the knife touches the enemy it should show a game over screen.


Unity bounds includes the center of the scene I'm trying to get the bounds of an object and put a box around it. Sounds simple right? I just encapsulate all the bounds together and use its center and size to do so. But the problem is one corner of the box is always at the center of the scene, like a part of the object is there, unless the center of the scene is in the bounds. This is when object is at the center This is when it isn't This is the code i'm using public static Bounds Calculate(Transform TheObject) Renderer renderer TheObject.GetComponent lt Renderer gt () Bounds combinedBounds new Bounds() if (renderer ! null) combinedBounds renderer.bounds var renderers TheObject.GetComponentsInChildren lt Renderer gt () foreach (Renderer render in renderers) if (render ! renderer) combinedBounds.Encapsulate(render.bounds) return combinedBounds


How can I import a Google Sketchup model with textures? I'm using Unity 4 and trying to import a SketchUp Model into Unity and other Engines but I can't get it to import correctly. Can anyone help me out?


Would creating a player scriptable game using Unreal Engine or Unity violate their license agreement? I want to create a game in Unity or UE4 which allows the user to write scripts in Python and run them mainly to control the AI. I will have to find a way to enable runtime script execution first. After searching the internet i was able to find some ways that may work. What i cant find an answer for is how to limit the parts of engine and game code the user has access to so that the player doesnt feel like he's playing it in God mode. And the main question is that even if i am able to restrict access to the API will it violate the terms of agreement for these commercial engines because the player will get access to the underlying engine and will be manipulating objects within it. I don't intend to make a moddable game just a game that requires you to write some code but that would be an extreme case to think about.


Spawn Array of GameObjects to Array of Transforms I have a question regarding spawning an array of GameObjects in Unity. What I want to happen is that when a big enemy dies, it will spawn enemies into their respective Transform positions (i.e., Enemy 1 will spawn in Position 1, Enemy 2 in position 2, and so on). I suppose I could go on with something like C public GameObject Enemies public Transform SpawnPoints void KillEnemy() GameObject enemy1 Instantiate(Enemies 0 , SpawnPoints 0 .position, SpawnPoints 0 .rotation GameObject enemy2 Instantiate(Enemies 1 , SpawnPoints 1 .position, SpawnPoints 1 .rotation GameObject enemy3 Instantiate(Enemies 2 , SpawnPoints 2 .position, SpawnPoints 2 .rotation Destroy(gameObject) But the problems are 1. I'm aware that the code is expensive to run, especially since I'm doing a 2D game and 2. It provides no flexibility, meaning if I want a different enemy to use the same code, then I won't be able to do stuff like adding more enemies to spawn (after the first one dies, of course). So yeah, I hope I get some help with this. Thanks!


Unity 5.5 Android scaling The questions I've seen are outdated, explained, not to my liking, or just don't work. Problem I want to be able to create a game that can scale on all mobile devices with ease and with no pixelation. Extra Info I'm very new to unity and tackling the the software with all my might I'm sorry for being a noob. I already paired unity with my phone and set the build to android (Nexus 5). Aspect ratio is 10 16, The game is going to be portrait. I have no scripts or anything, Its legit a blank game with a camera that has a blue background. I have some pictures, if you need anything else for my assistance don't hesitate I'm here to learn and take, GULP, Constructive Criticism. PC Android


unity3d nullreferenceexception i want to display a mesh sequence so i imported my obj files and found a script and partially edit it a bit.My project looks like this the script is this using UnityEngine using System.Collections Animate a mesh by cycling through different meshes. author bummzack public class MeshAnimation MonoBehaviour public Mesh Meshes public bool Loop public float FrameDuration private int index private bool playing true private float accumulator private MeshFilter meshFilter public void Start() meshFilter GetComponent lt MeshFilter gt () index 0 public void Update() accumulator Time.deltaTime if( accumulator gt FrameDuration) accumulator FrameDuration index ( index 1) Meshes.Length if( index 0 amp amp !Loop) Stop() return meshFilter.mesh Meshes index print ("Hello World") the line that causes the problem is this meshFilter.mesh Meshes index and the problem shown in the console is this NullReferenceException MeshAnimation.Update () (at Assets MeshAnimation.cs 43) i know it has something to do with Meshes index being null but i cant find the solution because i think the Meshes array is properly filled.Can anyone suggest a solution? Thank you all in advance.


Remove Sprite Shape Controller Icons from 2D sprite shapes How do I get rid of those "purple icons in my scene"? They are so annoying ... they literally covers the entire 2d shape! GIF showcasing it


How to make animation in unity Dots hybrid? I'm working on isometric game in 2D but didn't find any good tutorial in how to handle animation...any help?


how to create a curve movement of slider in unity I am trying to create a curved (not circular) movement of slider. Here is my demo images for reference I have watched some tutorial but those are for circle images. I want to make this movement along the arrow images below car. Also if this can be done with just images without using slider that will be ok too. I just this done the simpler and easy way.


How should I account for the GC when building games with Unity? As far as I know, Unity3D for iOS is based on the Mono runtime and Mono has only generational mark amp sweep GC. This GC system can't avoid GC time which stops game system. Instance pooling can reduce this but not completely, because we can't control instantiation happens in the CLR's base class library. Those hidden small and frequent instances will raise un deterministic GC time eventually. Forcing complete GC periodically will degrade performance greatly (can Mono force complete GC, actually?) So, how can I avoid this GC time when using Unity3D without huge performance degrade?


Objects aren't rotating in sync This is a follow up question to How to reapply force applied to one object to another object I want to make two objects move, react to collisions and other stuff as if they were one. For example, Objects A and B are entangled. When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall. I tried changing position speed every frame, but this only works when done in one direction. Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it. Edit This is the new code which only fails when multiple collisions happen at once using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(Rigidbody)) public class EEScript MonoBehaviour public List lt EEScript gt activeObjects public new Rigidbody rigidbody public Vector3 lastPosition Start is called before the first frame update void Start() rigidbody gameObject.GetComponent lt Rigidbody gt () Update is called once per frame void Update() lastPosition transform.position private void OnCollisionEnter(Collision collision) foreach (EEScript entangled in activeObjects) if (entangled this) continue Rigidbody rb entangled.rigidbody if (rb is null) continue rb.velocity rigidbody.velocity rb.angularVelocity rigidbody.angularVelocity entangled.transform.position entangled.lastPosition transform.position lastPosition


How can i rotate both NPCS facing the door moving to the door and then...? I need to make some steps. To rotate both npcs but each time running the game they will rotate randomly from another direction. For example the first one will rotate from the right side or left side same the other one. They will facing the door and start moving to the door. Near the door she will open automatic they will wait then they will move through the door. one of the npcs will keep moving and will start random patrolling. The second npc will rotate facing the door from the outside and will do something like locking the door ( I will animate it later he will rotate facing the door wait 2 3 seconds will rotate and will join the first npc and start patrolling too. This is a screenshot of both npcs each one have a box collider. The door they should rotate smooth randomly and facing and moving to the door the one behind them. This is the behind the door outside the hall. This is where one of the npcs should start patrolling and the other one wait some seconds facing the door like he is locking the door and then after some seconds to join and start patrolling too. And this is the hall out side the door and then the hall right and left. They should be patrolling the hall right and left and also the hall with the door. But not getting too close to the door s so they will not open all the time. The last screenshot show where they should be patrolling. The left image is the hall outside the door the right image is a door on the front hall on the right and the bottom image the door on the left. It's like a T I need some guide how to start it by logic how to do it. I have the scenario in my mind what they should do the 4 steps. But not surw hot start doing it. The scenario in general is Two guards(npcs) lock the door from the outside and start patrolling outside.


Instantiation of a GameObject not working for a threading reason I receive the following error "INTERNAL CALL Internal InstantiateSingle can only be called from the main thread." "Constructors and field initializers will be executed from the loading thread when loading a scene." "Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function." whenever I try to instantiate some GameObject's using this function public void DisplayCalls () for (int i 0 i lt calls 0 .Count i ) for (int j 0 j lt impFields.Length j ) GameObject textClone Instantiate (textBox, Vector3.zero, Quaternion.Euler(Vector3.zero)) as GameObject textClone.transform.SetParent (canvas.transform) Text text textClone.GetComponent lt Text gt () text.text calls impFields j i text.alignment TextAnchor.MiddleCenter textClone.transform.localPosition new Vector3 ( 262.5f (175f j), (182f (30f i)), 0f) The function is called using this other function public void GetPanelInfo () string file "getpanelinfo.php" string hash Md5Sum (mostRecentID.ToString () SecretKey1 SecretKey2) string parameters "?mostrecentid " mostRecentID.ToString () " amp hash " hash string fullURL baseURL file parameters Uri fullURI new Uri (fullURL) WebClient client new WebClient () string jsonString string.Empty client.DownloadStringCompleted (sender, e) gt if (!e.Cancelled amp amp e.Error null) jsonString e.Result JSONNode json JSON.Parse (jsonString) for (int i 0 i lt json "calls" .Count i ) for (int j 0 j lt calls.Length j ) calls j .Add (json "calls" i names j ) mostRecentID json "calls" i "callID" .AsInt else if (e.Cancelled amp amp e.Error null) Debug.Log ("Cancelled") else Debug.Log ("Error " e.Error) loading false LogCalls () DisplayCalls () client.DownloadStringAsync (fullURI) Which is called once using a button. I cannot seem to find the problem, but as stated above, the error says that it is a threading problem and that I cannot call instantiate from another thread other than the main one. I do not know how to change the instantiation to another thread, but any help to solve this problem would be much appreciated.


Create borders and clickable areas from image Crusader Kings, Europa Universalis and several other strategy games use provice based maps where "tiles" are not squares nor hexagons. Border style indicates different ranks owner. I've done some research and this is what I found from modding guides they seem to use a source image to dynamically generate the borders which are used to separate the provices but also to indicate currently selected areas (border changes color or flashes etc) and Im pretty sure that same file is used for "clickable areas" (click on provice to get province details screen). Source image contains all the provinces painted with solid colors. This image is same size as height map (water bodies and land masses) to align geographical shapes with provinces. Then there's some sort of dictionary file (text, JSON etc) that has all the province colors that maps these colors to meta data about the province. It also makes provinces "loopable" for game engine in order to add them to in game database and to use colors to find the correct shapes from image. Example in JSON "key" is RGB color that points to correct province in previous image "253 28 37" "name" "Kent", "otherStuff" 13 , "142 133 150" "name" "Oxford", "otherStuff" 54 How to create referenceable borders and clickable areas from source image?


Missing references in built bundles The following is a copy of our post in Unity Forum (https forum.unity.com threads missing references in built bundles.1103689 ) Hello, We have a bundle for our scenes and another one to store our prefabs (actually we have around 10 bundles but let's keep it simple). In every scene we have unpacked prefab instances. We have no problem in playmode using the AssetDatabase but once we use built addressables some unpacked prefab instances in our scenes are broken. Sprites and or scripts are missing in a inconsistent way in some scenes those objects are fine and sometime they are not. This comes along multiple warning messages quot The referenced script (Unknown) on this Behaviour is missing! quot . Note that the issue also happens when we fully deploy our player. Unity version 20193.3.13 Addressables version 1.16.1 Solution 1 We tried to remove addressable prefabs (A,B,C in the diagram) from their bundle since we don't really have to instantiate them at runtime for now and it worked. Solution 2 We also tried to put scenes and prefabs into the same bundle and it worked too. Solution 3 Switch to 1.18.2 and 1.15.1 version of addressable package and it didn't work. Solution 4 Finally we tried to use the Duplicate Bundles Dependencies analyzer multiple times in order to have no more issues of this type and it didn't work. Questions 1 As far as we understand, when addressable groups are built, Unity computes all dependencies and build them inside the bundle along the orignal assets (in my diagram quot Scenes quot bundles is packed with D'). What we don't understand is why having our prefabs in a separated bundle break references link in the scenes. Our guess is that Unity doesn't know which version of those dependencies to use (the one in the scene bundle or the one in the prefab bundle) and somehow fails to load them properly. Question 2 Is splitting our content is a good approach, we did it mostly for visibility but it appears to be more a problem in the long term, what are your guidelines regarding this matter ? Question 3 Why Duplicate Bundle Dependency rule has to be processed multiple times to properly fix every issue ? We think that running this rule creates duplication issues itself but we can't really tell.. Thanks.


How do I use an external FBX object in Unity? Is it possible to use an external .fbx object in Unity 3D the same way we can insert a picture? Something like myPath "http www.myserver.com object myobject.fbx" ?


Drawing rectangle around a target on screen I am just started with Unity and C . I need in my work to do rectangle on a scene. I have a 3D scene, say some warehouse and there is an object. Camera is animated and moving towards the object. Is it possible to draw a rectangle around the object on the camera screen while the camera is moving unless the object on the screen? The task is like keeping target in war flight games. This is my code, where I tried to draw rectangle anywhere using System.Collections using System.Collections.Generic using UnityEngine public class MY getting images MonoBehaviour Start is called before the first frame update public GameObject pallet public Camera color cam public Vector3 pos LineRenderer l void Start() pallet GameObject.Find("PalletWood01") l pallet.AddComponent lt LineRenderer gt () List lt Vector3 gt ps new List lt Vector3 gt () ps.Add(new Vector3(0, 0)) pos pallet.transform.position ps.Add(new Vector3(10,10)) l.startWidth 1f l.endWidth 1f l.SetPositions(ps.ToArray()) l.useWorldSpace true Finding camera in a scene tag needed camera, for example "Player", and then GameObject.FindWithTag("Player").GetComponent lt Camera gt () Tag the camera another way for deployment color cam GameObject.FindWithTag("Player").GetComponent lt Camera gt () pos color cam.transform.position pos pallet.transform.position Debug.DrawLine(Vector3.zero, new Vector3(0, 0, 5), Color.red) Debug.Log(pos) Update is called once per frame void Update() Debug.Log(pos) pos color cam.transform.position Debug.Log(pos) The scene now looks like on the image above I want 2d rectangle around the pallet drawn on the screen.


How to move my cube left or right using touch Inputs (C ) in unity I am trying to create a 3d game in unity. I have a cube in unity and I want it to move left or right on swipe . It should move to a distance till where user swipe or take their finger off of a screen. I want it to move fast or the cube should move fast on swipe and cube should flow smooth. Like in the gif there is a circle and the user use their finger to move the circle till wherever the user swipe it and it should be instant and I want my cube to move like that at a distance till where user swipe their finger and it should be instant and fast. I don't know how to do it. Any help is appreciated!


Add a tag in Unity editor in code How to add a tag in editor? I am working on automatic asset generation and I would like to use tags for certain objects.


Precise punch animation for unity I'm using blender to model, rig and animate my character for a Unity game, but there is something that I can't figure out by myself neither find on the internet, for example Lets say the main character is able to punch npcs and I want that punch aimed to the face but not all npcs have the same height. How can the animation be adjusted to handle this? Inverse kinematics seems to be the solution but to this date I couldn't find any good example or information about this subject better than "Check this box to fix the animation for stairs" and so on.


Unity IOS game restart when you press the home button Why does my unity IOS game restart when i press the home button on the device? The same game worked fine on Android device and did not restart on pressing the home button. Thanks


Unity How to apply bloom to only some objects in the scene? In my game I want to apply bloom, from the standard assets, to only a few objects in the scene. To do that, I set up 2 cameras at the same position and orientation, one with the bloom component and the other without. Then I put the blooming objects on a "Bloom" layer, set the blooming camera to only render objects on this layer, and the main camera to render everything else. Then I noticed that, if the main camera has a depth lower than the bloom camera, then the bloom camera will apply bloom to everything in the scene. I guess that's because the bloom effect works on everything rendered up to the point the script is executed. So I made sure that the bloom camera has the lowest depth and clears with a solid color. Main camera does not clear. However, now I lose the illuminated pixels around the blooming objects. I guess they are overwritten by the main camera, since the blooming camera probably did not give them any depth. Here's a simple scene to illustrate the problem Currently the game looks like this If I swap the configuration of the 2 cameras (Main camera lower depth, clear with solid color Bloom camera higher depth, don't clear), the game looks like this (exaggerated for demonstration) What I want is the yellow object to look like that in the last image, and the purple object to look like that in the second last image. How? Because of company policies, I am limited to Unity 5.4.1f1, and cannot use anything not made by Unity in the Asset Store.


Resize rigidbody in runtime, Box collider OnTriggerEnter not work Scene setting Object A Rigidbody, kinmeatic Box collider, is trigger true. Object B Box collider, is trigger true. Script is on Object A void FixedUpdate() if(increaseScale) transform.localScale transform.forward speed when to stop if ((AEForward transform.localScale.z).sqrMagnitude gt range range) increaseScale false void OnTriggerEnter(Collider other) Debug.Log(other.transform) No log message when part of object A is inside B. And the funny part is if I use it on a sphere collider, it works. (use transform.localScale new vector3(1,1,1) speed instead )


Unity Global illumination seems no longer applied to static objects on runtime First of all I'm newbie with Unity, so please forgive me if the answer of this question is obvious for any experimented developer. So, in one of my project I have this result while I run the project in the editor However, on runtime I get this result As you can see, several objects in the scene are no longer lighted. In fact, I noticed that ALL my static objects lost their illumination on runtime. I tried with Windows and WebGL as targets, same result. As I'm hobbyist, I may provide any info about the project configuration. Better, I can provide the Git link of my project https github.com Jeanmilost Unity tree master Survival 20Demo 20Scene This is a demo project, but in the future I'm interested to create more serious projects, and thus I need to understand why this issue happen. So if someone can point me what I'm doing wrong, I would be very grateful, because I already spent some hours to search the solution, without success.


Make an object rotates by an arbitrary angle and rotates toward a target in Unity I have an object facing up in Unity. I need it to move from point A to point B, without prior knowledge of where A and B are. So when I place it at point A, I need to rotate it toward point B. I used this this.gameObject.transform.rotation Quaternion.FromToRotation(A.position, B.position) However, before doing the movement, I also need to rotate the object by 90 around the X axis. I used this this.gameObject.transform.rotation Quaternion.Euler(90.0f, 0.0f, 0.0f) These two functions worked, but separately. When I try to use these two functions together, the last function called overrides the other.


How to test if procedurally generated level for infinite runner can be passed? I have a 2D infinite runner platformer game built in Unity 5, where the level procedurally generates itself. I need to check if it is possible to pass the holes on the level. How could I do that?


How do I get Input Positive Button value in Runtime? In Unity in InputManager I assigned R Button to "Restart" name. Now that property (Restart) has another property with a key "Positive Button" and string value "R". In the game I can show notice to user "click R for Restart!" But what if user will change that key in the start config window? For example from R to T button. Now the game should display notice "click T for Restart!" Question How do I get changed Positive Button value by name "Restart" via script in Runtime? Is it possible? p.s. in Editor I can do this SerializedObject inputManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings InputManager.asset") 0 ) SerializedProperty axisArray inputManager.FindProperty("m Axes") for (int i 0 i lt axisArray.arraySize i) var axis axisArray.GetArrayElementAtIndex(i) var axisName axis.FindPropertyRelative("m Name").stringValue if (axisName "Restart") restartButtonValue axis.FindPropertyRelative("positiveButton").stringValue break But it allows to use it only in the Editor. Because it uses UnityEditor.dll


Chess engine stock fish process for mobile I am making the chess interface I designed for a game. I am using the process to get answers from a stock fish binary stockfish new Process StartInfo new ProcessStartInfo FileName System.IO.Directory.GetCurrentDirectory () " Assets Scripts Stockfish stockfish.exe", Arguments "", UseShellExecute false, RedirectStandardOutput true, RedirectStandardInput true, RedirectStandardError true, CreateNoWindow true The problem I face is it worked for my Windows build but for mobile package build it won't work with the executable. Is there a way around it?


Limit rotation angle I am currently trying to rotate the weapons of a spaceship towards the mouse position, but in order to avoid the collision of projectiles with the ship I want to limit the angle the weapon can turn. I've tried doing this Vector3 mousePos Input.mousePosition float range 100.0f float rotStep 0.1f Vector3 positionOnScreen Camera.main.ScreenToWorldPoint(mousePos Vector3.forward range) Vector3 targetDir positionOnScreen transform.position Vector3 newDir Vector3.RotateTowards(transform.forward, targetDir, rotStep Time.deltaTime, 0.0f) Quaternion lookRot Quaternion.LookRotation(newDir) float xAngle lookRot.eulerAngles.x if (xAngle gt 10 amp amp xAngle lt 180) xAngle 10 else if (xAngle lt 350 amp amp xAngle gt 180) xAngle 350 float yAngle lookRot.eulerAngles.y if (yAngle gt 10 amp amp yAngle lt 180) yAngle 10 else if (yAngle lt 350 amp amp yAngle gt 180) yAngle 350 float zAngle lookRot.eulerAngles.z if (zAngle gt 10 amp amp zAngle lt 180) zAngle 10 else if (zAngle lt 350 amp amp zAngle gt 180) zAngle 350 lookRot.eulerAngles new Vector3(xAngle, yAngle, zAngle) transform.rotation lookRot The problem here is that I don't know how to limit the rotation angle since it's not the same depending on the ship rotation (for example if it's (0, 0 , 0) or ( 90, 90, 90)). I've tried using transform.localRotation too, but still happens the same. Do you how could I limit the rotation regardless of the ship rotation?


Prefabs property is not overriding when changing from editor script? In unity we can have different instances of a prefab with different properties. Unity represents the overridden property with bold characters. This works fine when manually change the value of prefab instance. But when I do it using a editor script, it do not turn bold and the property value changes to the source prefab when I play the game. Here is an example of the code using UnityEngine using UnityEditor CustomEditor(typeof(testScript)) public class editor Editor public override void OnInspectorGUI() DrawDefaultInspector () testScript scrt (testScript)target if (GUILayout.Button ("button")) scrt.test() . using UnityEngine public class testScript MonoBehaviour test() gameManager GameObject.Find("GameManager") gameManager.GetComponent lt gameManager gt ().arr new GameObject 3 . using UnityEngine public class gameManger MonoBehaviour public GameObject arr The arr array in gamemanager class is not overridden and it changes to the source prefab value on play. EDIT actual function called from editor script public void assignPortalPass() GameObject gameManagerObj GameObject.Find ("Game Manager") gameManager gameManagerScript gameManagerObj.GetComponent lt gameManager gt () Transform passed GameObject.Find ("passed").transform int noOfChild passed.childCount if (noOfChild ! gameManagerScript.noOfPortals) Debug.LogError ("Check passed objects and noOfPortals (class gameManager) because both values are different") return Undo.RecordObject(gameManagerObj, "Made some changes to gameManager") as suggested by the answer gameManagerScript.portalPass new GameObject noOfChild for (int i 0 i lt noOfChild i ) gameManagerScript.portalPass i passed.GetChild (i).gameObject


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?


Unity3d vector and matrix operations I have the following three vectors posA (1,2,3) normal (0,1,0) offset (2,3,1) I want to get the vector representing the position which is offset in the direction of the normal from posA. I know how to do this by cheating (not using matrix operations) Vector3 result new Vector3(posA.x normal.x offset.x posA.y normal.y offset.y, posA.z normal.z offset.z) I know how to do this mathematically Note indicates a column vector, indicates a row vector result 1,2,3 2,3,1 0,0,0 , 0,1,0 , 0,0,0 What I don't know is which is better to use and if it's the latter how do I do this in unity? I only know of 4x4 matrices in unity. I don't like the first option because you are instantiating a new vector instead of just modifying the original. Suggestions? Note by asking which is better, I am asking for a quantifiable reason, not just a preference.


Convert Canvas Space point to local space of a rotated rect? I got a quite tricky problem I have my mouse position and my rectangle position in canvas space(screen space but with adjusted scaling). Now I want my mouse position converted to local space of the rectangle. Problem is, the rectangle can be rotated. Without rotation its quite simple and works nicely. Heres a graphic for better demonstration Edit3 Got it finally working. I messed up with a minus in the calculation instead of using a . Also the hierarchy of the image in unity was incorrect. Lastly I had to change the rotation from CCW to CW(Thanks unity for using CCW in your UI...). This is my final solution Code Unity C var mapRect MapContentTransform.rect Canvas Space Map Center var mapPositionCenter CanvasRectTransform.InverseTransformPoint(MapContentTransform.position) mapPositionCenter.x CanvasRectTransform.rect.width 2.0f mapPositionCenter.y CanvasRectTransform.rect.height 2.0f Mouse Position in Canvas Space Vector2 mousePositionCanvasSpace CalculateScreenspacePositionCanvasSpace(new Vector2(Input.mousePosition.x, Input.mousePosition.y)) Rotation angle of the Map in Radians float theta (MapContentTransform.eulerAngles.z 360.0f) Mathf.Deg2Rad var rotatedX ((mousePositionCanvasSpace.x mapPositionCenter.x) Mathf.Cos(theta) (mousePositionCanvasSpace.y mapPositionCenter.y) Mathf.Sin(theta)) mapRect.width 2.0f var rotatedY ((mousePositionCanvasSpace.y mapPositionCenter.y) Mathf.Cos(theta) (mousePositionCanvasSpace.x mapPositionCenter.x) Mathf.Sin(theta)) mapRect.height 2.0f Thank you Kyy13!


What is the difference between the two circles in the rotation tool in Unity? What is the difference between the two circles in the rotation tool in Unity? In 2D rotation tool there are two circles which allow to rotate an object. And I can not conceive a difference between them. Could someone explain me what is the purpose of having both of them? It seems they both do the same.


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


Button not clickable if it's under a Content Size Fitter Horizontal Layout Group in Unity? I'd like to make a Tooltip System Tutorial System. I'm using the Content Size Fitter and Horizontal Layout Group components to have a dynamic text bubble.. Also I'd like to attach a button to it, so when the tooltip appears, the game pauses, and then when the player clicks the button, it closes the tutorial text, resuming the flow of the game. But for some reason the click doesn't reach the component. Not even the animation happen, like something is blocking my button from being clicked. Hierarchy uiTutorialText Has a CanvasGroup to fade the whole structure. Interactable true, BlocksRaycast false TutorialText Has an Image (background) RaycastTarget false Has a Content Size Fitter and a Horizontal Layout Group And Text and Button are just simple plain Text and Button objects, and the Button's Interactable is true. I also tried making the Button a child of Text, and then translating it sideways, so the button doesn't share screen space with the tooltip. But it's not clickable this way as well. As soon as I move the Button out of the hierarchy, like directly under the canvas, it works.


How can I animate draw a line renderer over a given period of time I have created a line renderer using the code below public class MyLineRenderer MonoBehaviour LineRenderer lineRenderer public Vector3 p0, p1 Use this for initialization void Start () lineRenderer gameObject.GetComponent lt LineRenderer gt () lineRenderer.positionCount 2 lineRenderer.SetPosition(0, p0) lineRenderer.SetPosition(1, p1) How can I write a coroutine that will animate draw the line over specific duration, say 2 seconds?


Advice on Story Text Based Game I am currently in preparation on making a game. This game will be looks like Lifeline by 3 Minute Games, which is a story text based game. My game will have the same concept with it. Where there will be a scrollable history of conversation between player and characters in game. However, my game will has more than one conversation history. He will be able to interact with more than one character. Therefore, when the game start, it will show list of interactable characters in game, and player can choose who he will interact with when any available. I am planning to make it with Unity. But I don't know is it possible to create some scrollable history of text, each with different content, like chat history, in Unity. So I wanna ask your opinion, is it good to just continue with using Unity, or should I change the game engine I use? If I should change, what is the best game engine to cope with this kind of game? Thank in advance )


How can I draw orbit paths for a solar system? I m trying to make the orbital paths visible for my solar system simulation game. I have most around with trail renderers and solid line sprite but not achieving the desired look I want. I m hoping to get something where the path is alway present but darker directly behind where the planet currently is, and lighter and more transparent ahead of where it s going. This effect is achieved in the game Worbital. If anyone could point me in the right direction how I can achieve this I would be much appreciated.


how to implement ARVR controller in unity vuforia hello i've been strugling figuring out this thing. i'm trying to make ar controller for my vr cardboard game, so the idea is using AR and VR simultaniously. you will completely in vr game but your phone camera wil be turned on and set to AR mode. while you're in vr mode and your AR camera will detect your marker and repositioned it based on your view and the distance between camera and object. that marker will appear in your vr game and you'll make it as a controller. then maybe you want to make that marker appear as a gun, a sword, a shield or whatever it is that can be work with this concept or maybe you just can watch it to get the idea if my explanation is not clear enough https www.youtube.com watch?v a v a23u6n0 so i'm trying to implement it with vuforia as it's augmented reality API and of course Unity. now i'm on the stage where i already now how to use AR amp VR simultaniously and how to transtition between AR to VR or otherwise. i'm still strugling on how to re potitioning my marker to correct position in my VR world. i already tried asking this in vuforia forum but there's still no answer until now. if you guys can help me with this it would be a big help !! thx before


why command is not executing on local player I am getting very strange behavior, if my player instantiate as host (Server Player) then my command function runs perfectly and certain object become instantiate but if I join the host then my Command doesn't execute on my local player but runs on all other clients. void Start() if (isLocalPlayer) Debug.Log("It is VR Player spawn Start") SetVRLocalPlayerSetting() InstantiateMimicVRHeadAndController() CmdInstantiateMimicVRHeadAndController() else Debug.Log("It is not vr Player its not isLocalPlayer") DisableSelectedMonobevaiourScripts() Command This function have a problem public void CmdInstantiateMimicVRHeadAndController() Debug.Log("instantiateing the controller and head object") vrHeadCopyObj (GameObject) Instantiate(vrHeadObjPrefab) vrRightCtrlCopyObj (GameObject) Instantiate(vrRightCtrlPrefab) vrLeftCtrlCopyObj (GameObject) Instantiate(vrLeftCtrlPrefab) spawn the bullet on the clients NetworkServer.Spawn(vrHeadCopyObj) NetworkServer.Spawn(vrRightCtrlCopyObj) NetworkServer.Spawn(vrLeftCtrlCopyObj)


Unity 2d Constant Player movement along the x axis The movement of my player depends on swipes, swipe left character moves to the left swipe right character moves to the right right now i am only getting a small movement, meaning that the player moves along the X axis but it stops inmediatelly. This is the code i have to check the swipes direction PLayer.cs public Vector2 desiredPosition void Update() if (MobileInput.Instance.SwipeIzquierda) desiredPosition Vector2.left if (MobileInput.Instance.SwipeDerecha) desiredPosition Vector2.right transform.position. Vector2.MoveTowards(transform.position, desiredPosition, moveSpeed Time.deltaTime) In the MobileInput script i control the swipes private const float DEADZONE 100.0f public static MobileInput Instance set get private bool swipeIzquierda, swipeDerecha, swipeAbajo, swipeArriba private Vector2 swipePuntoAhora, touchComienzo public bool SwipeIzquierda get return swipeIzquierda public bool SwipeDerecha get return swipeDerecha public bool SwipeArriba get return swipeArriba public bool SwipeAbajo get return swipeAbajo private void Awake() Instance this Use this for initialization void Start () Update is called once per frame private void Update () Debug.Log(SwipeIzquierda) swipeDerecha swipeIzquierda false region Input Pc if (Input.GetMouseButtonDown(0)) touchComienzo Input.mousePosition else if(Input.GetMouseButtonDown(0)) touchComienzo swipePuntoAhora Vector2.zero endregion region Mobile Input if (Input.touches.Length ! 0) Debug.Log("hola") if (Input.touches 0 .phase TouchPhase.Began) touchComienzo Input.mousePosition else if (Input.touches 0 .phase TouchPhase.Ended Input.touches 0 .phase TouchPhase.Canceled) touchComienzo swipePuntoAhora Vector2.zero endregion region Calcular distancia swipePuntoAhora Vector2.zero if (touchComienzo ! Vector2.zero) Mobile if (Input.touches.Length ! 0) swipePuntoAhora Input.touches 0 .position touchComienzo PC else if (Input.GetMouseButton(0)) swipePuntoAhora (Vector2)Input.mousePosition touchComienzo endregion region Calcular DEadzone del swipe if (swipePuntoAhora.magnitude gt DEADZONE) float x swipePuntoAhora.x float y swipePuntoAhora.y if (Mathf.Abs(x) gt Mathf.Abs(y)) Izquierda o Derecha if (x lt 0) swipeIzquierda true else swipeDerecha true else Arriba o Abajo if (y lt 0) swipeAbajo true else swipeArriba true touchComienzo swipePuntoAhora Vector2.zero endregion The goal of all of this is to If i swipe to te right, the player starts to walk to the right AND continues doing so unless i swipe to the left, only then the player starts to move to the left. I want the movement to be constant in one direction until the other swipe changes it Any help with this will be really appreciated


Unity3D Resources load to materials, how to? I think is a simple question, but I don't know nothing about it I have an created material in my materials folder, I just want to apply it to the GameObject by script. I am trying this.GetComponent lt Renderer gt ().materials 0 Resources.Load("Test", typeof(Material)) as Material The material name is Test and it is in materials folder, but the return is always the default material applied to the GameObject, so I think Unity didn't found it.


How do I access objects that are in the next scene I'm loading? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class HouseExit MonoBehaviour public Transform player public void Houseexit() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1) void OnCollisionEnter2D(Collision2D col) if (col.gameObject.CompareTag( quot Player quot )) Houseexit() GameObject.Find( quot Wizard quot ).transform.position GameObject.Find( quot SpawnPos quot ).transform.position This code belongs to the scene quot Goblin House 1 quot and I'm trying to find the wizard and the spawn position both from level 1.


How to import a NET .dll newer than 2.0 into Unity? I'm trying to build one of the simple EventBus libraries from Github and import them into Unity. Here are the libs TinyMessenger and RedBus It's that simple I take the source code, build it through the VS2015 and place the .dll into the Assets Plugins folder. Then, I have no way to use the lib's namespace (Unity doesn't read the file). Both of these libraries are written in NET 3 or 4 and this is the failure's reason. I've recompiled the second one (removed the System.Linq code, changed the project's version) to NET 2.0 and it worked, but that's not the point. I need the first library and it ain't easy to rewrite the entire 4.0 code to 2.0 without Linq. As I remember, you can use System.Linq in Unity (at least, I did it once). This means that Unity uses some kind of trickery magic, as always. What's the problem here? Is there any way to get this working?


Why is my game object generated by a custom Unity editor script missing its sprite? I have a number of sprites that I generate outside of Unity. I'd like to automate the process of importing these sprites into Unity as fully configured game objects. I'm trying to do this through a Unity editor script, but I'm having some difficulty. When I run my script, my game object is saved as a .prefab as expected. However, the Sprite I'm assigning to my game object's SpriteRenderer component is missing In my script, I'm assigning my SpriteRenderer's sprite property to a Sprite object that I dynamically create in the script. Here's the relevant excerpt from my editor script GameObject gameObject new GameObject(fileName) SpriteRenderer spriteRenderer gameObject.AddComponent lt SpriteRenderer gt () texture size will be replaced during the LoadImage() call Texture2D texture new Texture2D(1, 1) texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName ".png"))) spriteRenderer.sprite Sprite.Create( texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.0f, 0.0f) ) PrefabUtility.CreatePrefab("Assets Prefabs " fileName ".prefab", gameObject) DestroyImmediate(gameObject) I can verify through logging that the image path to my .png is correct and that the Texture2D and Sprite objects seem to be instantiated correctly. For example, I can do this logs "580" as expected Debug.Log(texture.width) What am I doing wrong? How can I save this game object as a .prefab without losing its sprite information?


How do I slice a 3D object at runtime in Unity? I'm specifically looking for some sort of algorithm or way that can "cut" a 3 dimensional mesh with some other game object. How would I implement this?


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


How to make UI text longer? I'm working on a menu that needs a wordy description, but I've noticed that it only shows 4 letters, then cuts off and this doesn't seem right. I right click, select UI text and again, it only displays 4 words, even though I can write a lot more there. Am I doing something wrong here? I'm not sure how to get past this and I want to ask if anyone knows how to get past this? It seems like such a strange limit to put on the UI canvas.


ReorderableList in Unity with Enums I'm trying to setup a simple ReorderableList in Unity 2017.3 for a list of enums. Adding items workes fine but selecting, dragging and deleting items from the list does not (see gif). Here is my code Serializable public enum RoofType HIP, GABLE, FLAT, NONE UnityEditorInternal.ReorderableList roofTypeList new UnityEditorInternal.ReorderableList(roofTypes, typeof(RoofType), true, true, true, true) roofTypeList.drawHeaderCallback (Rect rect) gt EditorGUI.LabelField(rect, "Roof types") roofTypeList.drawElementCallback (Rect rect, int index, bool isActive, bool isFocused) gt roofTypes index (RoofType)EditorGUI.EnumPopup(rect, roofTypes index ) roofTypeList.DoLayoutList() Any ideas why this does not work? My guess it is because I use enums and not classes but it is not documented anywhere.


Rushing water in Unity How would I go about creating a river with rushing water? I can do the texture around it but I'm stuck on the actual water part. This is in Unity3D.


Are constantly growing (in dimensional size) GameObjects a problem? It's possible the following is fundamental to Unity, and not a problem? I am using an example of a WheelJoint2D Car from the Ray Wenderlich tutorials. Note from the pic below, the top level game object called "Car". It has children of "Body" which contains the wheel joints and the wheels (attached to the wheel joints). The top level "Car" GameObject is placed in the scene (here at X 6.4). Now we run the game for a short time, and the car rolls forward as expected. From the inspector, we would see that X position of the Body and the wheels has changed, but note that the Car game object's X position has not changed So, in reality the game object "Car" has grown in the X dimension. Granted this growth seemingly has nothing to do with physics simulation (as all the rigidbodies and joints are moving along as expected). One interesting side affect is that this growth might make scaling the parent object problematic. But it seems that if this were an infinite runner, you would have an ever increasingly wide "Car" object. On the surface this seems undesirable, but is it really? And if so, how would you mitigate this (given that this game object hierarchy seems to be the prescribed way of using the wheel joints).


What does vertex disp and tessellate tessEdge mean? Shader Unity I came across the following declaration on unity tutorial pragma surface surf BlinnPhong addshadow fullforwardshadows vertex disp tessellate tessEdge nolightmap I think disp is the displacement shader but what does vertex disp mean? Likewise for tesselate tessEdge. from https docs.unity3d.com Manual SL SurfaceShaderTessellation.html Thanks. I am rather new to HLSL.


Recursive Unity Coroutine I have a co routine which is heavily reliant on calling itself to get the task done. I have tested it and the code works fine, the problem is that the co routine will return every time that it enters itself recursively. IEnumerator test(arg1, arg2) I want to pause here yield return null I don't want to pause on any of these yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) In the example above I have a yield return at the top that is hit and pauses the co routine, thats fine. Then there are the calls to itself below which also pause the co routine. How do I avoid pausing the co routine on the recurcive calls?


Trouble with LineRenderer with orthographic camera in Unity When a weapon is fired, I want to draw a line for the bullet's trajectory. I am using a LineRenderer to draw the trajectory with the code below void FixedUpdate () timer Time.deltaTime if (Input.GetButton ("Fire1") amp amp timer gt timeBetweenBullets amp amp Time.timeScale ! 0) Shoot () if (timer gt timeBetweenBullets effectsDisplayTime) DisableEffects () void DisableEffects () gunLine.enabled false void Shoot () timer 0f Set first point gunLine.SetPosition (0, transform.position) shootRay.origin transform.position shootRay.direction transform.forward gunLine.SetPosition (1, shootRay.origin shootRay.direction range) I am using an orthographic camera in the scene. The line will show up but at certain rotations the line will partially render or be completely hidden. Oddly, the line will always render in the scene view the problem only exists in the game view. Has anyone had this issue?


Unity Part of the sprite is covered in shadow I have a sprite with Transparent Cutout Diffuse shader. Recieving shadows is turned on in SpriteRenderer. The light is a pointlight and I am using deffered rendering path. However when I am above or right of the object, it is covered in shadow. When I am below or left of the object everything seem to work as it should.If I place the light in the center of the sprite, only a part of the sprite is lit up, the other part is covered in shadow. Maybe it is something with normals? I need to get rid of the self shading effect. Shader Shader "Transparent Cutout Diffuse" Properties Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Trans (A)", 2D) "white" Cutoff ("Alpha cutoff", Range(0,1)) 0.5 SubShader Tags "Queue" "AlphaTest" "IgnoreProjector" "True" "RenderType" "TransparentCutout" LOD 200 CGPROGRAM pragma surface surf Lambert alphatest Cutoff sampler2D MainTex fixed4 Color struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 c tex2D( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG Fallback "Transparent Cutout VertexLit" I found out what unity uses for lambert lightning. Since I use deffered rendering so unity should use function with PrePass prefix. But the implementation of the actual lighning is implemented somewhere else and is it used for all materials, that looks like dead end. Custom Lightning inline fixed4 LightingSLambert (SurfaceOutput s, fixed3 lightDir, fixed atten) fixed diff max (0, dot (s.Normal, lightDir)) fixed4 c c.rgb s.Albedo LightColor0.rgb (diff atten 2) c.a s.Alpha return c inline fixed4 LightingSLambert PrePass (SurfaceOutput s, half4 light) fixed4 c c.rgb s.Albedo light.rgb c.a s.Alpha return c inline half4 LightingSLambert DirLightmap (SurfaceOutput s, fixed4 color, fixed4 scale, bool surfFuncWritesNormal) UNITY DIRBASIS half3 scalePerBasisVector half3 lm DirLightmapDiffuse (unity DirBasis, color, scale, s.Normal, surfFuncWritesNormal, scalePerBasisVector) return half4(lm, 0)


Player not detecting layermask I'm trying to implement a simple collision detection for my player but it is not detecting the layer mask as my Player comes into contact with it. I have a move point that moves slightly ahead of the player, and if it comes in contact with the StopMovement layermask then it should NOT move any further. Unfortunately, the layer is never detected and therefore the player just moves right through the object. Script using System using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour public float moveSpeed 5f private float moveHorizontal private float moveVertical public Transform movePoint public LayerMask whatStopsMovement Start is called before the first frame update void Start() movePoint.parent null Update is called once per frame void Update() moveHorizontal Input.GetAxisRaw( quot Horizontal quot ) moveVertical Input.GetAxisRaw( quot Vertical quot ) private void FixedUpdate() transform.position Vector3.MoveTowards(transform.position, movePoint.position, moveSpeed Time.fixedDeltaTime) stops the movePoint from going too far if (Vector3.Distance(transform.position, movePoint.position) 0f) if (Mathf.Abs(moveHorizontal) 1f) makes it so we can check if 1f OR 1f without 1f 1f if (!Physics2D.OverlapCircle(movePoint.position new Vector3(moveHorizontal, 0f, 0f), 0.2f, whatStopsMovement)) Debug.Log( quot No collision quot ) movePoint.position new Vector3(moveHorizontal, 0f) else Debug.Log( quot Collision quot ) else if (Mathf.Abs(moveVertical) 1f) makes it so we can check if 1f OR 1f without 1f 1f if (!Physics2D.OverlapCircle(movePoint.position new Vector3(moveVertical, 0f, 0f), 0.4f, whatStopsMovement)) Debug.Log( quot No collision quot ) movePoint.position new Vector3(0f, moveVertical) else Debug.Log( quot Collision quot ) Any help at all is appreciated.


Unsticking game objects I have used void OnCollisionEnter(Collision collision) collision.gameObject.transform.parent gameObject.transform To stick two players together when they connect. Basically after they have collided the second game object is still stuck to the original object and i need that not to be the case. How do i make the game object not stuck when they come apart ?


Player losing alignment with tilemap after moving I'm using an isometric tilemap(2 1) and I can't figure out how to make grid based movement on it's surface. I managed to get a code working for the grid based movement, moving my character with 0.5 along the Y axis and 0.86 ( sqrt(3) 2 ) along the X axis since I imagine it should work as if they are diamonds with the side of 1 unit, but it doesn't align with the center of the next tile. Here is my movement code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Assertions.Must public class Movement MonoBehaviour Vector3 pos For movement float speed 5f Speed of movement public float x 0.86f public float y 0.5f void Start() pos transform.position Take the initial position void FixedUpdate() if (Input.GetKey(KeyCode.A) amp amp transform.position pos) Left pos Vector3.left pos new Vector3( 0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.D) amp amp transform.position pos) Right pos Vector3.right pos new Vector3(0.86f, 0.5f, 0) miscare in diagonala if (Input.GetKey(KeyCode.W) amp amp transform.position pos) Up pos Vector3.up pos new Vector3(0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.S) amp amp transform.position pos) Down pos Vector3.down pos new Vector3( 0.86f, 0.5f, 0) transform.position Vector3.MoveTowards(transform.position, pos, Time.fixedDeltaTime speed) Move there


Animation position leftover I am fairly new to unity and I have encountered this same problem previously. I have a gun with hands and I created an animation that simulates shot movements with properties transform.position and transform.rotation. Root motion is applied and motion curves are generated for the animation.The default state animation for that object has no properties assigned to it and as much as I understand from the animation controller window, the shot animation is completed before the transition to the default state is made. The problem is that on every 3 shots 0.001 is added to the X rotation Y and Z positions are losing some small values. I tried to prolong the animations exit time but the result is the same. I checked the key values and the motion curves, the first and last ones are the same. Why is this happening and how can I fix it ?


Additive Scene Loading Buttons not Becoming 'Active' I'm quite new to Unity but I'm making a game, and have created a simple Pause menu, when a key is pressed (escape), I just load a Pause scene, additively, and set that Pause scene to the active scene, however, only the buttons on the previous 'game' scene are interactive. The mouseEnter, exit etc aren't triggering on the pause menu buttons, despite the pause menu being overlayed on top of the 'game' scene the Pause scene being the active one and the 'game' scene buttons are still the interactive ones (i.e. register clicks, mouse overs etc). Obviously when I open the pause menu, I want the pause menu buttons to be the interactive ones (registering clicks, mouse over etc), not the previous 'game' scene buttons. The pause menu scene interacts perfectly when loaded additively with a scene that had no buttons. Many thanks.


Use a different target framework version in a unity c project, other than 4.6 I'm using a dll in my project which is built against a higher target framework (4.6.1 actually) I can't build or attach to Unity because of this. Visual Studio shows this error The primary reference "MQTTnet" could not be resolved because it was built against the ".NETFramework,Version v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version v4.6". The only option in player settings in Unity for API compatibility level is .NET 4.6 how can I change that to 4.6.1 in order to be able to build or attach to Unity?


Unity Create a custom editor for Vector2 I'm starting to dig into Unity's editor customization. What I'm looking for is a way to create custom line (or a point at least) which I could move around in SceneView and set a Vector2 value that way. I might create a child GameObject and then calculate the relative distance, but I'd like to know, if there is any way using the Editor instead of adding other useless GameObjects. Thanks in advance.


How to check if NPCs are on ground or not? I'm using Unity Engine. I see the common way to check if player is on ground is shooting a Raycast How to solve the ground check problem? How to check if grounded with rigidbody I have a simple scene with Unity's terrain for ground (Game Object 3D Object Terrain). Imagine you have a lot of NPCs (like GTA), is it possible to check a character on ground without Raycast? Do you have to run loop to ray cast check each NPC?


Maintaining facing direction at the end of a movement I want to make my 2D top down walking animation stop and revert to the idle animation while continuing to face in the same direction as the previous movement. For example, when I go up then stop, my character should continue to look up. If I go down, it should continue to look down. I use lastmoveX and lastmoveY floats for idle and for walking I use moveX and moveY floats. moveX and moveY change when I move with the joystick, but lastmoveX and lastmoveY do not change, and I don't know how to fix this. Here is my code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody2D myRB private Animator myAnim public Joystick joystick public MoveByTouch controller SerializeField private float speed Use this for initialization void Start () myRB GetComponent lt Rigidbody2D gt () myAnim GetComponent lt Animator gt () Update is called once per frame void Update () myRB.velocity new Vector2(joystick.Horizontal, joystick.Vertical) speed Time.deltaTime myAnim.SetFloat( quot moveX quot , myRB.velocity.x) myAnim.SetFloat( quot moveY quot , myRB.velocity.y) if(joystick.Horizontal 1 joystick.Horizontal 1 joystick.Vertical 1 joystick.Vertical 1) myAnim.SetFloat( quot lastMoveX quot , joystick.Horizontal) myAnim.SetFloat( quot lastMoveY quot , joystick.Vertical)


Will my huge sprites for a 2d game create performance issues? I'm new to Unity, and have been confused about this issue for a while. Some people say that for 2D games you don't need to worry about performance (I'm making the game for PC, not mobile) while others report bad performance with larger sized sprites I have a long scene with some large background sprites, measuring about 14552x3308 (weird resolution I know, would that also cause issues?) All methods of scaling it down and resizing in Unity lead to jagged edges (these are basically hills so I need them to be significantly bigger than the player character) I always keep the image size in the inspector similar to the resolution of the actual file, and set the filter mode to Point, so the jagged edges are not due to that, but only because of me scaling up a smaller file size to fit the scene. If I use the original sprites of 14552x3308, it's perfectly smooth (image size set to 8192 in inspector) but each file takes about 120mb in the profiler. All combined, my assets are showing a usage of 1.25 GB for this scene. How bad is this? Should I be trying to keep it under 1GB? I don't really know what the best practices are in this situation, so I don't know what to aim for. I'd ideally like to keep the sprites at this large size so that I don't have to redraw anything.


Material colours in unity not displaying correctly? Even though I've picked blue the color is displayed as something pinkish. All colors are like this


Unity3D Making heavy calculation on separate thread So, I've created a program with Kinect as its input. As you know, Kinect will send the data 30 frame per second. I have a model that will mimic Kinect's input motion, so on Update() I read the motion from Kinect. The problem is, on Update(), I've done a heavy computational algorithm. It makes the system lag and freezing. I've tried to do the calculation every 60 frames instead of each frame, but the system still got lag. void Update() ... GET DATA FROM KINECT frame new SkeletonRecorded() frame.root.rotation skeletons kinect2SensorID, playerID .root.rotation ... frame.rightShoulder.position skeletons kinect2SensorID, playerID .rightShoulder.position frames.Add(frame) if (frames.Count gt 60) CALLING THE CALCULATION METHOD (Here is the heavy part begin) comparatorClass.GetSkeletonData(frames) frames.Clear() The above code is just small parts of the Update() method (I cut it short for convenience). So, how should I call the GetSkeletonData() method without making the interface lag?


I try to recreate a plasma gun from halo into my fps game this is my code public class WeaponTest MonoBehaviour public float weaponHeat public float weaponOverHeat 100f public bool weaponIsOverHeat Start is called before the first frame update void Start() weaponHeat at the start was 0 weaponHeat 0 Update is called once per frame void Update() if (Input.GetButton( quot Fire1 quot ) amp amp !weaponIsOverHeat) if (weaponHeat lt weaponOverHeat) Weapon Shoot() weaponHeat IsHeating() float IsHeating() weaponHeat Random.Range(5f, 10f) return weaponHeat void Weapon Shoot() RaycastHit hit if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range)) code for damaging the enemy the shoot method was function exactly like what is want but I need the cooldown method I already try a few them but it not work exactly like I want. the I idea was went the left mouse was click the weapon heat will increase and when the left mouse was not been click the weapon heat will decrease until it reach 0. I hope you can help me solve this problem


How do you "branch" a Unity project How do you branch a unity project? Suppose you have Game Project A, and say there is variant A' that requires a large convoluted plugin. But the idea is also that you want to keep developing this without the plugin getting in the way, for the other variants say A and A'' that don't require it.


Why is my sphere jumping? I got a sphere that moves with an angular velocity of 2000 in the X axis, I need that sphere moves on 130 platforms, all those platforms have 0.0182175 in the Y axis. The problem is that when I play, the sphere starts normally but as it advances starts make some jumps, first shorts but then more large, and it is as if the platforms did not have the same value in the Y axis. Can someone help me, please? I've put some images. Very thanks Hey people!! I've uploaded a video to show you clearly the problem. Here's the link Platforms, sphere and sphere script Sorry for my english by the way.


How to update UI after changing text in a view After applying a text change to a scrolling view, how do you get the new height of the text, resize other UI elements around the changed text length, etc? Many have posted this question. Some have noted that the rect size doesn't change or that they have to wait multiple frames to then react to the UI updates.


How do I tell if an object is currently colliding with another object? I can't figure out how to tell if a GameObject is currently colliding with another in Unity. I've looked online and can't find any tutorials or answers that work. Also, what's the difference between a Collision and a Collider w.r.t. Unity? My dilemma I have a third person controller set up and want it to wall jump. I already have an isGrounded function, I just need to test if I'm hitting anything other than the floor. Otherwise I want it to wall jump backwards. I've already tried if (this.OnCollisionEnter) ... if (Collider.OnCollisionEnter) ... But it did not work. I now tried function OnCollisionStay() Debug.Log("Collision") I checked my logs, console and still can't find anything.


How should I reload a ball? I am making an angry bird type 2d game using Unity and C . After I throw the ball from catapult, I have no idea on reloading the ball. Then I use SceneAsync to reload the ball but it is the worst thing I've ever made since I can't make the other sprite objects to continue their movents after the ball is thrown. So what code should I use to reload the balls after throwing?


How do C and UnityScript differ in Unity development? Other than the obvious language differences, how do UnityScript and C differ when developing games in Unity3D? Is there a noticable performance difference? Is the UnityScript code packaged as is? If yes, does this help the game's moddability? Is it possible to use libraries developed for one language while developing in the other one? Can the two languages be mixed in the same Unity project coding some parts in C and others in UnityScript?


Using enums for detecting object collisions As far as I know, I can detect what objects the player is colliding with is by the following code private void OnCollisionEnter2D(Collision2D collision) if(collision.collider.name.Equals("")) But I have heard that I can use enums instead to reduce computations. Could anyone explain to me using examples?


UI looks different between editor and in game I am very confused about Unity's UI system. This is how my inventory menu looks in the Editor And this is the view in game Settings Can someone please explain why this happens?


Can Cloud Functions be used for a multiplayer game server? I'm building a turn based online multiplayer game with Unity for both desktop and mobile. Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc. I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda. However, at first glance it doesn't seem to me like that would work for my game because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime or can I? For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games. Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them. I'd image that would work, but that seems rather overkill with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses. Is there something I am missing? A coding practice that would make serverless code feasible for a cross platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.


Choosing random array indexes in Unity C I want to change a string by randomly choosing an index in an array, using the random.range command in unity. Bare in mind that I'm using strings here, not floats or integers. Here is a code example(not the real thing. I'm just coming up with this by example, but it still has the same meaning. I may make a few typo errors as a result) public string ChangingString ("") public string ExampleArray new string 2 void Start () ExampleArray 0 ("String1") ExampleArray 1 ("String2") void OnGUI () if(GUI.Button(new Rect(10,10,100,24), "Randomize text")) ChangingString (code to choose random string using the ExampleArray) GUI.Label(new Rect(10,30,100,20), ChangingString) EXTRA NOTE I'M NEW TO USING ARRAYS.


Force Reload VS soution Explorer when adding new c Script via Unity3d? When I create C script (Create gt C Script) via Unity3d or delete it from Unity3d Visual Studio shows me the warning window. it's annoying. Is there any way to force "ReloadAll" in solution Explorer without the window?


How to make dynamic DOF from mouse position in Unity 5? I found a video a while ago for how to make a dynamic DOF in unity. It fires rays from the camera and positions an empty at the location that the ray first hit. How can I change this so that it doesn't fire rays from my camera but rather from my mouse position, and then positions the empty from there? Code public Transform origin Raycast origin public GameObject target public CameraMovement cameraMovement void Start () void Update () Ray ray new Ray(origin.transform.position, origin.transform.forward) RaycastHit hit new RaycastHit() if(Physics.Raycast(ray, out hit, Mathf.Infinity)) Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.cyan) target.transform.position hit.point else Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.red)