Circular draggable UI element in Unity canvas I am trying to implement my own runtime color picker that's easy to use for touch interfaces. I want the hue slider to be a ring, along these lines, except the whole ring texture would rotate when dragged. I have scavenged enough code to get a raw image object rotating when dragged in a UI canvas in the manner I'm looking for private float baseAngle private Vector2 pos public void OnBeginDrag(PointerEventData eventData) pos transform.position pos eventData.pressPosition pos baseAngle Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle Mathf.Atan2(transform.right.y, transform.right.x) Mathf.Rad2Deg public void OnDrag(PointerEventData eventData) pos transform.position pos eventData.position pos float ang Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle transform.rotation Quaternion.AngleAxis(ang, Vector3.forward) Since it doesn't use colliders, how can I limit the draggable region to a circle within the square bounds of the texture? Even better, also limit it to a ring rather than a whole circle. Will I have to implement my own check based on some pure math or is there a built in way? thanks!


Positional noise changes in Unity Editor vs compiled I have a surface shader that adds a bit of positional noise, using the following code float2 uv main IN.uv MainTex float2( tex2D( PosNoise, IN.uv MainTex).r 0.5, tex2D( PosNoise, IN.uv MainTex).r 0.5 ) float2( Width, Height) MovementOffset o.Albedo tex2D( MainTex, uv main) MovementOffset is a float, the Width and Height are the size of the map in world coordinates. PosNoise is a texture that is the same for both versions. The problem I'm seeing is that the effective noise changes between how the image looks in the Unity Editor vs when it is compiled. The effect is such that I need to multiply the MovementOffset by a factor of 2 3 to have the same effect in the compiled version. Unity Compiled I don't understand what could be causing this, and am having some real difficulties figuring it out. Any suggestions on where to look? Thanks!


Texture tearing with UV texture atlas mapping The following code maps the texture from a texture atlas to a UV. The problem is I'm having texture tearing issues. Does anyone know how to overcome this problem and have any suggestions? Here is the code I have, all images are point filtered and no mipmapping is used. for (int i 0 i lt mesh.uv.Length i ) UVs.Add(GetUVTextureFromAtlas(mesh.uv i .x, mesh.uv i .y, voxel, 0)) ... Vector2 GetUVTextureFromAtlas(float x, float y, ushort voxel, Facing side) Rect rect GetVoxelTextureRect(voxel, side) float xout UVLerp(rect.x, rect.x rect.width, x) float yout UVLerp(rect.y, rect.y rect.height, y) return new Vector2(xout, yout) float UVLerp(float from, float to, float t) float difference to from return from (difference t)


Dragging a Rigidbody2D without passing through obstacles I have this body of code written for an object that needs to be an obstacle and another object that is draggable. I have colliders on both and a kinematic rigidbody on the draggable object, but the obstacle is still allowing the dragged object to be dragged through it. This is all 2d. I'm not sure what I'm doing wrong. The part that I'm confused on is this when you just add a collider to the obstacle sprite and a collider and rigidbody (all 2d) to the draggable sprite, if I don't add the script above, then the draggable sprite falls due to gravity on top of the obstacle and stop there, it doesn't fall through the obstacle sprite. However when I add the above script which has the OnMouseDrag function, and I move the draggable sprite around because now I can, it falls through the sprite. With no script the obstacle acts like an obstacle. With this script the it does not. using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class Block MonoBehaviour public GameObject Four Object1 public GameObject clone Four Object1 private Vector3 screenPoint private Vector3 offset private Rigidbody2D rb2d private Vector3 screenPoint private Vector3 offset private Vector3 cursorPosition public void Start() rb2d GetComponent lt Rigidbody2D gt () GetComponent lt Rigidbody2D gt ().isKinematic true public void OnMouseDown() screenPoint Camera.main.WorldToScreenPoint(Four Object1.transform.position) offset Four Object1.transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)) public void OnMouseDrag() Vector3 cursorScreenPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) cursorPosition Camera.main.ScreenToWorldPoint(cursorScreenPoint) offset transform.position cursorPosition public void FixedUpdate() rb2d.MovePosition(cursorPosition) Debug.Log("Update!")


Box Collider center relative to GameObject I'm trying to get the distance from the BoxCollider center of a gameobject to the bottom of that same BoxCollider. Note that the center of the collider is slighty modified. So far, I have float halfHeightCollider (bounds.size.y 2) I tried the following to take care of the slight modification float halfHeightCollider bounds.center.y (bounds.size.y 2) But seems like bounds.center give me the position of the center of the BoxCollider in the world, not relative to the gameobject, like in the inspector That value is the one I want. How can I get it?


Unity Check if sprite is within range around player I need to know if a sprite is within range (circle or square doesn't matter) around the player. If the sprite is, let's say, 100 blocks away from the player, I will disable it. This wouldn't be too much of an issue, just compare positions and you're done. However, my game is a tile based game and I want the world to be as big as possible, which will result in millions of sprites. I could also add a overlapcicle2D, but the problem is this these objects can't have a collider, since they could be walkable. So how can I check if the millions of sprites are in range of the player, without lowering performance? Alternatively, I could add occlusion culling. But how do you do this with sprites?


Limit a scrollbar's OnValueChanged to full step intervals only So I have done some research on the matter but I can't find anything. I created a UI scrollbar and asigned 10 steps to it.Then I noticed that the values of the scrollbar does not change in reference of the handle's steps but in reference of the pointer's position(like a slider).That seriously slows down the performance since it has a lot more to process "onValueChanged" and it is unnecessary for what I am trying to achieve. The values of the steps should go step 1 0.1(1),step 2 0.2(2) etc.I need to get these values and nothing in between or the step that the handle is currently on. How can I do that ?


Implicit conversion error why is this code trying to convert a 'World' to an 'int'? using System.Collections using System.Collections.Generic using UnityEngine public class World Tile , tiles int width int height public World (int width 200, int height 200) this.width width this.height height tiles new Tile width, height for (int x 0 x lt width x ) for (int y 0 y lt height y ) tiles x, y new Tile this, x, y public Tile GetTileAt(int x, int y) if (x gt width x lt 0 y gt height y lt 0) Debug.LogError ("Tile (" x ", " y ") is out of range") return null return tiles x, y anyone see anything wrong with this code because on line 18 of my code i get this error "cannot implicitly convert type 'World' to 'int' and i don't know what is going wrong.


Textures in build duplicated, despite they're packed into atlases I have a simple SpriteAtlas quot UIAtlas quot which is located in the Resources folder. It points to a folder quot UIAtlas quot which contains my menu textures. All of my batching is working perfectly, everything is being batched, because of the atlas. When I build an iOS version, in the Editor.log I can see this Build Report Uncompressed usage by category Textures 299.5 mb (30 ) Meshes 0.0kb (0 ) ... Used Assets and files from the Resources folder, sorted by uncompressed size 16.0 mb 1.6 Built in Texture2D sactx 2048x2048 Uncompressed UIAtlas 312aba98 ... 345.3 kb 0.1 Assets Resources UIAtlas medal.png ... more entries like this ... Please notice that this texture (medal.png), along with the other textures belongs to this atlas, which is already included in the build executable. I feel this is wrong. If I pack things, they should be packed into that texture and only that 2048x2048 texture should be in the build, right? What's wrong here?


Can I clip a collection of geometry to render only inside a particular worldspace volume? I am making a VR app in Unity. I have a giant map that I want to display on a virtual table. The map is too large to fit on the table, and I cannot change its size. (It is a third party asset, and does not easily have that capability.) How can I tell the camera not to render the parts of the map that fall off of the table? Perhaps something along the lines of Camera.DoNotRender(new Vector3(100, 0, 0)) I have been looking into using some MonoBehaviour messages such as OnPreRender, OnRenderObject, etc. But I do not know which one can help me, if any. Ideally, the pixels behind the non rendered pixels should be rendered, but that is not my priority. The map is made up of 100s of little renderers How can I have my Camera not render specific world space pixels?


Unable to rotate a 2D object, wanting to move it like a ball wheel I'm using Unity2D. I have a very basic 2D space with a platform, a ball and 2D physics. Physics is being applied and ball sits on top of the platform. However, it will not spin. Below is the script attached to the ball using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class Circle MonoBehaviour private Vector3 screenPoint private Vector3 offset private float speed 10f public Rigidbody rb void Start() rb GetComponent lt Rigidbody gt () void FixedUpdate() float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.maxAngularVelocity 999 rb.AddTorque(movement speed) void OnMouseDown() offset gameObject.transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)) void OnMouseDrag() Vector3 curScreenPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) Vector3 curPosition Camera.main.ScreenToWorldPoint(curScreenPoint) offset transform.position curPosition The script is attached to the ball, I know this because I'm able to drag it (see OnMouseDown). I have also tried with other objects such as a rounded corner square, but I just can't get any spin or torque to be applied. Below is a screenshot of the inspector on the element. Circle.cs (the script) is the above pasted script. Any help appreciated.


Black screen when building apk Unity Alright, I have a bit of a confession to make I accidentally posted this question in the wrong place Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post. I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game over UI appears, and I can use it as normal. The shop menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point). Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build.


Resolving this kind of situation in my platformer (movement on slope with roof) I'm building a simple 2D character controller based on raycasts. At this moment I'm trying to finish the player ground interaction. For the ground I will be using edge colliders and no tiling information. I have most code working but there's something I don't really know how to fix. Here is an screenshot explaining the situation As you can see, Player (purple rectangle) is on a slope. When player wants to move right the new x and y coords are calculated to set the player feet again on the slope (Blue rectangle). But, after this response has been applied to the player to make it out of the slope, It is pushed through the roof and some part of it is sticking out the edge collider (red box). How do you handle this situation? On the other hand, If there's any way to accomplish this in a simpler fashion I'm all ears ). Cheers.


Unity Shader Material Only Activates when Clicked I am currently programmatically settings some shader textures, related to a Mesh Filter. The Mesh Filter is using a standard shader, and I am merely generating and setting the Bump and Height maps, via code. Sphere.materials 0 .mainTexture biome Sphere.GetComponent lt MeshRenderer gt ().materials 0 .SetTexture (" BumpMap", bump) Sphere.GetComponent lt MeshRenderer gt ().materials 0 .SetTexture (" ParallaxMap", heightTexture) This is fine. The issue is that the shader only seems to activate itself once it is clicked in the inspector. Is there some sort of Activate() function I need to call in order to apply the shader effects to the Mesh? Notice in the example (this is running in Play mode), that the shader only activates once I click the expand button on the Shader in the inspector. What is going on here?


NPC daily routines and scene loading I'm making a basic survival RPG in Unity 3d. I'm separating my world into different scenes to save memory but I'm not sure how I'm going to program NPC daily routines. For example, if the player arrives in a town scene in the morning, how do I ensure that the NPCs are working in appropriate places with the appropriate equipment? I suppose I could hard code it so NPCs are in certain places at certain times. Therefore, if the player arrives at 9 00am then all the NPCs will move to their 9 00am places. I'm just wondering if there is a better way of doing it than that. I can see myself needing to write a lot of code to cover all the possibilities so it could get really messy. I was hoping there was some way I could have the NPC routines continue seamlessly in the background but this would be taxing on memory if it's even possible. Any ideas pointers on this issue would be appreciated.


Realistically drivable car I want my car to be realistically drivable (like in real life...) Unfortunately all I did so far is Rotate the whole vehicle using A and D and AddForce in forward backward direction using W and S (which didn't prevent it from moving sideways and yes, I am using Rigidbody) I'm assuming I'd have to let front wheels rotate independently from the rest of the car, but how do I use them to move the car? And how do I force the car to move only in the direction of the wheels while still making drifting at high speeds possible?


Can I save a score as highscore, if it's a float? So I have this infinite runner type of game, subway surfers style. I chose a method where the player doesn't move, and instead the obstacles move towards him. My score is a float and it increases as time passes. However, I'm unable to figure out how can you save this as a highscore. I tried a few methods but most of them were for int so it didn't work out. Here is what I have for the score counting. It's currently missing the save score part completely. public class GameManagerC MonoBehaviour float score 0 public float scoreMulti 5 void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot ) EDIT Many of you asked how I tried to implement the code I've found so here it is public float score public float highScore void Start() score PlayerPrefs.GetFloat( quot score quot ) highScore PlayerPrefs.GetFloat( quot highScore quot ) if (score gt highScore) highScore score StartGame() Update is called once per frame void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot )


What to do to set gravity in unity What to do to set gravity in unity? I'm working on a game called "OXYGEN", and for the space scene. I want to set the gravity of the Controller to 0.38, or Mar's gravity.


UnityEditor related classes can not be referenced. Why? I have two classes. Both of them are placed in the editor interface field folder. using System using UnityEngine namespace editor.interface field public class RequiredInterfaceAttribute PropertyAttribute public readonly Type type public RequiredInterfaceAttribute(Type type) this.type type using UnityEditor using UnityEngine namespace editor.interface field CustomPropertyDrawer(typeof(RequiredInterfaceAttribute)) public class RequireInterfaceDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) if(property.propertyType SerializedPropertyType.ObjectReference) var requiredAttribute this.attribute as RequiredInterfaceAttribute EditorGUI.BeginProperty(position, label, property) property.objectReferenceValue EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true) EditorGUI.EndProperty() else var previousColor GUI.color GUI.color Color.red EditorGUI.LabelField(position, label, new GUIContent( quot Property is not a reference type quot )) GUI.color previousColor I have another class. using editor.interface field using UnityEngine namespace interface user.implementations public interface IInterface public class InterfaceUser MonoBehaviour SerializeField RequiredInterface(typeof(IInterface)) UnityEngine.Object interfaceImplementation The RequiredInterface(typeof(IInterface)) line throws the following error The type or namespace name 'RequiredInterfaceAttribute' could not be found (are you missing a using directive or an assembly reference?) Assembly CSharp csharp(CS0246) I can not understand why does not Unity see the RequiredInterfaceAttribute class and how could I make it see it.


Make enemy follow player intelligently I was trying to make a script to make my enemy follow my player intelligently (but not too much) and I want to know if there was a better way to do it (of course there is but I wanted to find a way myself) Here is what I did I wanted my enemy to detect the player when he approach a certain distance from him. I have a varibale to determine what distance the nemy have to back up (when player is too close) and when it has to follow the player (player too far). Now, I didn't wanted the enemy to just forgot there is an intruder when the player goes around a corner and they can't see him. When the enemy sees the player directly (raycast), they rotate toward him and start following him directly by normalizing the difference of their 2 position. Now is the tricky part i'm not sure about. My player has a list that keeps the 1000 last positions of my player and that update every 0.01 second to add the lastest position and remove the oldest. If the enemy can't see the player directly (!raycast) he goes through all the positions in the list by checking for every Vector3 1 is there something between the enemy and this position ? 2 is there something between this position and the player ? Then it add up the distance between the enemy and the point and the distance between the point and the player and checks 3 is the lenght of the path by going at this point shorter than the last shortest path ? if it's smaller, it's assigne to the best point. If it detected a point that matches these conditions, it goes at it and if it doesn't see the player, it continues checking for new points. If no point matches the condition, he just stop following the player (the enemy lost him). All this works with raycasting to check positions, presence of objects between enemy, player and points and path to go.


How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick? So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick? CODE public float moveSpeed Rigidbody2D myBody protected Joystick joystick void Start() myBody GetComponent lt Rigidbody2D gt () joystick FindObjectOfType lt Joystick gt () Update is called once per frame void Update() myBody.velocity new Vector2( joystick.Horizontal moveSpeed, joystick.Vertical moveSpeed )


How to retrieve the coordinates of an animated object? On Unity, I created a script in C to animate a cube. I am trying to create a script in C which, once the animated object and in support of a key of the keyboard (for example F) returns to me the coordinates of the object at the moment when I pressed F Can you give me this script? Thank you for your help


How to keep player rotated toward a sphere when within a certain radius? In my game the player can fly to multiple spheres, I want to make it so that when the player gets within a certain distance of the sphere, (maybe using a bigger is trigger sphere collider around it?) their feet will stay pointing towards the sphere until they leave the radius, (maybe using a quaternion?) then if they get within the radius of a different sphere, their feet will point towards that too. How can I make this work? I don't know too much about c , so any example code would help a lot too!


How people get their game ideas? One thing that always stop me when I want to start making a game is having no idea what to do. How do people get ideas for their game ? I mean realistic ideas for people who are alone with the minimum ressources (no money for assets, blender and unity). I will never stop being impressed by all new concept, mecanics or crazy ideas of game indie developpers come up with, like making game out of random everyday objects. I wish I was able to do that. Do developpers get their inspiration by looking at other games and trying to mix them or change the concept ? Do they look outside trying to come up with what they wish was a game ? Or do they simply walk around and try to imagine a game with whatever they see or reallife situations or concept ?


Touch a specific area on the screen in Unity 5 I am building a Roulette game in Unity 5. I want to place bets on a Roulette table when I touch specific areas on the screen with mouse(PC) and touch(mobile). For example when i touch Number 1 on the roulette table a bet should be placed on that number. I tried using box collider iwth trigger but I think thats for only colliders. Screenshot attached


UNET spawn dynamically generated object unity Spawning works when all clients are connected, but if a client connects after I spawn all my prefabs there are errors. I spawn the object before changing its Rigidbody's velocity, which seems to cause the problem. I spawn objects, change them, then the other client joins, and the errors come. these are the errors Failed to spawn server object, assetId 953c1c6ecbb84304280d1334ef5dae0b netId 26 I also make changes to variables on other scripts. All objects have network identities, network transforms, and are spawnable prefabs.


Unity3d webplayer failed to download data file When testing my game web builds on localhost, I get the error "Failed to download data file". The game data file is correctly placed, and the page loads fine, it just wont download the plugin, or prompt me to do so. I tried the following things Add MIME Types to IIS 7.5 Open IIS Manager Double click "MIME Types" in the IIS section. Click Add on the right side "Actions" menu. File name extension .unity3d MIME type application unity3d click ok Restart the server (right side "Actions" menu) That didn't work for me specifically because it turned out I was using IIS Express, so I did the following If Windows 7, browse to 'C Users Documents IISExpress config ' and open the file ApplicationHost.config. Search for 'staticContent' and add the following before the closing tag However, again, it didn't work..


How do I transform from local points to world when using a scroll view? I'm using a scroll view to store my game character icons (basically an RPG). The movement system for the characters is tile based, but in game hazards could be located anywhere. So I need to detect if a certain tile will interset with a hazard if a character moves into it. To do this I can calculate the corners of the tile using the co ordinate system of the scroll view. I thought I could turn these into world co ordinates then query to see if the collider attached to the hazard contains the point (the collider could be rotated so I can't just do the math myself). When I try to convert the co ordinates into world co ordinates though the numbers I get just don't match up. For example, the lower left corner of the tile a character will move into is at ( 1250.0, 938.0). If I convert that to world co ordinates I get ( 28.7, 49.8). The actual position for the hazard I'm testing against has a world position of ( 8.0, 1.5, 93.4) though and the test tile should be right on top of it. I'm using code like this to try to get the world co ordinates Vector2 charPosition5 travellingCharacter.owningGameObject.GetComponent lt RectTransform gt ().transform.TransformPoint(travellingCharacter.GetComponent lt RectTransform gt ().anchorMax) Vector2 charPosition6 travellingCharacter.GetComponent lt RectTransform gt ().transform.TransformPoint(travellingCharacter.owningGameObject.GetComponent lt RectTransform gt ().anchorMin) Can someone tell me what values I should be feeding in or what other function I should be using please?


How to create inline glow shader for 2d polygon in CG using Unity Shader Lab? So here is what I am trying to do. Given irregular polygon (on the left) I would like to be able to create a shader that would resemble Photoshop inline glow effect with opaque fill (on the right). Creating similar effect for 3d object I can achieve with Fresnel function. However, I am not able to do it for a flat surface of any given irregular 2d polygon. EDIT I am planning on using Voronoi method to generate polygons and then connecting individual polygons to territory shapes based on which player owns them. Which, then will have border material applied. What I need is effectively border (or territory) shader. That means shader has to work for more irregular shapes, like the one below.


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


How to make balls (water, or fluid) through pipe I'm working on a project and get stuck for days. I want to make balls going through the pipe like this game You can watch this Youtube video for more detail. How can i replicate this game machenis?


Night cycle object not going smootly when object instantiated Hello so I'm adding night cycle to my game it's going smoothly for object except the instantiated one as you can see that is a different color on it. so here the script for night cycle public GameObject ca1, ca2, ca3, ca4, ca5, ca6 void Update() if ( GameManager.instance.isStarted) timer Time.deltaTime if (timer gt maxTime) GenerateObstacle() if ( GameManager.instance.score gt 450) if ( GameManager.instance.score 2 0) GenerateBuwungObstacle() if ( GameManager.instance.score gt 3000) if ( GameManager.instance.score 5 0) GeneratedMeteorObs() timer 0 if ( GameManager.instance.score 200 0 amp amp activeFade null amp amp activeFadeObjectClouds null) fadeToBlack !fadeToBlack Color colorCactusObs fadeToBlack ? Color.white Color.gray activeFadeObjectCactus StartCoroutine(ObjectCactusFadeTo(colorCactusObs)) for generating the cactus public void GenerateObstacle() choosedObstacle Random.Range(0, Obstacles.Length) GameObject obstacle Instantiate(Obstacles choosedObstacle ) IEnumerator ObjectCactusFadeTo(Color destination) Color start1 ca1.GetComponent lt SpriteRenderer gt ().color Color start2 ca1.GetComponent lt SpriteRenderer gt ().color Color start3 ca3.GetComponent lt SpriteRenderer gt ().color Color start4 ca4.GetComponent lt SpriteRenderer gt ().color Color start5 ca5.GetComponent lt SpriteRenderer gt ().color Color start6 ca6.GetComponent lt SpriteRenderer gt ().color for (float t 0 t lt 1f t (Time.deltaTime fadeSpeed) 2) ca1.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start1, destination, t) ca2.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start2, destination, t) ca3.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start3, destination, t) ca4.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start4, destination, t) ca5.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start5, destination, t) ca6.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start6, destination, t) yield return null ca1.GetComponent lt SpriteRenderer gt ().color destination ca2.GetComponent lt SpriteRenderer gt ().color destination ca3.GetComponent lt SpriteRenderer gt ().color destination ca4.GetComponent lt SpriteRenderer gt ().color destination ca5.GetComponent lt SpriteRenderer gt ().color destination ca6.GetComponent lt SpriteRenderer gt ().color destination activeFadeObjectCactus null I already try with for loop in the object cactus fade but still not smooth


Allow code after a bugged line to continue without use of try and catch My problem is with C in unity, but I think the problem can be applied to all coding languages. For example I have a start function event that may initiate many things. Some lines of code may issue a bug but I want to allow new lines of code run after that without having to encapsulate every line of code with try and catch. Is there any common solution for this that I'm missing?


Day and Night mode according to user's real local time How do I make it so the texture of my plane is a black sky when it's night according to player's local time (say from 10 PM to 5 AM it's going to be black, and from 6 AM to 9 AM it's going to be a blue sky)? Blue sky texture name is "bluesky" Black sky texture name is "blacksky" Thanks.


Having trouble setting a game object as a child of another. What is wrong here? So I'm trying to raycast on mouse click if it hits any thing make that object a child of the sender (in this case the parent). Below is my code... public class PhysGun MonoBehaviour private GameObject Player void Start () Player GameObject.Find("Player") Update is called once per frame void Update () Vector3 fwd transform.TransformDirection(Vector3.forward) if (Input.GetMouseButton(0) amp amp Physics.Raycast(transform.position, fwd, 10)) this.transform.parent Player.transform transform.SetParent(Player.transform) Debug.Log("There is something in front of the object!") The script is attached to a child of the player and I will eventually attatch it to a motion control (Vive). What am I doing wrong exactly? I've tried multiple ways to do this and none of them work (or present any errors). Also to clarify the issue it's not parenting the game object hit by the ray cast to the Player like I want it to.


How to "undraw" a SetPosition on LineRenderer? I'm animating the SetPosition on a line renderer to show a laser site quickly quot spin up quot so the user sees the laser head outward. I'd like to do the reverse and when a user switches off the laser sight and it also quickly retracts. I have the spin up working good, but I can't figure out how to quot undraw quot the line when a user toggles the sight off. Once its quot undrawn quot a user can just spin it up again when they turn it back on. Here is the code (ignore the weapons checks) using System.Collections using System.Collections.Generic using UnityEngine public class WeaponAimAlignment MonoBehaviour weapon assignments SerializeField private Transform rocketBarrel laser sight assignments SerializeField private float aimOnSpeed SerializeField private Transform aimLaser SerializeField private LineRenderer lineRend private bool aimOn false private float counter private float dist void start() lineRend.enabled false void FixedUpdate() if (Input.GetKeyDown(KeyCode.B) amp amp aimOn false) aimOn true lineRend.enabled true lineRend.SetPosition(0, aimLaser.transform.position) else if (Input.GetKeyDown(KeyCode.B) amp amp aimOn true) lineRend.enabled false aimOn false Ray rayOrigin Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hitInfo if (Physics.Raycast(rayOrigin, out hitInfo)) if (hitInfo.collider ! null) Vector3 direction hitInfo.point rocketBarrel.position machineGunBarrel.rotation Quaternion.LookRotation(direction) grenadeBarrel.rotation Quaternion.LookRotation(direction) rocketBarrel.rotation Quaternion.LookRotation(direction) if (aimOn true) dist Vector3.Distance(aimLaser.transform.position, hitInfo.point) if (counter lt dist) counter .1f aimOnSpeed float x Mathf.Lerp(0, dist, counter) Vector3 pointA aimLaser.transform.position Vector3 pointB hitInfo.point Vector3 pointAlongLine x Vector3.Normalize(pointB pointA) pointA lineRend.SetPosition(1, pointAlongLine)


Making read from and write to databases I want to make a few simple databases for a sports game using Unity2D(C ). One is a read only google sheet where it takes the players from the pool and adds them into the game at the start. Another one is a read and write database where all 30 team's players will be saved as well as current stats( a lot of numbers), I don't know if i should make this online or local saves. I want to keep the cost at a minimal. Generally new to making databases, can someone point me in the right direction?


Double vision with Google Cardboard in Unity I am working on a VR app. I have a terrain and some cube placed in the terrain.Even I have added the Reticle to point at the cube and display some message when the user gaze at the cube. I have set the distortion to "None". The problem I am facing here is,when I run the app the cubes and the pointer(reticle) is seeing as double in the scene.What will be the reason for it.Can anybody help me out please.


Spatial Jitter problem in large unity project I have a very large environment where i am getting very weird view of objects as picture given below As you can see there are black lines spot, maybe the vertex lit problem. Currently I am using Standard specular shader. Remember this problem is only occuring at the end of the project (away from origin like position 17000, 0, 144) As a workaround i tried to change my shader to Unlit and i found this shader Shader "Unlit UnlitAlphaWithFade" Properties Color ("Color Tint", Color) (1,1,1,1) MainTex ("Base (RGB) Alpha (A)", 2D) "white" Category Lighting Off ZWrite Off ZWrite On uncomment if you have problems like the sprite disappear in some rotations. Cull back Blend SrcAlpha OneMinusSrcAlpha AlphaTest Greater 0.001 uncomment if you have problems like the sprites or 3d text have white quads instead of alpha pixels. Tags Queue Transparent SubShader Pass SetTexture MainTex ConstantColor Color Combine Texture constant This shader has almost solve the problem but i have to tweak and set colour of each object as be default it is not according to my expectation.


Unity Physics collision metrix doesn't work on ParticleCollisions I have this Physics collision metrix(1). I have Player layer on the ship and PlayerShells on Particles whitch's my shooting. The problem When I shoot, OnParticleCollision on my shells collides with player, but as you can see on the picture it shouldn't happen. Proofing my theory, I testet it (2) and (3) screenshoots My quot collision quot code private void OnParticleCollision(GameObject other) SetDamage(other.GetComponent lt ISetDamage gt ()) Creating hit effect mainParticles.GetCollisionEvents(other, collEvent) Vector3 pos collEvent 0 .intersection hit posotion Quaternion newRot Quaternion.Euler(transform.rotation.x, transform.rotation.y, transform.rotation.z) Tryed to rotate effect like opposite from bullet, but it doesn't work for now switch (other.GetComponent lt Stats gt ().GetMatter) case Matter.Steel Instantiate( hitSteel, pos, newRot) break case Matter.Wood Instantiate( hitWood, pos, newRot) break case Matter.Flesh Instantiate( hitFlesh, pos, newRot) break case Matter.Dirt Instantiate( hitDirt, pos, newRot) break case Matter.Stone Instantiate( hitStone, pos, newRot) break What am I doing wrong?? (


Sometimes can't use the rendered mesh as a collider in Unity? Most of the times I can use the Mesh Filter's mesh as collider in Mesh Collider But sometimes there is just nothing. No collider. Why? I used this free asset https assetstore.unity.com packages 3d environments fantasy green forest 22762


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


How can I change the root namespace for scripts in Unity? How can I change the root namespace for scripts in Unity? I went to Edit Project Settings... Editor Root namespace and put there the gameplay value. I checked that the Assembly CSharp.csproj has the lt RootNamespace gt gameplay lt RootNamespace gt Now I go to VS Code editor, create a class and the class still uses a wrong namespace. What may I be missing here?


How to change AddForce code to MovePosition or SetVelocity? Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1f) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized targetPosition (camF vec.y camR vec.x) MoveSpeed Vector2 targetVelocity (targetPosition transform.position) Time.deltaTime rb.AddForce(targetPosition rb.velocity, ForceMode.VelocityChange) My problem is my character doesn't affects by the gravity when i changed my code from transform.position to rb.AddForce. I searched online and even asked here how to calculate gravity and add it to my character, nobody knew, so i think if i can change this code to rb.MovePosition or rb.SetVelocity maybe it does affects by the gravity?


How do I use this Perlin Noise texture to change the mesh? Using the Unity docs page on Perlin noise, I made this script Width and height of the texture in pixels. public int pixWidth public int pixHeight The origin of the sampled area in the plane. public float xOrg public float yOrg The number of cycles of the basic noise pattern that are repeated over the width and height of the texture. public float scale 1.0F private Texture2D noiseTex private Color pix private Renderer rend void Start() rend GetComponent lt Renderer gt () scale Random.Range(15, 20) xOrg Random.Range(0, 20) yOrg Random.Range(0, 20) Set up the texture and a Color array to hold pixels during processing. noiseTex new Texture2D(pixWidth, pixHeight) pix new Color noiseTex.width noiseTex.height rend.material.mainTexture noiseTex void CalcNoise() For each pixel in the texture... float y 0.0F while (y lt noiseTex.height) float x 0.0F while (x lt noiseTex.width) float xCoord xOrg x noiseTex.width scale float yCoord yOrg y noiseTex.height scale float sample Mathf.PerlinNoise(xCoord, yCoord) pix (int)y noiseTex.width (int)x new Color(sample, sample, sample) x y Copy the pixel data to the texture and load it into the GPU. noiseTex.SetPixels(pix) noiseTex.Apply() void Update() CalcNoise() The only difference between this code and the Unity docs example is that I added some randomness to the size and origin points of the texture. I attached the script to a plane, and now when I run the game, the plane has a random noise texture on it. Now I want the texture to give height to the mesh, so it will look like a terrain. How do I do this?


How to make rigid body move smoothly on uneven platform? Right now I'm using Rigidbody2d for the game character along with polygon collider 2D(2d platform game). I'm beginner hope I'm using correct components. And transform to move character from left to right. Character.transform.Translate(Vector2.right speed Time.deltaTime) And upward(jump). Character.transform.Translate(Vector2.up speed Time.deltaTime) When the game character moves on slopes there's lot of friction and bounciness and rotation and its worse when jumping from slopes.


Smoothly switch between 2 pairs of oscillating colors I have a simple script that changes the emission color based on a bool. The first color is its idle color, which transitions between orange and light purple using a lerp weighted with a sine wave. The second color is its quot isinDanger quot state, and this lerps between orange and red. Is there any way to make the transition between both of these color variants smooth? When the bool is set to true the colors switch instantly with no transition. I've tried numerous things to try to get them to be smooth but ultimately it just breaks the lerping. using System.Collections using System.Collections.Generic using UnityEngine public class GemGlowOrange MonoBehaviour public Material Mat Color Red Color lightpurple Color orange public bool isInDanger false Color CurrentColor float startTime public float speed 1.0f void Start() startTime Time.time time since game started orange new Color(1.320755f, 0.5346785f,0.2928088f,1f) making my colours RGBA Red new Color(0.858f, 0f,0f,1f) lightpurple new Color(1.320755f,0.2973427f,0.8263685f,1f) var Mat GetComponent lt Renderer gt ().sharedMaterial making a reference to the material so we can enable the emission keyword if you do not want this to affect every object using this material then use quot Getcomponent lt Renderer gt ().material quot the same goes with setting the color as you can see further down. Mat.EnableKeyword( quot EMISSION quot ) this is making sure this shader has the emission keyword enabled. void Update() float frac (Mathf.Sin(Time.time startTime) speed) CurrentColor Mat.GetColor( quot EmissiveColor quot ) if (!isInDanger) Mat.SetColor( quot EmissiveColor quot , Color.Lerp(lightpurple, orange, frac)) getting the same material over and over again each frame and updating its emission colour else if (isInDanger) Mat.SetColor( quot EmissiveColor quot , Color.Lerp(Red, orange, frac)) if it is in danger then it will alternate between red and orange.


How can I prevent movement from analog joystick "bounce"? I'm working on a top down game where the player can move up down left right. The sprite changes to the corresponding direction, and I have an internal value that tracks the direction the player is facing. The actual movement is handled just by doing rigidbody2D.MovePosition(player.position movement speed Time.deltaTime) and it's working fine. Direction is determined by looking at the absolute values of all 4 axis values and seeing which one is greatest. The problem I'm having is when using an analog joystick on a controller. So, if you suddenly let go of the stick, it has a little "bounce" where it goes past the center, and into the opposite direction. I uploaded a slow motion video of the joystick being released, to show this "bounce." See GIF here I added some logging to the input, and here are some numbers The joystick bounce always ends up being somewhere between lt 0.1 to up to 0.5, for maybe 1 frame in time. What can I do to mitigate the effects of this bounce? It's causing my player to suddenly look in the opposite direction if they suddenly stop moving. I've had these ideas for solutions, but I'd love some advice Increase deadzone to be over 0.5 This seems like an easy fix, but that feels like it's too big of a deadzone. Ignore input if the difference between last frame and current frame is greater than a specific value (maybe 0.5?) Average out input over the last few frames and then move? Seems like it could be buggy though (and feel laggy)


Unity Smoothing between two floats which are continuously changing I'm looking for some help with smoothing between an original float and a target float, where the original float is consistently changing (potentially interfering with interpolation techniques and or Mathf.SmoothDamp) I tried Mathf.SmoothDamp with the below (float rocketBoostPower is a global variable) float yVelocity 0.0F float tempForce rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f rocketBoostPower Mathf.SmoothDamp(rocketBoostPower , tempForce, ref yVelocity, 0.5f) This doesn't change the force at all however, it just stays locked in place. I'm currently using the below to change my power, however I want to smoothly change the power instead of just incrementing sharply on each Update frame rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f Please can someone help? I need the assumption that every update will receive a new rocketBoostPower value, whilst still smoothing its previous value.


Update the UI Rotation According to camera rotation I have a camera which is showing the userInterface (canvas) object into the front of my camera. I am only updating my userinterface position if the camera raycast is not hitting my userInterface object collider. something like this public class UIPlacerAtCamFront MonoBehaviour public GameObject userInterface public float placementDistance Vector3 uiPlacementPosition RaycastHit objectHit void Update () Vector3 fwd this.transform.TransformDirection(Vector3.forward) Debug.DrawRay(this.transform.position, fwd 50, Color.green) if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50)) raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already else raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera uiPlacementPosition this.transform.position this.transform.forward placementDistance userInterface.transform.position uiPlacementPosition Continuously update userInterface rotation according to camera userInterface.transform.rotation this.transform.rotation The above script has attached with my camera, it displaying the object correctly but as i start to rotate my camera my UI object rotation looks very strange as below image suggested As i rotate, this problem occurs I know that the problem is in rotation, so I tired to change my this rotation code userInterface.transform.rotation this.transform.rotation to this userInterface.transform.localEulerAngles new Vector3 (this.transform.localEulerAngles.x, 0, this.transform.localEulerAngles.z) but it bring another strange rotation for me, like given below I want that my userinteface object face my camera correclty, even my camera watching the start or end of my userinteface object. How can i rotate my UI according to camera rotation correctly?


How to set default pose of model from Blender? (Exported as FBX) I have a model that has lots of animation clips(actions). Before export as FBX, I set the pose to named "default" pose and exported as FBX like this. But in Unity, it's changed to first animation clip in animation list in Blender! I try to fix it, but there is nothing I can do. I can't change the order of animations in Blender and Unity either. This wasn't first time, I had same issues before but I just ignored because it's fine in game play, but I really want to fix it this time. What I want is set "default" pose in edit mode in Unity(not play mode). How do I set "default" pose as default, not first animation clip in the list? Using Blender 2.78, and Unity 2017.3.0f3.


Idle Walk animation problem and double button input axes I have 2 problems with unity3d. First, I created an animator and attached it to player. In animator I put 2 condition, Speed and Running (first is float, second is boolean). Default Animation is Idle. Then player press W, I want animation to fade from idle to walk and when he stop press the button, I want the animation to fade from walk to idle. Here is my problem. When I press W, he make walk animation, but after it he play half of idle animation and after it he enter again in walk animation. How can I loop the walk animation until he release W? And if he release, even if the animation isn't totally played, I need the animator to make transition to idle. How can I make this "transition"? Then I release W, he just go from walk to idle animation without any transition (and it is a kind of wear). Second, How can I put 2 input buttons on axes? I mean If he press W, there should go vertical axes. When he press W Left Shift, there should go running axes. How can I attach 2 buttons to 1 axes? I am new in unity and I want to figure out how to work with this things.


Creating 3D gravity in zero G tied to mass in unity with c As a total beginner, I've been working on a patch job script for a gravity mechanic in an open space sim, I want to derive all my objects from this "Block ALPHA" object and its' set of variable attributes, so it's important that I get it right before moving on. The idea is simple enough, call an array of all interactive objects' coordinates and apply a basic equation to simulate gravitational pull. After some tinkering I have a piece of code that ticks all the boxes AFAIK, but I can't for the life of me figure out the syntax error I've made... I've been up all night massaging the script to fit my needs, but in the best cases it only raises one error "expected ' '" Maybe I'm just tired, maybe I broke the code, but trying to place parentheses only seems to bring more errors Here's the code as it is so far complete with the compiler error and suggested fix (in red), which does no good whatsoever using UnityEngine using System.Collections public class DynamicWeightAnalysis MonoBehaviour Strength of attraction from your game object, ideally this will be derived from a calculation involving the objects volume and density eventually public float RelativeWeight Here, we name our target objects GameObject blockALPHA Initialise code void Start () here, we define our target objects further by searching for the predefined tag blockALPHA GameObject.FindGameObjectsWithTag("Block ALPHA") Use FixedUpdate because we are controlling the orbit with physics void FixedUpdate () " EXPECTED" this is where we define the graverage coordinates Vector3 graverage (Vector3 blockALPHA) if (blockALPHA.Length 0) return Vector3.zero float x 0f float y 0f float z 0f foreach (Vector3 pos in blockALPHA) x pos.x y pos.y z pos.z return new Vector3(x blockALPHA.Length, y blockALPHA.Length, z blockALPHA.Length) Vector3 offset here we get the offset between the object and the average position of all objects offset graverage transform.position This is the variable for square magnitude calc float magsqr Offset Squared magsqr graverage.sqrMagnitude Check distance is more than 1 to prevent division by 0 (because my blocks are all 1x1x1, any closer and they'd be intersecting) if (magsqr gt 1f) Create the gravity make it realistic through division by the "magsqr" variable GetComponent lt Rigidbody gt ().AddForce((RelativeWeight graverage.normalized magsqr) GetComponent lt Rigidbody gt ().mass) I don't doubt that I've overlooked something stupid, but it's my first stab at proper coding, so, no shame in asking Thanks D


TBS Shooter targeting AI I have some experience in developing all sorts of (small) games using Unity3D, I have a few personal game projects and I also work for a small game studio. The only subject in game development that I've avoided at all costs was AI, up until now. My other projects required just basic NPC algorithms, so i can't call that AI. On to my problem I have 2 or more player opponents that have to shoot at each other, taking turns (think of a Worms game). They fire using a ballistic arc, adjusting firing power and gun elevation. The problem is making the CPU player to behave like a human player would, without using firing at random. I have, from other games, and algorithm that computes the angle and projectile velocity required to hit dead on the target, but that would kill the opponent in the first few seconds. So i need a smarter, human like approach fire a trial shot, smartly adjust to improve aim. Also account for wind direction and speed that affect the projectile. After some AI research, I was thinking of using genetic algorithms, but i do not need a perfect solution to my problem (to hit the target in the first round) but rather a constant improving one. Also if the algorithm could be tuned for easy medium hard difficulty would be great. I do not necessarily need a complete solution, but a direction to dig to.


Increase speed with each enemy destroyed? I need some help with coding this idea "For each Target destroyed, increase the Gunner's speed by (speed variable)". The idea is that the Gunner is automatically moving, and I want it to become more frantic with each target hit. Here's the relevant code I have so far using UnityEngine using System.Collections using System.Collections.Generic void Update () Gunner Move () gives me the error "Assets Scripts MovementPathScript.cs(60,83) error CS0200 Property or indexer System.Array.Length' cannot be assigned to (it is read only)" void Gunner Move() if (GameObject.FindGameObjectsWithTag ("BulletProgressionObject").Length 1) Gunner SpeedIncrease () void Gunner SpeedIncrease() behavior that I'm not sure how to make for the bullets colliding with target's parent object void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag ("BulletProgressionObject")) Destroy (other.gameObject) I think it's a foreach loop, but the issue I'm having is properly implementing it. Any suggestions or referrals would be greatly appreciated.


Disable global fog from camera Does anyone know how to disable global fog from a particular camera? I have two cameras in my scene one is a mini map camera, where I need to disable global fog. I have checked this answer and the wiki, but have found nothing that works.


Why does Unity think my RectTransform has changed? I am working with UI. I want to know when my RectTransform changes its position. I am using transform.hasChanged void Update() if (transform.hasChanged) Debug.Log("Updated Position") transform.hasChanged false However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky. I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property. How can I check to see if my RectTransform has changed its position efficiently and elegantly?


Unity DirectoryInfo not working in OSX standalone build So I'm building an application in unity which I hope to use at a market day coming up soon at my school (it's not a game, it's basically like a checkout app, kind of...) Anyway, I'd like to be able to import images from the app and to have the option to change them while the app is running. Currently I have the images in a folder and I'm using DirectoryInfo to get the contents of that folder and load the images. Works like a dream inside the editor but as soon as I build the app (on OSX), everything is blank. Other people seem to have similar issues but I'm a little unsure as to how they fixed it. Could someone please help me, this is kind of urgent!


Get VertexSize of Instance in VertexShader I'm using Unitys DrawProceduralIndirect function to directly render the content of a ComputeShader. I setup the argumentBuffer for this function as follows int csArgs new int ptsOnLine, 2, 0, 0 argsBuffer new ComputeBuffer(4, 4, ComputeBufferType.IndirectArguments) So every instance consists of ptsOnLine (lets say 10) vertices. My vertexShader then looks like this fsInput vert(uint id SV VertexID, uint instanceId SV InstanceId) fsInput fsIn float3 worldPos linePoints id (instanceId 10) fsIn.pos mul(UNITY MATRIX VP, float4(worldPos, 1.0f)) return fsIn The question is simple. My problem is (instanceId 10). Is there a built in variable telling me the length of one instance? I couldn't find anything. I mean, its in the argument buffer so it shouldn't be too much of a problem? I could forward this value from the compute buffer but thats ugly. ) Help is much appreciated!


How to offset a 2D GameObject by a pixel amount? I'm extremely new to game creation. I'm playing around with creating a 2D Unity game. The scene is setup from the default Unity 5 2D template. Following a tutorial, I've created a TerrainManager GameObject and Script. The script instantiates tiles and sets their position using a standard double loop. I've found a 2D isometric tile set. Each tile is visually rendered as rotated around the vertical axis by 45 degrees, creating more of a diamond shape rather than a square. This requires that every second tile be offset by half the tile width on the x axis, and half the tile height on the y axis. As each tile is of a different height, one can not simply offset the tile on the Y axis by half its height. Each terrain "layer" is 16px tall in the PNG. Some PNGs have a single "layer", some have multiple "layers". (For instance, a single layer water tile is 83px in height, while a dual layer "grass on top of dirt" layer is 99px in height. As the game object expects the transform.position as a Vector3 in (I assume) game units, I do not know how to compose this using pixel values. So the question I have is, how do I achieve the 16px y axis offset of the game object? I'm more than happy to provide additional details if needed.


Null instance on manager class extending from singleton class I have four classes class A, which is abstract and partial extending from singleton class C. class A1, which is partial and extending from class A . class B, extending from class A. class C, a singleton which has code to throw an exception if the instance is null, and otherwise uses DoNotDestroyOnLoad(). In scene view, I add class B to the scene. It works, but throws a null instance exception for class A, as it's instance is not present in scene. I think this is because class A extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the class A to the scene because it is abstract. What can I do to in order to add the class A component to the scene, or otherwise not to get this error?


Loading player position from file but player object not at right position sometimes In my current project I am developing a game saving system and I have encountered a problem where in some cases when I save the game and re load it the player will not be loaded in at the correct position. I've printed the position that is loaded in from file to the console to see if it's being changed and it's not. Is there anything i'm not seeing? For reference here's the two methods I use when loading the game public void LoadData() if (File.Exists(filename)) byte soupBackIn File.ReadAllBytes(filename) string jsonFromFile encryption.Decrypt(soupBackIn, JSON ENCRYPTION KEY) copy JsonUtility.FromJson lt SaveData gt (jsonFromFile) print(copy.playerPosition) DataToLoad() private void DataToLoad() player.transform.position copy.playerPosition player.transform.rotation copy.playerRot player.playerHealth copy.playerHealth player.agility copy.agility player.attack copy.attack player.defense copy.defense player.strength copy.strength for (int i 0 i lt copy.inventory.Count i ) inv.AddItem(copy.inventory i .id)


Adding a feedback survey to a game So I am currently making a game that aims to help people with anxiety management. I , however, would like to ask them how they feel before playing the game and then again after playing the game. Would it be possible to do this directly on Unity? I would like for them to be able to log their entries much like an online journal. I have attached pictures from the daylio app. I would like to do something similar. At this point, I really do not know how to begin doing this on Unity. Any advice, or tutorial suggestions would be appreciated. This far I have managed to do the following (in the picture below) This is how the survey looks (its pretty rudimentary at this point) And this is where the information is getting displayed (in the inspector) So now, what I would like to know, is how would I go about sending this data to somewhere else i.e. as it is in the daylio app?


Rendering part of an equirectangular video on a plane For a Unity project I have a 360 camera which produces an equirectangular video. I need to realize preview of this video for putting it on a plane. In most cases the part of the video to be drawn on the plane is the central part of the video, which is not so stretched and so it can be drawn as is. In some cases, instead, the camera has to be put above the scene, upside down, in order to capture the scene below, as shown in the following image. In this kind of situation I need to produce a preview from the upper part of the video in other words I need to project a portion of the upper part of the video on a plane. I imagined two ways, the first one is easy but not so effective, the second one is tricky but surely better. I project the video on a sphere and capture, with a virtual camera, the interesting part, which is taken and rendered on a plane. I write an appropriate shader which, given the equirectangular video, crops the portion of it and draws it correctly on a plane. May you give me a hand on writing the shader?


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


Using Euler angles to rotate object 360 degrees I'm trying to create script that rotates object in given axis by set amount of degrees. That's my 2 core methods public Vector3 rotation public void RotateDegreesFast () transform.DOLocalRotate (GetTargetRotation (), rotationTime) private Vector3 GetTargetRotation () Vector3 newRotation new Vector3 ( rotation.x transform.localEulerAngles.x, rotation.y transform.localEulerAngles.y, rotation.z transform.localEulerAngles.z) return newRotation I was using this script for a little while, it was working perfectly in Y and Z axis. Now I try to rotate object 45 degrees in X axis (rotation new Vector3(45f, 0f, 0f)). It works until rotation in x value equals 135. Transform.localEulerAngles.x is returning 45 instead of 135. So it's stuck between 90 and 135 degrees. I was trying to use transform.localRotation.eulerAngles.x instead, but it doesn't work as well. I am aware this works that way because specific Euler angle can be represented in many ways. I also know that DOTween has DOLocalRotateQuaternion method, but the thing is that this component is often reused by a designer that sets value of rotation variable in the inspector. It's way easier to use Euler angles for him.


How do I add an "offset" to LookAt? I have created a Third Person Controller. The camera is behind the player I would like to make it so that the player aims at the mouse pointer position. To do that, I use the following code to rotate the chest towards the position var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) Chest.LookAt(aim) The hands do not perfectly straightly point forwards, so I need to add an quot offset quot to the LookAt. I tried this approach var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Chest.LookAt(aim) Of course I do all rotation patching in LateUpdate(). In Update(), it would simply be erased by the animation itself. It does work, but when the model is rotated around the Y axis, something goes wrong The offset is quot wrong quot , it doesn't have the same effect. This surprises me because all I do is rotate the entire model. So I think this line is not correct aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Is this not the way to offset the LookAt results?


UDP server in unity not working I know there are a lot of UDP examples out there, but I really need to know specifically what I am doing wrong. I have Wireshark monitoring my data traffic and according to that program Unity is not sending data at all. Could some of you coding wizards look over this and help me find my mistake? public class heatLampControl MonoBehaviour Ben Stewart, june 6th, 2016 this code controls the "Position" of the heat lamps, ie what angle the heat should be coming from. The value will be added to a new UDP connection to the dSPACE machine Update 6 10 Added UDP functionality, as accessing the UDP class that was created for this purpose turned out to not function correctly public float lampIntensity 0.0f Multiplier for relative intensity of the sunlight GameObject sun public GameObject player dropped in via GUI public bool isNight false is it night? if so, heat lamp should turn off public double sunAngle angle about the y axis. that is the only angle that can be controlled. public bool isOn false public string keyDown public int port public string dataStr byte data public GameObject cycle following three keep track of day night cycle public Day Night.TimeOfDay tod public Day Night dayNight public int strLength private IPAddress ip private UdpClient udp private IPEndPoint ipep public float fruitIntensity public float hayIntensity OlfactoryControl olfactory string hostname IPAddress ipList void Start () hostname Dns.GetHostName () ipList Dns.GetHostEntry (hostname).AddressList port 13722 cycle GameObject.Find ("DayNight") dayNight cycle.GetComponent lt Day Night gt () sun this.gameObject olfactory GameObject.Find ("Olfactory").GetComponent lt OlfactoryControl gt () ip ipList 0 ipep new IPEndPoint (ip, port) udp new UdpClient (13722) Update is called once per frame void Update () sunAngle player.transform.eulerAngles 1 Math.Atan2 (sun.transform.position 2 , sun.transform.position 0 ) gets the positional angle of the sun compared to the player keyDown Input.inputString if (isNight Input.GetKeyUp (KeyCode.L)) IF L is pressed down, light will come on lampIntensity 0f isOn false if (!isNight amp amp Input.GetKeyDown (KeyCode.L)) lampIntensity 1f isOn true tod dayNight.tod if (tod Day Night.TimeOfDay.Idle) lampIntensity 1.0f if (tod Day Night.TimeOfDay.SunRise) lampIntensity (dayNight.timeOfDay (dayNight.sunSet dayNight.StartTime)) hayIntensity olfactory.hayIntensity fruitIntensity olfactory.fruitIntensity sendUdp () june 30th edit void sendUdp() dataStr hayIntensity.ToString () fruitIntensity.ToString () lampIntensity.ToString () byte sendBytes System.Text.Encoding.ASCII.GetBytes (dataStr) Debug.Log (dataStr) udp.Send (sendBytes, sendBytes.Length, ipep) Debug.Log ("Data sent to IP Address " ip.ToString() " on port " port.ToString())


Null Reference Exception while getting Components I'm trying to access my enemy and spawning values from two different classes into a class that is trying to change them both. Although when I do this I keep getting a Null Reference Exception error. The error is where spawnManager first gets called. This is the code that is trying to get the two values. (And just to note I am trying to access these two values from my Welcome scene and these two values are in my Game scene but I do not know if this is affecting anything) private EnemyAI enemy private SpawnManager spawnManager void Start() spawnManager GetComponent lt SpawnManager gt () enemy GetComponent lt EnemyAI gt () public void onEasy() spawnManager.enemyShipWait Random.Range(1f, 3f) lt This line has the error spawnManager.randomPowerupWait Random.Range(7f, 12f) enemy.speed 2.75f These are the two pictures of my scenes Game Scene Welcome Scene


Unity higher Z position tiles rendered underneath When placing tiles in an isometric tile map in Unity, I try to place blocks on top using the quot Z Position Value quot However it looks like higher Z position values get rendered underneath. In this picture, the green cubes have a z position of 0 whereas the yellow cubes have a z position of 1. I want the yellow cubes to render on top, but they are underneath. I'm using an Isometric Z as Y tile map and have the Transparency Sort Axis set to (x 0,y 1,z 0.26).


How to make a character sit in Unity? So I've got the animation, it has root motion but activating it in the settings doesn't seem to do much. What would be a good optimized way to have the character sit on the stool with the animation matching the movement? Would I need to do it through code?And if that's the case, could I specify in which frame do the movement? Or add a second animation that is in charge of Root Motion? I know either of these two options I give could work but I'm checking to see if there is a better way or if I'm missing something here. Thanks! EDIT Following DMGregory's comment I disabled the collider to see if it improved... it did change, but it isn't much better EDIT 2 This is how the animation preview looks like (what I'm expecting) Then I just hold the last frame while they're sitting and play the animation backwards for when they're getting off this is just while I get it to work.


how do I set an int to the scroll wheel data in unity i need to set an int to data from the scroll wheel so I can have the script use this int to display an item attached to a number from that int. i'm using c i set up my scroll wheel input, what am i doing wrong? here is the script counter Mathf.RoundToInt(Input.GetAxis("ScrollWheel")) Items.text counter.ToString()


Unity Trying to copy the render texture for the scene rendered by a camera but it is blank? I'm trying to copy the scene rendered by a particular camera to a render target. I know this should be possible to do without using the camera's target texture as I read through this official Unity article about Command Buffers which avoids any use of them. Instead, I found that they use the following code in the renderer for blurry refractions (CommandBufferBlurRefraction.cs) to copy the scene to a render target. buf new CommandBuffer() buf.name "Grab screen and blur" m Cameras cam buf copy screen into temporary RT int screenCopyID Shader.PropertyToID(" ScreenCopyTexture") buf.GetTemporaryRT(screenCopyID, 1, 1, 0, FilterMode.Bilinear) buf.Blit(BuiltinRenderTextureType.CurrentActive, screenCopyID) The problem is that I can't get this to work for myself using a very simple scenario of Camera renders the entire scene which is a single hexagonal sprite The command buffer assigned to the camera grabs the BuiltinRenderTextureType.CurrentActive (Scene Render Target) The command buffer then copies that to another render target That render target is then drawn in the upper left of the screen on a yellow background This results in the scene render target being completely blank and not including the white hexagon. The code I am using is Camera cameraUsedToRender CommandBuffer commandBuffer RenderTexture debugRT Texture2D debugRTBackground void Awake() Create debug texture to render debugRTBackground new Texture2D(2, 2) debugRTBackground.SetPixels(new Color 4 Color.yellow, Color.yellow, Color.yellow, Color.yellow ) debugRTBackground.Apply() cameraUsedToRender Camera.main cameraUsedToRender.orthographicSize 10f Create debug render texture to render to using our camera debugRT new RenderTexture(cameraUsedToRender.pixelWidth, cameraUsedToRender.pixelHeight, 16) debugRT.Create() Create command buffer commandBuffer new CommandBuffer() commandBuffer.name "Debug" Add the camera buffer to the main camera cameraUsedToRender.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, commandBuffer) void OnRenderObject() Clear the command buffer commandBuffer.Clear() Set the render target commandBuffer.SetRenderTarget(debugRT) Clear the render target commandBuffer.ClearRenderTarget(true, true, Color.blue) Copy scene into a render target RenderTarget.active SceneView RT (UnityEngine.RenderTexture) commandBuffer.Blit(BuiltinRenderTextureType.CurrentActive, debugRT) Release the render target commandBuffer.SetRenderTarget(null as RenderTexture) void OnGUI() Draw the debug render target (which should have the SceneView RT copied to it) GUI.DrawTexture(new Rect(0, 0, 130, 130), debugRTBackground) GUI.DrawTexture(new Rect(1, 1, 128, 128), debugRT) The complete small, simple project that demonstrates this issue can be found here. Does anyone have an idea how to resolve this as I'm finding the Unity rendering pipeline to be rather confusing at this point?


Determining value to add subtract scaling I have a menu panel. It appears if the user presses the Enter key, and it disappears if he presses the Enter key again. When the menu is still hidden, its X scale is set to 0. In its normal expanded state is 0.00175f. When the menu is shown or hidden, I want to smoothly scale from 0 to 0.00175f or from 0.00175f to 0. To do that, I have written a coroutine private IEnumerator pShrinkExpandMenu(bool uShrink) if (!uShrink) Menu.SetActive(true) the menu should be expanded enlarged, so we need to make sure it's visible float fWidthIfExpanded 0.00175f float TimeInSecondsToSwitch 0.3f TimeElapsedOnShrinkingExpanding Time.deltaTime while ( TimeElapsedOnShrinkingExpanding lt TimeInSecondsToSwitch) float fValue if (uShrink) fValue ... else fValue ... Menu.localScale.X fValue yield return 0 if (uShrink) if we shrink, and it's completely shrunken, hide it Menu.SetActive(false) I hope that my coroutine is fine. One thing that I just don't know is how to determine the value that the X scaling should be changed during one loop. I have no idea how to calculate fValue. Could anybody explain that to me, please?


how to sync clients and local avoidance in mobile RTS game? I have been making mobile RTS game in Unity look like Clash Royale similarly. Unfortunately, I faced to two big problems. First is two phones(clients) to be synchronized each other in game state. And second is "path finding" or "local avoidance"(collision check). To solve the path finding issue, I have searched about "Flow Field". Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"? If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients? Thank you in advance.


How to use base.Function() in Unity I am using 3 classes EnemyBullet MonoBehavior EnemyBulletType1 EnemyBullet EnemyBullet Class void FixedUpdate() this.gameObject.transform.rotation Quaternion.Euler (new Vector3 (0,0,90)) EnemyBulletType1 Class override void FixedUpdate() base.FixedUpdate () Do something else here The reason is I'll have many EnemyBulletType classes and I want them all to do a common thing and then do something on their own. Question This code isn't working Error virtual or abstract members cannot be private How is FixedUpdate() defined in the MonoBehviour and how to change it to help my usecase?


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


.png file to Sprite(2D and UI) still not visible under source image I am trying to use an image as a UI Image but even after changing its texture type to Sprite(2D and UI), it isn't visible in the source image menu. The file was created in MS Paint and I'm accessing the source image menu via the "circle selector" next to Source Image in the Inspector. I'm pretty sure I've never had this issue before. I wish I could share more details but there's nothing much to say. What could be causing this issue?


Programatically Build List of Custom Class Objects (prefabs) This seems like it should be a simple thing, but I cannot seem to figure out a method. Currently, I have a public List lt MapGraphItem gt roomList variable, and in the inspector, I add prefabs from Tiled2Unity for a given biome currently a list of nine tiles for my test biome. Map generation works great via this method. MapGraphItem is a custom class that is applied to these prefabs via script. I'd like to programmatically build the list so that I can build it appropriately based on the biome that's being called (dungeon, forest, desert, et cetera). I seem to be having trouble getting unity to put together a list of the items anyhow (they are in a specific assets folder and also have a specific prefix, in this case "dng "). I tried this and some variations on it List lt GameObject gt obj GameObject.FindObjectsOfType(typeof(GameObject)).Select(g gt g as GameObject).Where(g gt g.name.StartsWith("dng ")).ToList() But it seems the objects need to be loaded first (plus, I'd need to convert it to a List lt MapGraphItem gt before using it). I could add another field to the MapGraphItem class for biome type and basically load ALL of the assets, but that's a huge waste of resources. Manually adding these for each biome is really not ideal, and really not efficient. Thanks!


Blocking Physics Raycasts with Unity's 4.6 UI? I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non rectangle shaped UI that's pretty difficult. I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size. Note Canvas Group does not apply to physics.raycast


Instantiating problems I'm beginner here, I'm trying to instantiate a single object every specific duration, either form the left of the screen or from the the right, at the same time I want this object to move to the other side of the screen So the troubles I'm facing here are sometimes 2 objects are being instantiated at the same time. the objects move in the direction that are defined in the first if statement (both objects on the left and the right move in one direction) the part where I instantiate objects is in the script(smallFishes) that's attached to an empty gameobject is void Start () timer gameObject.AddComponent lt Timer gt () width 2f timer.Duration 3 timer.Run() left Resources.Load("Left") as GameObject right Resources.Load("Right") as GameObject void Update () if (timer.Finished) lr Random.Range(1, 3) if (lr 1) var generetx 8.8f width 2 Instantiate(left, new Vector2(generetx, Random.Range( 4.8f,4.8f)), Quaternion.identity) else var generetx 8.8f width 2 Instantiate(right, new Vector2(generetx, Random.Range( 4.8f, 4.8f)), Quaternion.identity) timer.Duration 3 timer.Run() public int state get return lr the part where I make the object move from the script that's attached to the object prefab void Start () small gameObject.AddComponent lt smallFishes gt () rb2d gameObject.GetComponent lt Rigidbody2D gt () void Update() var fishes GameObject.FindGameObjectsWithTag("small") if (fishes! null) if (small.state 1) moveright new Vector2(4 Time.deltaTime, 0) rb2d.AddForce(moveright, ForceMode2D.Impulse) else moveleft new Vector2( 4 Time.deltaTime, 0) rb2d.AddForce(moveleft, ForceMode2D.Impulse) Thanks in advance.


Programmatically creating new tags in Unity I'm writing a custom editor script to add tags programmatically. I got the error of IndexOutOfRangeException Array index is out of range from the lines below SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") These are my codes SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") Adding a Tag string s "Instantiated" First check if it is not already present bool found false for (int i 0 i lt tagsProp.arraySize i ) SerializedProperty t tagsProp.GetArrayElementAtIndex(i) if (t.stringValue.Equals(s)) found true break if not found, add it if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s Latest Update Error IndexOutOfRangeException Array index is out of range is solved by resolving file location in my original script. I apologized for that. Fixed Added a line in the script to update the properties if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s tagManager.ApplyModifiedPropertiesWithoutUndo()


How to make a cell shader like BOTW in Unity? It seems most cell shader tutorials focus on individual shaders for materials, but the effect used in BOTW seems to be more like a filter, that is applied to everything. I've researched multiple examples that have been done in UE4 like here and here but nothing in Unity. How would I apply something like this in Unity?


Unity2D Rendering multiple sprites as a single one I'm creating NPCs in Unity 2D using C , and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet. I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way? Thanks in advance!


Instantiate two objects at random non overlapping positions I'm making an endless runner game. I have the script that make coins and walls appear at the same time in front of the player. The problem is that sometimes the coin and wall appear in the same place position. How can I ensure that coins and walls do not appear in the same place position? public class Instantiate MonoBehaviour public float betweenSpawn 1.05f public float angle public Vector3 spawnValues Range of appearing public GameObject coinPrefab public GameObject wallPrefab public Transform coinInstantiate public Transform wallInstantiate void Start() InvokeRepeating("Spawn", 0f, betweenSpawn) void Spawn() Vector3 coinPosition new Vector3(Random.Range( spawnValues.x, spawnValues.x), 1, Random.Range( spawnValues.z, spawnValues.z)) Vector3 wallPosition new Vector3(Random.Range( spawnValues.x, spawnValues.x), 1, Random.Range( spawnValues.z, spawnValues.z)) Instantiate(coinPrefab, coinPosition coinInstantiate.TransformPoint(0, 0, 0), Quaternion.AngleAxis(angle, Vector3.forward)) Instantiate(wallPrefab, wallPosition wallInstantiate.TransformPoint(0, 0, 0), Quaternion.AngleAxis(angle, Vector3.forward))


Sprite Image in Canvas not displaying correctly (distorted) I have a problem with displaying images in my Canvas, as they're not displaying exactly like the imported image. In the image below, the sprite on the left is how it looks when it's imported. The sprite on the right is how it looks in the canvas. Notice that some of the pixels have incorrect colours, like the lighter pink in the center of the staff's top is gone, the eyeball is a darker shade, some of the colouration under the hood is wrong, and other errors. ( The sprite is just a test I took from somewhere else, not what I intend to use as a final product. ) The project is 3D (going for a 2.5D look with billboard sprites) set to 384x224 resolution, orthographic camera size of 3.5, no anistropic textures, no anti aliasing. Is there some setting I missed somewhere to ensure that images display 100 exact like the source sprite when used in the Canvas? EDIT Sprite in the Inspector (Seems to also not be correct) EDIT Added entire inspector


Do I need to be careful about PPU and Camera size and Device Resolution even if I'm not creaing a pixel art 2d game? I was reading this blog post https blogs.unity3d.com 2015 06 19 pixel perfect 2d and was wondering if I need to be super careful about those numbers, although my game's art is not pixel art.


How to hide a sprite on trigger when the player enters the trigger zone? I am making a roof for my 2D top down survival game, and I want to make it so that the roof disappears when the player enters the building, and re appears when they leave. Here is the code I've written so far using System.Collections using System.Collections.Generic using UnityEngine public class Roof MonoBehaviour public GameObject roofGameObject void OnTriggerEnter2D(Collider2D collision) roofGameObject.SetActive(false) void OnTriggerExit2D(Collider2D collision) roofGameObject.SetActive(true) I got it to work so that, when I go in, the roof it disappears. But when I leave it stays disappeared. How can I fix that?


Recursive method causes an OutOfMemory error If a GameObject in my game has a special ability it triggers it, but I want all the special GameObjects that this GameObject affects to also trigger their abilities, for example if a bomb hits some objects, if these objects are also bombs, trigger them too. I though this would be easy by calling the method that handles all the special abilities recursively, but it wasn't. Basically what happened is a chain reaction of bullcrap that caused Unity to show an OurOfMemory error. Also makes my PC freeze completely while politely turning all the screens off. The question is, how can I make it so it triggers all the affected cubes' special abilities, without everything going nuts? Code Triggers the cube's special ability, if it has any private void TriggerSpecialCubeAbility(GameObject specialCube) switch (specialCube.tag) Destroy all cubes in a radius from the special cube case "Bomb" TriggerBombAbility(specialCube) break Destroy all cubes of the same color as the special cube case "Lighting" TriggerLightingAbility(specialCube) break default break private void TriggerBombAbility(GameObject specialCube) var nearbyColliders Physics2D.OverlapCircleAll(specialCube.transform.position, explosionRadius) Instantiate(particles 0 , specialCube.transform.position, specialCube.transform.rotation) Instantiate(particles 1 , specialCube.transform.position, specialCube.transform.rotation) foreach (var collider in nearbyColliders) if (collider.tag "Indestructible") return var affectedCube collider.gameObject TriggerSpecialCubeAbility(affectedCube) Destroy(affectedCube) destroySelectedCubes true


Sticky Conveyor Belt I'm working on having a sticky conveyor belt, so that objects can also go around it. But my objects currently get stuck half way, as seen in the picture. This is the movement code of the conveyor belt. private void HandleCargo() var speed speed Time.deltaTime foreach (var cargo in cargo) var change cargo.Key.transform.right speed cargo.Key.transform.Translate(change) And the code taking care of the rotation to the surface. private void Update() Debug.DrawRay(transform.position, transform.up, Color.black) if (!Physics.Raycast(transform.position, transform.up, out var hit, distance)) return var normal hit.normal transform.up (transform.up hit.normal) 0.05f If someone has pointers as to why this happens, that would be great. I kind of have an idea, since the transform right of the conveyor code is pointing inwards at this angles so the movement doesn't happen around the belt anymore, but I exhausted my attempts to fix it... Edit After DMGregory answer a new issue appeared. As soon as the cube starts to adjust to the spheric surface it is not exactly on the mesh anymore, which triggers my on collision exit code and stops movement on the object. I have some code that is supposed to stick the object to the belt, but that doesn't seem to work? The sticky code private void Update() Debug.DrawRay(transform.position, transform.up, Color.black) if (!Physics.Raycast(transform.position, transform.up, out var hit, distance)) return transform.rotation Quaternion.FromToRotation(transform.up, hit.normal) transform.rotation transform.position new Vector3(transform.position.x, hit.point.y 0.5f, transform.position.z)


Is my collision free location script working? I've recently been learning C and I wanted to take one of my 2D tutorials to Unity. I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction generated random location, calculating Vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors. But, because I'm still only just learning C , I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something? Vector3 spawnLocation new Vector3 (Random.Range (minSpawnX, maxSpawnX), Random.Range (minSpawnY, maxSpawnY), Camera.main.transform.position.z) Vector3 spawnPoint Camera.main.ScreenToWorldPoint (spawnLocation) Vector2 lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Vector2 upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) ! null) spawnPoint.x Random.Range(minSpawnX, maxSpawnX) spawnPoint.y Random.Range(minSpawnY, maxSpawnY) lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner)) I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working. I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.


How to create a material with variable color I'm new to Unity and trying to create a Carrom game. Since all the White and Black pieces, Queen basically have the same material and physical properties and texture except for their color, I'm trying to create a single material that I could assign to all 3 types of objects but could then set the material color per object type. Can this be achieved in Unity (I'm using 5.3.2)?


OnTriggerEnter2D or OnCollisionEnter2D not getting called I checked the other answers for this but mine didn't get fixed Here's the code using System.Collections using System.Collections.Generic using UnityEngine public class DestroyCollectibles MonoBehaviour private void Start() Debug.Log( quot Hallo quot ) private void OnTriggerEnter2D(Collider2D collision) Debug.Log( quot Trigger quot ) private void OnCollisionEnter2D(Collision2D collision) Debug.Log( quot Collsion quot ) if (collision.gameObject.CompareTag( quot Collectible quot )) Debug.Log( quot Apple quot ) Destroy(collision.gameObject) And screenshots