Render Texture shows opposite view of camera when rendered? I am using render texture (cube) to render what camera sees into it. However, the render texture shows me opposite side of cameras view (flipped) instead of what camera sees. Any solution for this? void Update() renderTexture.isPowerOfTwo true Graphics.SetRenderTarget(renderTexture, 0, CubemapFace.PositiveZ) renderTexture.dimension TextureDimension.Cube camera.RenderToCubemap(renderTexture, 63) What camera sees What Render Texture shows What happens when I rotate Render Texture manually by hand 180 degrees So, instead of rotating per hand, what I want is for the render texture to be rotated via code so that what is in camera view is shown exactly the same in render texture view.


Rotate an object with 'Quaternion.Slerp' in world space I'm currently working on a multiplayer skydiving Unity game in which i rotate the players like this transform.rotation Quaternion.Slerp(transform.rotation, desiredRotation, delta) Now this rotates the player relative to it's own rotation. I know rotation in world space is done by multiplying the quaternion of the desired positon with the quaternion of the current position like this localRotation transform.rotation desiredRotation worldRotation desiredRotation transform.rotation But how do i slerp to that position in world space? Thank you all in advance and have a great day!


How does Unity Inspector handle values changing during play without any thread locks? First of all, I'm a Java coder. Usually, when you write a game, you run it on thread different than the UI one like pseudocode starts new Thread(new Runnable() Override public void run() while(someVolatileBoolean) input() physics() graphics() and then you declare some sort of listener for the input which usually works on application UI thread so you need to mark it as volatile, atomic or perform a basic synchro using the synchronized keyword (depending on the situation). Let's take a simple Unity script public class SomeMovementScript MonoBehaviour public Vector3 speed new Vector3(0.1f, 0, 0) void Update () this.transform.Translate(speed Time.deltaTime) If we then play the game, the object starts to move with speed 0.1f. Now, when the game is playing, we can change the speed variable through the inspector I thought from the UI coder point of view I'm changing a variable, which is being read each frame by the game thread. How does this happen, that I don't get some sort of ConcurrentModificationException if there's no visible synchronization at all. The variable is public, not being cached in any way. I know that this question should be asked on SO, but I thought that GD has more users specialized in Unity and it's mechanics. I came up with immutability. Variable is considered thread safe if it's state can't change. As components are immutable, and classes like Vector2 3 4 are immutable it would work. But... You can make your own class Serializable , mark their fields as public and the class is not thread safe but it is visible through the inspector. How does Unity Inspector perform these real time updates with all the classes you can think of?


How to rotate a parent object while rotating a child object to a certain angle using coroutines I have a semicircle like game object which I made by putting two arcs in an empty game object (SCircle) and rotating the 15 (for left arc) and 15 (for right arc) as seen below. SCircle has an Orientation enum with two valuesLeft (rotates SCircle to 45 ) and Right (rotates SCircle to 45 ) as seen in the image below. I use the following coroutine to move SCircle between orientations. IEnumerator RotateLeftOrRight(Vector3 byAngles, float inTime) Quaternion fromAngle gameObject.transform.rotation Quaternion toAngle Quaternion.Euler (transform.eulerAngles) if (circOrientation Orientation.Left) toAngle Quaternion.Euler (gameObject.transform.eulerAngles byAngles) circOrientation Orientation.Right else if (circOrientation Orientation.Right) toAngle Quaternion.Euler (gameObject.transform.eulerAngles byAngles) circOrientation Orientation.Left for(float t 0f t lt 1f t Time.deltaTime inTime) gameObject.transform.rotation Quaternion.Lerp(fromAngle, toAngle, t) yield return null gameObject.transform.rotation Quaternion.Lerp(fromAngle, toAngle, 1) I also used a very similar coroutine to move the individual arcs by 30 (in opposite directions) from say, Orientation Left, as seen below Since SCircle Coroutine is activated by a mouse click, I have the case where the individual arcs coroutine is run and before it is complete the parent SCircle coroutine is also run. In this case the arcs end up moving from Left to A, which is not the behavior I need. I would want the behavior of them ending up at B when moving from the Left. Likewise, from B, when the SCircle coroutine is run while the arcs coroutine is in progress the orientation will return to the Left. Please note that the blue arrow represents the movement of the left Arc, the red represents the right Arc and the black represents movement of SCircle the parent object. How can I achieve the behavior from Left to B and from B back to Left?


Detecting internet Connection on Unity connection to serve ads How can you detect someone's Internet connection in Unity? I see a lot of forums where people make a request to any site (mostly google.com) to check it, but it does not seem to be an elegant solution. With 3G 4G connections to serve Unity ads or admob interstitial, it takes a lot of time and crashes the game. Regards!


Masking cameras for Voronoi splitscreen I would like to mask a camera to only render to a certain (non square) region of the screen, to be used as an overlay, for splitscreen, or any other application. The goal is obviously to prevent any unnecessary rendering from that camera, so I specified performance, but I'm also happy to hear the easiest to implement option as well. What I'm considering so far Stencil shader on a mesh in front of the camera but my understanding is that doing so would require modifying all shaders on world objects, which isn't ideal. Is there an easier way I'm missing? Transparent mesh with a cutout I could cut out a hole in a mesh and the solid part would block rendering of objects behind it, but I'm not sure how to make that part be transparent so other things can render I'm using Unity 2019 LTS and the built in render pipeline I feel like there must be a simple answer I'm missing but maybe I'm wrong?


How to set up Easy Mobile Pro to work with assembly defintions? I have a project with EMP imported, and now I would like to use assembly definitions to clean up my project a little bit. Everything works fine in the editor, but when I hit Build player script in my Addressables or just trying to Build I get a bunch of nasty error messages. When I switch to VS obviously there are no issues in the code editor. I have asmdef files in Core folder in my Scripts folder, these are scripts created by myself. asmdef EMP Editor folder this one references 3. asmref EMP Scripts folder asmdef There are the kind of errormessages coming up(when trying to build only, there are 200 of them) Assets Plugins EasyMobile Editor EM BuiltinObjectCreator.cs(6,19) error CS0234 The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) Assets Plugins EasyMobile Editor EM SettingsEditor Privacy.cs(9,24) error CS0234 The type or namespace name 'SerializedProperty' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) Assets Plugins EasyMobile Editor EM SettingsEditor Privacy.cs(10,24) error CS0234 The type or namespace name 'EditorStyles' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) I tried adding a refernece to the Unity.Editor dll in VS to the EMP assembly, but VS just doesn't do anything, no errors, no messages...Tried the same in asmdef file in Unity with no luck... I got the inspiration from this video, and it was working ok... Unity 2019.3 VS 2019 Android platform EMP 2.5.2 Thanks


Unity Vertex Color Shader with Transparency I'm trying to achieve a simple effect I have a cube mesh and I want some of the vertices to change color. In this case, I want it to form some sort of a gradient where the unchanged vertices are set to the default color (with alpha 1) and the changed vertices to slowly fade (default color with alpha decreasing towards 0). I'm able to modify these vertices' color with this piece of code using System.Collections using System.Collections.Generic using UnityEngine public class Test MonoBehaviour Mesh mesh Vector3 vertices Color colors List lt int gt verticesToChange void Start() mesh GetComponent lt MeshFilter gt ().mesh vertices mesh.vertices colors new Color vertices.Length verticesToChange new List lt int gt () for(int i 0 i lt vertices.Length i ) colors i Color.white Set the default vertex color if(Mathf.Approximately(vertices i .y, 0.5f)) Change only the vertices on the plane y 0.5 verticesToChange.Add(i) void Update() foreach(int i in verticesToChange) colors i .a Mathf.Max(colors i .a Time.deltaTime 0.5f, 0f) mesh.colors colors Not needed here, but I will be changing the vertices' position too later mesh.RecalculateBounds() mesh.RecalculateNormals() mesh.RecalculateTangents() My problem is selecting a shader that actually uses this color and this color only. I've tried Unlit Color, Unlit Transparent and Particles Standard Unlit with multiple combinations of Rendering Mode, Color Mode and Albedo color. Is there a built in shader that does this and I'm not getting the right combination of its parameters? Or do I have to build my own shader? I've never wrote a shader with Unity, so I would prefer a built in option or an open source free shader.


Import Material from blender into unity Export FBX There have been several questions like this but nothing that is quite the same. I've noticed when Mixamo can create models with materials attached in their FBX. I'm trying to do the same in blender, several people say that this cannot be done. When I export an FBX from unity how can I get the material in with it, whether, that be importing the material through a separate process, or some how baking them in with the FBX?


Unity Get list of gameobjects close to object clicked? I have a stack of balls of 4 colors some touching some not. When you click on one color ball I want to destroy that ball and any other balls of that color that are close. They may not be touching so collision wont work. How do I detect gameobjects close but not touching that are the same color? Say half a radius away from the edge of the ball clicked. Here are the two scripts I'm working with to create and touch the game objects. public class SpawnBalls MonoBehaviour public Rigidbody ball public float waittime 0.5f Use this for initialization void Start () spawn () Update is called once per frame void Update () Instantiate (ball) public void spawn() yield WaitForSeconds(waittime) for (var i 0 i lt 10 i ) Instantiate (ball) Selecting the balls public class Ball MonoBehaviour public Color colors private Color ballpicked Use this for initialization void Start () GetComponent lt Renderer gt ().material.color colors Random.Range (0, 4) Update is called once per frame void Update () void OnMouseDown() if (Input.GetKey("mouse 0")) ballpicked GetComponent lt Renderer gt ().material.color if (ballpicked "Any other balls within a half a ball width") Destroy (gameObject)


My .FBX model is not picking the .TGA texture file I'm at a complete loss. An artist has sent me a 3D model so I can test it in Unity. This is exactly what I got Guy.fbx Guy DIF 512.tga Alright. So I move the folder into the Unity inspector. Suddenly, a Materials folder is created within such folder. The Materials folder has one material. Anyway, now I put the Guy prefab into the scene. It doesn't have textures applied. No problem. A simple Google search yields this response The textures for your model have to be in your Unity project for Unity to apply them automatically when you import. There are 3 different ways to make sure this happens 1 Use Textures for your 3D model from a textures directory already in your Unity project 2 Embed them in the FBX 3 Copy the textures into your project before you import your model I will avoid the second option for now to avoid troubling the artist. Let's see the third option... 3 If you are using 3D software packages that might not have newer FBX plugins or are importing native files you generally do not have the option to embed media, so you will need to copy the textures into a directory inside your project called textures nested next to the model before you import it e.g. Projectx Assets Models Textures ModelTexture.tga Projectx Assets Models Model.fbx Ok, so I created Assets Models Textures and imported the Guy DIF 512.tga file into it. Then in Assets Models folder I import the Guy.fbx file. Doesn't work. The model still doesn't have textures applied. Alright, so let's look at the first option then. ... Let's look at the first option... 1 If you create your textures in your Unity project to start with and source them from a textures directory nested under Models for example, Unity should always create materials and pick up the textures correctly at import Assets Models Textures Assets Models Uh, isn't this the same as the third option? How do I import my 3D model? I am using Unity 5.


How to get which gameobject the mouse is over in Unity? So I'm working on a simple drag n drop based trading card game for my own amusement. There is a card inspector included. What I want to achieve is to change values in the inspector (which has its own Inspector.cs, so I would change the variables in it) based on which card I hover over with my mouse. Each card has its own Card.cs attached from which I want to read the values of the current card. If I try to do this from within the Inspector.cs by something like this Name.text gameobject.GetComponent lt Card gt ().Name , then obviously it won't work, because using gameobject in the current context is not valid. So solution No1 would be to properly reference the gameobject over which the mouse is, which I don't know how to do. When I try to do the same from within Card.cs, I cannot use an event trigger OnPointerEnter and run the code through that, because I have to have a reference to the gameobject that contains that function. ( And I cannot do that in a prefab, only in gameobject already existing in the level.) So could anyone tell me how I could achieve what I want, please?


2D Platformer Methods to Implement a Whip Weapon I hope posting here isn't a faux pax, if it is please feel free to direct me to the correct location. Or, if there is a thread that already covered this I would love to be pointed in its direction. I've tried looking in quite a few different forums and I can't seem to find very much information about this. What I'm looking to do is implement a whip weapon for a character that's similar to that of Castlevania 4's whip. I have no idea where to start. I'm really just looking for any information. Things like how to program it, the idea of how it was done in the game, really just anything to help me figure out how to make a whip like Castlevania 4. I would appreciate any help. Thank you.


How can I implement the traffic( drawing) functionality in the game? I am a beginner game developer. Games such as "Cities Skyline", "Simcity", "Citybounds", and "Traffic lanes 3" directly build roads and show simulations of cars moving over them. I have no knowledge to make these things. I can use Unity, construct2. How can I express things like roads, lanes, intersections, snapping, traffic simulations, path finding, driver AI, traffic lights, even wheels on the road? Road drawing Traffic simulating


How to limit the speeding up of enemy movement? Is there a way of limiting my speeding my enemy script every time my player collects 10 points. I have a movement script attached to my enemies and every time my player collects 10 points my enemies get faster. I want to put a limit on that so that the movement script (attached to my enemies) doesn't increase all the time even if the player continue to collect 10 more points and onwards. I want the limit to be 40, so even if the player continues to collect another 10 points the movement should stay at 40. This is my speeding up my enemies script (this is used in my score script) if (Score 10 0) Increment movespeed variable from Movement script Movement.movespeed 4 And this is my movement script attached to my enemies public static int movespeed 20 public Vector3 userDirection Vector3.right public float lifetime void Start () Destroy (gameObject, lifetime) public void Update() transform.Translate (userDirection movespeed Time.deltaTime) How can I limit the movement speed so that it doesn't exceed the upper limit I want?


Get world position of touch on objects In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it. How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly? OK one cannot answer the question with the information I provided. In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).


Creating color texture from greyscale heightmap in shader I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects. I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here. Shader "Custom Planet" Properties height("HeightMap", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 struct Input float2 heightMap float minHeight 0 float maxHeight 1 float inverseLerp(float a, float b, float v) return saturate((v a) (b a)) UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float hv inverseLerp(minHeight, maxHeight, IN. heightMap) o.Albedo hv ENDCG FallBack "Diffuse"


Slow down in the same time over different distances I'm trying to slow down a object over different distances in the same time, say 3 seconds. My slow down code is. function lerpSpeed (speed float, lerpSpeedTime float) incomingFlightSpeed flightPathScript.flightSpeed i 0 while(i lt 1) i Time.deltaTime lerpSpeedTime i Mathf.Clamp(i, 0, 1) flightPathScript.flightSpeed Mathf.Lerp(incomingFlightSpeed, speed, i) yield So I call it with. waypointScript.lerpSpeed(1,(totaFlighpointsDistance flightSpeed)) In the picture below I've draw a bezier curve and at the last 8 flight points (the red and yellow spheres) I want to start the slow down from the yellow sphere to the last red sphere. I get the distance in between each of the last 8 flight points and total them up to give me the total distance, I understand to get the time it will take to travel that distance is time total distance speed, but as I'm slowing the speed in my function above this will not work. And because every bezier curve I generate is different, some stretched out, with total distances sometimes ranging from 30 to 8. So I'm a bit stuck here, thought I'd get this one, but unless I'm missing something simple I can't get my head around it, so any help would be greatly appreciated, thanks.


Get MonoBehaviour components from Prefab I need to assign the script values for the following Prefab in Unity 3.5 The structure is the following Kinect Prefab MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script All the components have the same name. I have tried to obtain all of them in an array, but the GetComponents method does not seem to work properly. var mono MonoBehaviour mono Kinect Prefab.GetComponents(MonoBehaviour) The thing is the resulting array is empty. Any idea what might be wrong? EDIT When I do GetComponents(MonoBehaviour) I get the following error InvalidCastException Cannot cast from source type to destination type. I have tried receiving the components in var mono Component but I still don't receive anything


giving to object velocity to the direction it facing (unity) I making 2d game on unity5 .I want to give to an object starting velocity to the direction it is facing(looking).(I put it in the "start" method) how can i do it?


How to use the latest MongoDB C driver with Unity? I recently updated my Unity 2018 to the 2020 version then I created a new project to connect my game to a MongoDB database. My main goal is to be able to store not only common data in my collection but also files and images by using GridFS. I use Visual Studio 2019 Community so for my project. I installed the MongoDB drivers directly from NuGet. In Visual Studio everything is OK, I added a using for all required libraries and I have no errors but when I switch to Unity 2020 it seems that I can't start my project because my MongoDB driver is not correctly loaded there. I found some tutorials like this one where they had the same problem and fixing it by adding the DLLs directly in the Unity folders. That works for me, but only with the DLLs shared in the tutorial (you can access the working DLLs in the video description). What is a bit disturbing is that the DLLs' versions seem to be outdated, since the connections process is a bit different from the one in the MongoDB documentation. I cloned the latest MongoDB C driver repository from GitHub and tried to reproduce the same process with the latest DLLs, but once again it only works in VS 2019 but not in Unity, even though I have added the DLLs in the Unity folder. Is there is some kind of compatibility problem between Unity and the latest MongoDB? How can I fix this to work with the latest version?


Rigidbody has unintended effect, velocity limiter from unknown source I have made a script that alters a rigidbody's angular velocity. It works well but has one issue, its speed plateaus past a certain point. Here is the script void Start() Get references. bat transform.GetChild (0).gameObject rig bat.GetComponent lt Rigidbody gt () Initialize variables. initPos bat.transform.position initAngle bat.transform.rotation.eulerAngles.y if (leftSide) maxAngle bat.transform.rotation.eulerAngles.y 45 rig.centerOfMass bat.transform.localPosition else maxAngle bat.transform.rotation.eulerAngles.y 45 rig.centerOfMass bat.transform.localPosition void Update() if(leftSide) True and false does the same but mirrored effect. if(Input.GetButton ("Left Bat")) button pressed? if(bat.transform.rotation.eulerAngles.y gt maxAngle) lower than max angle?(since this is the mirrored version, its rot starts at 180 and turns CCW, thus the ' gt ') currAngle 1 turnSpeed then allow turning else otherwise currAngle 0f prevent further turning else button not pressed? if(bat.transform.rotation.eulerAngles.y lt initAngle) greater than resting angle?(same reason as above explanation) currAngle 1 turnSpeed then automatically return else otherwise currAngle 0f stop returning bat.transform.rotation Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z)) this statement re aligns the rotation of the flipper its initial state(instantly) to prevent slight kinks due to inconsistencies. bat.transform.position initPos turning the flipper for some reason can deviate its own position(slight but cumulative), this returns the flipper to its initial position. else default version. if(Input.GetButton ("Right Bat")) if(bat.transform.rotation.eulerAngles.y lt maxAngle) currAngle 1 turnSpeed else currAngle 0f else if(bat.transform.rotation.eulerAngles.y gt initAngle) currAngle 1 turnSpeed else currAngle 0f bat.transform.rotation Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z)) bat.transform.position initPos void FixedUpdate() rigidbodies should be processed in fixedupdate I think rig.angularVelocity new Vector3( 0, currAngle, 0) The issue is, no matter how high a value I enter for the movement part, it doesn't get faster than a specific speed. I tried hardcoding a value instead of changing the variable but it didn't make a difference. If I enter a small value, the movement is slower though.


EventSystem.current is null private void OnEnable() Debug.Log(EventSystem.current) EventSystem.current.SetSelectedGameObject(gameObject) Very simple script for selecting a UI element on enable. However, EventSystem.current prints null to the console. Unity 2019.3.15f1 I have an Rewired event system in the scene. Also tried putting this in an IEnumerator and waiting a frame before logging to the console no change.


Is this Possible to force gameobjects (coliders etc) to get stretched based on the aspect ratio of the screen? Well with unity3D, I am in big trouble whenever I use sprites. As for textures I compensate for a evener look by Stretching it (Screen.width amp Screen.height that's fine for low end 2D games). Now If I have an Image and based on content of Image (Let's say I want to add BoxCollider for the walls in image). It works, but for only one aspect ratio. As I am making game for Android. I am having bunch of different resolution amp Aspect ratios. Is this possible to stretch my coliders or other game objects so that I can Work easily???? please help me. I am in a rush (


Unity Event Register Deregister and Scene Unload From what I understand in C , normally when you register an event, it maintains a reference to the object of the containing method, so in order for garbage collection to pick up an object, you need to first deregister it. My question In unity when one scene is loaded and another is unloaded, do I need to first clean up and deregister any registered events, or does the scene unload process destroy objects and remaining references?


Object pooling in Multiplayer Game. Physics not synchronizing well I implemented object pooling for my multiplayer project. Following Unity Manual I used custom spawn handler for shooting bullets. Bullets game object has rigidbody so selected Sync Rigibody 3D in Network Transfrom. My pool size is 5. While shooting when all 5 projectile is shooted then they have to have to come back to initial position one by one that is the concept of pooling. When projectile moving back they just instantly go back to initial position on host but on client their position are lerping and can easily be seen that we are reusing projectile. How will I fix this ? I've added GIF for better understanding Code For SpawnManager where I'am using Custom SpawnHandler public class SpawnManager MonoBehaviour public int m ObjectPoolSize 10 public GameObject m Prefab public GameObject m Pool private Queue lt GameObject gt objectPool public NetworkHash128 assetId get set public delegate GameObject SpawnDelegate(Vector3 position, NetworkHash128 assetId) public delegate void UnSpawnDelegate(GameObject spawned) void Start() assetId m Prefab.GetComponent lt NetworkIdentity gt ().assetId objectPool new Queue lt GameObject gt () for (int i 0 i lt m ObjectPoolSize i) GameObject obj (GameObject)Instantiate(m Prefab, Vector3.zero, Quaternion.identity) obj.SetActive(false) objectPool.Enqueue(obj) ClientScene.RegisterSpawnHandler(assetId, SpawnObject, UnSpawnObject) public GameObject GetFromPool(Vector3 position) GameObject obj objectPool.Dequeue() obj.transform.position position obj.SetActive(true) objectPool.Enqueue(obj) return obj public GameObject SpawnObject(Vector3 position, NetworkHash128 assetId) return GetFromPool(position) Not calling this function yet public void UnSpawnObject(GameObject spawned) Debug.Log("Re pooling GameObject " spawned.name) spawned.SetActive(false) And this is the code where I am calling these function. public class PlayerTest NetworkBehaviour SpawnManager spawnManager private void Start() spawnManager GameObject.Find("Spawn Manager").GetComponent lt SpawnManager gt () private void Update() if (!isLocalPlayer) return if(Input.GetKeyDown(KeyCode.Space)) CmdFire() Command void CmdFire() Set up prefab on server var prefab spawnManager.GetFromPool(transform.position transform.forward) prefab.GetComponent lt Rigidbody gt ().velocity transform.forward 4 spawn prefab on client and server NetworkServer.Spawn(prefab, spawnManager.assetId)


OnRoomConnected always fail (Google play service unity3d) OnRoomConnected always return false, Im stuck...(Authenticate is success). Thank you for attention. private List lt Participant gt participants public void Authenticate() PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder() .Build() PlayGamesPlatform.InitializeInstance(config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate() Social.localUser.Authenticate((bool success) gt if (success) Debug.Log("Authentication succeeded") CreateQuickGame() else Debug.Log("Authentication failed") ) public void CreateQuickGame() const int MinOpponents 2, MaxOpponents 2 const int GameVariant 0 PlayGamesPlatform.Instance.RealTime.CreateWithInvitationScreen(MinOpponents, MaxOpponents, GameVariant, this) region RealTimeMultiplayerListener implementation public void OnLeftRoom() SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnParticipantLeft(Participant participant) SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnPeersConnected(string participantIds) Debug.Log("OnPeersConnected") byte message Encoding.ASCII.GetBytes("Test") build your message bool reliable true PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliable, message) public void OnPeersDisconnected(string participantIds) SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte data) public void OnRoomConnected(bool success) if (success) Debug.Log("Room Connected success") MainScene ms new MainScene() ms.Waithing sprite.SetActive(true) Successfully connected to room! ...start playing game... PlayersNames 0 participants 0 .DisplayName PlayersNames 1 participants 1 .DisplayName PlayersNames 2 participants 2 .DisplayName GenerateBoard() bool reliability true string data "Instantiate 0 1 2" byte bytedata System.Text.ASCIIEncoding.Default.GetBytes(data) PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliability, bytedata) else Debug.Log("Room Connected FAIL") PlayGamesPlatform.Instance.RealTime.LeaveRoom() Loading.text "Error!" Back.SetActive(true) Error! ...show error message to user... public void OnInvitation(Invitation invitation, bool shouldAutoAccept) handle the invitation if (shouldAutoAccept) PlayGamesPlatform.Instance.RealTime.AcceptInvitation(invitation.InvitationId, this) else do some other stuff. public void OnRoomSetupProgress(float progress) Debug.Log("Room Progress Waithing players") List lt Participant gt participants PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants() show the default waiting room. if (participants.Count ! 3) PlayGamesPlatform.Instance.RealTime.ShowWaitingRoomUI() Debug.Log("Room Progress Waithing players") else Debug.Log("Room Progress 100") MainScene ms new MainScene() ms.MoveToGame() PlayersNames 0 participants 0 .DisplayName PlayersNames 1 participants 1 .DisplayName PlayersNames 2 participants 2 .DisplayName


Unity 5.6 Can no longer select empty GameObject with Gizmo in editor Has anyone else noticed this? I'm using the latest version of Unity (5.6.0p2) and it appears Gizmos are no longer selectable by default. Is there any way to restore this behaviour? Some of my objects are essentially empty (no meshrenderer Filter) with a MonoBehavior attached, which require a gizmo drawn sphere so it can be selected. Is there a better more appropriate way of making non mesh gameobjects selectable in the editor that I'm not aware of? I understand I could use Handles to detect a mouse click but this doesn't allow for simple drag selection (marquee tool) if I want to select a load at once.


AI Algorithm to make enemy smarter from level to level in Runner game I am designing a City Runner game in Unity 3D Engine.I am a beginner in game development (not in programming). The idea is really simple, the Runner will be followed by AI enemies, and if caught by one of them it will be dead or his energy will decrease. Anyway I cannot find any Algorithm for implementing a "smart" AI, in the sense that not only he will follow the player and do Path finding to the player, but also get smarter from the first level to the second level. Probably AI must store some information state in regards to the terrain and the runner position. My question here is Is it a good idea to make the AI smarter (because all the runner does is running in a straight line, only the person who is playing the game can change his direction left, right so maybe its not like the learning will be very beneficial) If this is a good idea, do you have any knowledge on what algorithms may be used (implementing neural nets or something alike) If it's not the best idea, what AI mechanism can I use expect of path finding, wandering, seeking, flocking ?? Any kind of advice would be greatly appreciated !! Thank you.


How to correctly combine scoreboard data? I need a help with a scoreboard I am making. Here's the scoreboard I want to achieve I actually have 4 tables and each tables has its own scoreboard but for this question only one table matters. Here's how I am creating this kind of scoreboard if (gametable no 1) for (int i 0 i lt tzPlayInfo.Instance.bc gametable history list.Count i ) newString 0 tzPlayInfo.Instance.bc gametable history list i .r newString 0 "," string groupedString newString 0 .Split(',') foreach (string allchars in groupedString) int x 0 int y 0 GameObject o Instantiate(prefab big road 0 ) as GameObject o.transform.SetParent(pos big road 0 ) o.transform.localScale Vector3.one o.transform.localPosition new Vector3(2.0f, 5.0f, 0f) o.transform.localPosition new Vector3(o.transform.localPosition.x x, o.transform.localPosition.y y, o.transform.localPosition.z) if (allchars.Contains(playerwinnopairboth)) o.GetComponent lt UISprite gt ().spriteName "layout player bigline 01" NGUITools.SetActive(o, true) if (allchars.Contains(bankerwinnopairboth)) o.GetComponent lt UISprite gt ().spriteName "layout banker bigline 01" NGUITools.SetActive(o, true) if (allchars.Contains(tienopairboth)) o.GetComponent lt UISprite gt ().spriteName "layout tie bigline 01" NGUITools.SetActive(o, true) The result I get with this code is this Here's what the data I use to generate the table looks like Gametable 1 history P ,P ,P ,B ,B P,P P,TBP So I need a way to know if the character is changing in the gametable 1 history data. Here's the expected scoreboard output with the data above If the value is not changing like P ,P ,P then the position should only increment on the y axis. If the next value is different like B , then it will move on the x axis. So, how would I implement this?


How do I stop my first person character going through walls? As per my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements using Cursor UnityEngine.Cursor public class FirstPersonController MonoBehaviour public float speed 5 public float jumpPower 4 Rigidbody rb CapsuleCollider col private GameObject player private float minClamp 45 private float maxClamp 45 HideInInspector public Vector2 rotation private Vector2 currentLookRot private Vector2 rotationV new Vector2(0,0) public float lookSensitivity 2 public float lookSmoothDamp 0.1f public Camera cam public GameObject crossHair bool isActive Start is called before the first frame update void Start() Cursor.visible false Cursor.lockState CursorLockMode.Locked rb GetComponent lt Rigidbody gt () col GetComponent lt CapsuleCollider gt () player transform.gameObject crossHair GameObject.FindWithTag("CrossHair") Update is called once per frame void Update() float Horizontal Input.GetAxis("Horizontal") speed float Vertical Input.GetAxis("Vertical") speed Horizontal Time.fixedDeltaTime Vertical Time.fixedDeltaTime transform.Translate(Horizontal, 0, Vertical) if (isGrounded() amp amp Input.GetButtonDown("Jump")) rb.AddForce(Vector3.up jumpPower, ForceMode.Impulse) if (Input.GetKeyDown("escape")) Cursor.lockState CursorLockMode.None if (Input.GetButtonDown("Sprint")) speed 15 Debug.Log("Sprint Button Held Down") if (Input.GetButtonUp("Sprint")) speed 5 Debug.Log("Sprint Button Let Go") if (Input.GetKeyDown(KeyCode.H)) isActive !isActive if (isActive) crossHair.SetActive(true) else crossHair.SetActive(false) rotation.y Input.GetAxis("Mouse Y") lookSensitivity rotation.y Mathf.Clamp(rotation.y, minClamp, maxClamp) player.transform.RotateAround(transform.position, Vector3.up, Input.GetAxis("Mouse X") lookSensitivity) currentLookRot.y Mathf.SmoothDamp(currentLookRot.y, rotation.y, ref rotationV.y, lookSmoothDamp) cam.transform.localEulerAngles new Vector3( currentLookRot.y, 0, 0) private bool isGrounded() return Physics.Raycast(transform.position, Vector3.down, col.bounds.extents.y 0.1f) I can't figure out what I am doing wrong in my code, I tried to write a first person controller from scratch. The full project can be downloaded from https github.com Some T FirstPersonController CSharp My player goes through any wall or object easily despite it having colliders on the objects and a rigidbody and collider on the player. I have gone through my code line by line and I cannot work out what is wrong? If someone could please advise me what to change or add to my code to fix this, or and explain the concept, presumably physics related, as to why this is going wrong please?


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


Unity2D coloring a map I have an image with a bunch of colored regions, with each region corresponding to a province in my game. Each province also has a nation owner, which has a respective color. I need to create a function that, when it is called, changes all pixels of a province's color on the first image and changes them to the owners's color on another image. Should I do this with shaders? A script?


Trying to make a button in Unity which spawns a character each time it's clicked I have a simple 2D game, I want a UI button to respawn the character (if it's not already present). The first problem I encountered is that the button only works once. I can't go any further before I solve this, so for now it doesn't spawn anything, I just want it to print debug text every time it's clicked. It only does that once, unfortunately. How do I make it call the function each time I click it? using UnityEngine using System.Collections using UnityEngine.EventSystems public class Button Restart MonoBehaviour public Canvas Canvas void Awake() public void Restart() Debug.Log("Restart button was clicked") EventSystem.current.SetSelectedGameObject(null)


In unity 5 export package is not working correctly I am using unity 5. I Created an objects with layer names. I tried to export a package. After Exporting, i import the package in new project and ran the project its not working. observed that objects layer name is missing for all the objects. i attached the screenshot with this. Before Export After Import the Exported Package In layer drop down box no layer name was found. only the default layer name is available. if anyone knows the answer please tell me.


Performance of manipulating a mesh in realtime Does Unity allow streaming mesh data that can be continuously changed? I have a level that is dynamically changing based on some parameters. The number of triangles stays the same, they just change positions. I'm speaking of around 2000 triangles that need their position updated each frame (they follow a spline that is computed on CPU), running on mobile phones. I can't use a TrailRenderer because the object is a whole level. I can't use bones, because I need to know the final position for each vertex for my custom collision code. The mesh should be marked Mesh.MarkDynamic.


How can i make all the scene dark night and spot a light on specific place area in the scene? I want to light the area of the 5 spheres. All the rest to be dark. What i have in the Hierarchy is Directional Light. I'm not sure if i need other lights objects and what to do to make it dark night environment and how to spot a light on the specific area.


How do I dynamically load a smaller texture in Unity based on the screen size? I have a Unity application on windows phone which is having problems running on small devices because the HD textures are so huge. What is the best way to test and dynamically use a smaller version on a smaller or less powerful device?


Addressable Asset Loading with Queue And Coroutine I have around 17000 addressable assets (prefab) tiles that I am loading near the position of the camera. Here is my algorithm Get all Reference of the 17000 tiles in the array Loop through the array and get the tiles that are within the proximity of my Player and queue It. Based on the first enqueue item, start downloading the tiles with Addreessabl.Instantiate. Load one by one and wait for the first item download to finish. here is the main loop that is doing the work public IEnumerator StartDownloading() isDownloadStarted true while (singleAbLoader.Count gt 0) SingleADLoader singleAbLoaderCurrent singleAdLoader.Dequeue() if (abLoaderUnloaderManager.GetTilesWithinPlayerRange(singleAbLoaderCurrent) true) Debug.Log( quot Starting to call quot singleAbLoaderCurrent.gameObject.name) yield return singleAbLoaderCurrent.DownloadAB() Debug.Log( quot Finsihed to call quot singleAbLoaderCurrent.gameObject.name) loadingSlider.value sliderIncrementValue else Debug.Log( quot escaping the download quot singleAbLoaderCurrent.name) yield return null isDownloadStarted false whereas the DownloadAD() public IEnumerator DownloadAD() AsyncOperationHandle lt GameObject gt handle Addressables.InstantiateAsync(prefabToLoad) yield return handle The tiles are loading fine but the problem is they are way too slow. I mean it takes much time to load tile.


OnMouseClick not detected I created "main script" and in Start() created simple cube GameObject cube GameObject.CreatePrimitive(PrimitiveType.Cube) cube.transform.localScale new Vector3 (1,2,1) cube.GetComponent lt Renderer gt ().material.color new Color(0,0,255) cube.AddComponent lt CubeScript gt () and then in CubeScript I have empty Start() and Update() but in onMouseDown() just Debug.Log("click detected") and I can never see log despite clicking on cube.. Any advice? did I missed something?


Periodic updates of an object in Unity I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error Update() cannot be a coroutine.) How would I fix this? Would I need a timer system to toggle the collider? var waitTime float 1 var trigger boolean false function Update () if(!trigger) collider.enabled false yield WaitForSeconds(waitTime) if(trigger) collider.enabled true yield WaitForSeconds(waitTime)


Add action to GameObject So I'm creating a Unity project that has a bunch of buttons (like hundreds) that each do a different thing when pressed. This is a 3D project and these buttons are also 3D. I already know how to detect if the player has pressed a button, so I just need to know how to attach an action to one of these buttons. Should I create a script for each? From what I've found, it's very memory expensive and will definitely drop FPS especially for hundreds of buttons. Should I try to use a UnityEvent? I don't know if this helps for what I'm doing...?


Circle Collider Vibrates on Edge Collider I am making a game (kind of bricks) and using edge collider objects as world bounds collider. I am increasing count of balls on each iteration, after 5 balls, balls start to vibrate when they contact with edge colliders. Vibrating means, they do not bounce directly when they contact with edge collider, they vibrate on x axis for some period while they are moving upwards on y axis. Ball physics (friction is 0, bounciness is 1) Wall physics (friction is 0, bounciness is 0) I am not updating transform of ball object, directly set a velocity to balls. Also i've recorded a video for this behavior https www.youtube.com watch?v K bjkXZjXjs amp feature emb logo Which point i am missing on this setup? Can you help me to solve this problem? Best, Edit I have a input listener class, that updates BallThrowHandler.thrown variable, when you put your finger to screen, move and release. Code that adds velocity to balls (which is running on another object) using UnityEngine using System.Collections public class BallContainerBehaviour MonoBehaviour lt summary gt total speed of the balls lt summary gt public float totalSpeed 5f public float timeBetweenBalls 0.2f WaitForSeconds wait public float degrees 0f Rigidbody2D childBody Vector3 speedVector float cosinus float sinus void Start() wait new WaitForSeconds(timeBetweenBalls) void Update() if(BallThrowHandler.thrown) start throw animation startBallMovement() start ball movement if they thrown private void startBallMovement() calculateDegrees() speedUpBalls() if(BallThrowHandler.thrown) StartCoroutine("speedUpBalls") CollectBallHandler.CollectingBallsStarted false BallThrowHandler.BricksMovedDown false private void calculateDegrees() degrees Vector3.Angle(Vector3.right, BallThrowHandler.ThrowVector) Mathf.Deg2Rad private IEnumerator speedUpBalls() cosinus Mathf.Cos(degrees) sinus Mathf.Sin(degrees) speedVector new Vector3(totalSpeed cosinus, totalSpeed sinus, 0f) foreach (Transform go in transform) childBody go.gameObject.GetComponent lt Rigidbody2D gt () childBody.velocity speedVector yield return wait BallThrowHandler.thrown false And here is whole code for a ball object (only bottom collider is trigger, left right and top is not) using UnityEngine using System.Collections public class BallEndTurnBehaviour MonoBehaviour Rigidbody2D body public float ballMinY public GameObject bricksContainer private BrickSpawner brickSpawner private BrickTurnOverMover brickTurnOverMover private const float EPSILON 0.01f private void Awake() body GetComponent lt Rigidbody2D gt () void Start() brickSpawner bricksContainer.GetComponent lt BrickSpawner gt () brickTurnOverMover bricksContainer.GetComponent lt BrickTurnOverMover gt () private void Update() if(System.Math.Abs(body.velocity.x) lt EPSILON amp amp System.Math.Abs(body.velocity.y) lt EPSILON amp amp CollectBallHandler.CollectingBallsStarted) transform.position Vector3.Lerp(transform.position, CollectBallHandler.CollectingBallsPoint, 0.1f) private void OnTriggerEnter2D(Collider2D collision) if (!CollectBallHandler.CollectingBallsStarted) CollectBallHandler.CollectingBallsStarted true CollectBallHandler.CollectingBallsPoint transform.position CollectBallHandler.CollectingBallsPoint.y ballMinY body.velocity new Vector3(0, 0, 0) Vector3.Lerp(transform.position, CollectBallHandler.CollectingBallsPoint, 1f) if(!BallThrowHandler.BricksMovedDown) brickTurnOverMover.moveBricks() BallThrowHandler.BricksMovedDown true brickSpawner.spawn()


Creating a random lottery system I would like the game to give all 16 characters (15 NPC 1 player) a number 1 16. This number stays the same no matter what and is unique only to that character so two characters cannot have the same number. At a point in the game, the character presses a button. I need this button to generate a random number and load a scene based on the number. Example Player's pre determined number is "8", if the number generator generates an "8" as well, it would load the next scene (where the player has to run away from a mob) If the generator generates anything else other than "8" It will load a different scene (where the player chases an NPC) Just to clear it up if the number generator generates 1 7 or 9 16 it will load the same scene no matter what. (Getting "9" from the generator would load the same scene as "2" would. Only when "8" is generated, would there be a separate scene) I'm still incredibly new to Unity and coding in general, so a brief summary of what each line of code is doing would be majorly appreciated! (but not at all demanded!) I'm most comfortable with C so if you could have the code in that would be great!


How to best apply colliders on a rough 3D shape I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D


Unity3d FullScreen Mode Vertical Aspect Ratio in WebGl My game has vertical aspect ratio and looks like this When I press full screen button lt div class quot webgl content quot gt lt div id quot gameContainer quot style quot width 500px height 860px quot gt lt div gt lt div gt lt div class quot fullscreen quot onclick quot gameInstance.SetFullscreen(1) quot gt lt div gt My game start to look like this I need to save aspect ratio of the game how can I do that?


Rotate Rigidbody to face away from camera with AddTorque I have a camera that rotates around an object with "Look At" . I want the object to rotate to face the direction the camera is pointing (Camera.main.transform.forward) using AddTorque, but I can't understand how. I tried to create a rotation in which the more the object's forward vector rotates towards the camera, the more it should slow down the rotation until it stops. But it only works in sections, when I use the rotation of the camera the object rotates and then stops, as if it detects only one part of the rotation, while the other is a blind spot. What equation can I use to rotate the object well? var currentR rb.rotation.y var targetR Camera.main.transform.rotation.y rb.AddTorque(transform.up 1000f (targetR currentR)) DMGregory I put your script as it is in a separate new script on a new object, equipped with a rigidbody. I post the script how I entered it. At "targetOrientation" I gave the value of "Quaternion.LookRotation (Camera.main.transform.forward) " because I want the object to follow the direction of that camera. The result is that all the axes of the rigidbody are influenced by the rotation (if I lift the camera the object turns towards the ground, etc.), and above all that the rotation works even if I block the axes with Freeze Rotation, and with this script the object is no longer affected by external forces. public class rotation MonoBehaviour private Rigidbody rb public Transform direction Start is called before the first frame update void Start() rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() Quaternion targetOrientation Quaternion.LookRotation(Camera.main.transform.forward) Quaternion rotationChange targetOrientation Quaternion.Inverse(rb.rotation) rotationChange.ToAngleAxis(out float angle, out Vector3 axis) if (angle gt 180f) angle 360f if (Mathf.Approximately(angle, 0)) rb.angularVelocity Vector3.zero return angle Mathf.Deg2Rad var targetAngularVelocity axis angle Time.deltaTime float catchUp 1.0f targetAngularVelocity catchUp rb.AddTorque(targetAngularVelocity rb.angularVelocity, ForceMode.VelocityChange) I set a command if (Input.GetKeyDown (KeyCode.T)) rb.AddTorque (transform.up 5500f, ForceMode.Impulse) to rotate the object with an impulse and this does not work when your rotation script is active. I also place a video where you see the object before activating the rotation script, and after it is active, to see how it does not react to the impulse with T, and how it rotates reacting on all rotation axes, while I want only that the rigidbody only rotates its Y axis of rotation, in the direction of the camera (as a person does when turning in one direction). In the video The axes of rotation X and Z are on freeze (otherwise without fixed the rotation the object falls moving). I also put a video of the desired effect taken from a game so as to explain me better. My video desired rotation


Unity UI InputField does not consume the keyboard input Unity UI I have an input field in which I can type. Unfortunately, when I hit any of the movement keys, such as the space bar, I move while I'm typing which is not the effect I want. Is there a way to force the input field to consume the keyboard input so it doesn't also get picked up by the game? Or do I have to write the code in my game to do that for me. (Seems like it should be configurable at least).


differing methods of Instantiating GameObjects in Unity (what is the difference?) I have been using Unity a while and always Instantiated objects slightly differently from what many of the tutorials and posts online say (I've seen 3 very similar ways). It seems to have the same outcome much of the time, however now I am trying to instantiate the prefab using my "Resources" folder instead of dragging it from the inspector and on one method it said it was an 'object' not 'gameobject'. I can't really find anything on Unity website or here, so what is the difference between the following These two lines to me seem identical, but most tutorials dont cast, and rather use the latter of the two instead, why? currentBall (GameObject)Instantiate(Resources.Load(prefabName, typeof(GameObject))) currentBall Instantiate(Resources.Load(prefabName, typeof(GameObject))) as GameObject This one I know is different somehow, because Unity said cannot convert from Object to GameObject, but honestly i do not understand why currentBall GameObject.Instantiate(Resources.Load(prefabName, typeof(GameObject)))


How can I draw a specific GameObject into a texture in Unity? I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure. Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?


Unity IUnityLifecycleManager already exists I followed this tutorial https www.youtube.com watch?v OElh7wda4Qc in Unity version 2019.3.1f.1 Personal Edition, but I got 6 errors like this in the console, also I updated to version 3.4.4 via the package manager, because it said that the asset store version was not compatible anymore. Library PackageCache com.unity.ads 3.4.4 Runtime Monetization AndroidPlacementContentOperations.cs(55,40) error CS0433 The type 'IUnityLifecycleManager' exists in both 'UnityEngine.Advertisements.Editor, Version 3.4.2.0, Culture neutral, PublicKeyToken null' and 'UnityEngine.Advertisements, Version 3.4.2.0, Culture neutral, PublicKeyToken null' This is the code I am using, its the same as the code in the official website, but personalized to my project. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.UI public class adsController MonoBehaviour, IUnityAdsListener public bool testMode true public Button rewardedAd private string storeID "3509232" private string rewardedVideo "rewardedVideo" private void Start() rewardedAd.interactable Advertisement.IsReady(rewardedVideo) rewardedAd.onClick.AddListener(ShowRewardedVideo) Advertisement.Initialize(storeID, testMode) private void Update() private void ShowRewardedVideo() Advertisement.Show(rewardedVideo) Implement IUnityAdsListener interface methods public void OnUnityAdsReady(string placementId) If the ready Placement is rewarded, activate the button if (placementId rewardedVideo) rewardedAd.interactable true public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) Define conditional logic for each ad completion status if (showResult ShowResult.Finished) Reward the user for watching the ad to completion. Debug.Log("Reward") else if (showResult ShowResult.Skipped) Do not reward the user for skipping the ad. Debug.Log("Not Reward") else if (showResult ShowResult.Failed) Debug.LogWarning("The ad did not finish due to an error.") public void OnUnityAdsDidError(string message) Log the error. public void OnUnityAdsDidStart(string placementId) Optional actions to take when the end users triggers an ad. EDIT Looks like I forgot a line in the code and reinstalling the unity ads package now it runs but still gives this warning. Please consider upgrading to the Packman Distribution of the Unity Ads SDK. The Asset Store distribution will not longer be supported after Unity 2018.3


Can I add rigging bones to a model imported from Blender inside Unity? I created a model in Blender but recently I stumbled upon a video claiming that you can add rigging to a model in Unity. So instead of rigging in Blender, is it possible to do it in Unity?


Best Practices for Locating Clicks I am building a 2D board game in Unity with a static camera pointed down at the game board. During the active phase of each player's turn, I want to detect where they click on the board. Fortunately, the board is laid out in an easy rectangular grid. (Essentially a trio of 5x5 grids). Which of the following would be best practice to implement this? Create invisible colliders for every square on the board and create a translation function that translates those back to board positions (5,3) with Raytracing? Get the translated coordinates of the click and use a function to figure out which square (if any) the click is in using the mouseclick event handler (by calculating which square the grid coordinates fall in)? Make each square a button with its grid identity encoded and use that in its OnPressed function? Edit 4) Some other idea I haven't thought of yet? Experience level I'm just learning Unity, but have written a lot of C (and tons of other code).


Recommend a way to draw thousands of particles (liquid) per frame in Unity3d I'm writing a plugin for this library for Unity3d. I have it working and now I am looking for an efficient way to draw the particles. My 1st test just uses sprites and runs fine on my laptop but I doubt it will be so good on a mobile device. Is there a cheap way of simply drawing lots of particles to the screen each frame? The library generates an array of all the particle positions which updates in FixedUpdate() so I can just draw everything in that array each frame. I'm thinking maybe somehting in the Graphics namespace would handy here, like maybe Graphics.DrawTexture Also I might consider doing some kind of metaballs like pass over the particles to make them look more liquid like.


World space UI stretched too much instead of billboard in unity I am scaling my world space UI element as my camera go far away from UI using this code snippet public class ZoomNamePlace MonoBehaviour public CameraController camContrller public int Zoom Factor void LateUpdate() Zoom() void Zoom() float size (Camera.main.transform.position transform.position).magnitude It is working fine and my UI scale according to the distance of Camera and UI. Now i want to rotate billboard my world space UI to the camera and here is my script public class Billboard MonoBehaviour Orient the camera after all movement is completed this frame to avoid jittering void LateUpdate() Camera m Camera Camera.main transform.LookAt(transform.position m Camera.transform.rotation Vector3.forward, m Camera.transform.rotation Vector3.up) But the problem is instead of billboard my UI shape stretched too much maybe due to my canvas scale set to 0.01.


Can I use Unity remote with a Android emulator instead of Android phone? Unity Remote is good app. It allows to connect with Unity while you are running your project in Play mode from the editor. But what if I want to test game but I don't have an Android phone? Yes, it happens ( ) I have a great Android emulator Nox APP Player The emulator doesn't have USB, so it just show me standsrt text Connect device with a USB cable ..... bla bla bla ...Game in the Unity Editor is running...emulator doesn't display the game. Can I somehow connect this emulator to unity using Unity Remote? Or using something else? How?


How do I find more details about a Vuforia error when going into play mode? I want to make an AR app in Unity using Vuforia Engine. But when I try to enter play mode nothing appeared. Here's the error alert Since this error does not give me any clue about what went wrong, I'd like to know if there is a way to get more details about it so I can eventually figure out how to fix it.


Passing Gameobject to another script in unity 3d I'm trying to pass a gameobject from one script to another runtime attached script. My fisrt script is attached to the FirstPlayerController and the gameobject is not dragged in the editor, but is picked up and carried in the script. All i want is to pass the gameobject to the CameraController class to as make the second camera follow that object. Below is what i've tried so far. I dont want to access the gameobject with the tag, because there are more gameobjects that can be picked up. I want to access the carried object to the cameracontroller class. Thanks! Pickupobject.cs using System using System.Collections using System.Collections.Generic using UnityEngine public class pickupobject MonoBehaviour GameObject mainCamera bool carrying public GameObject carriedObject public float distances public float smooth float speed 1000f new Camera camera Use this for initialization void Start() mainCamera GameObject.FindWithTag("MainCamera") camera GameObject.FindWithTag("secondCamera").GetComponent lt Camera gt () camera.enabled false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.T) amp amp carrying) carrying !carrying ThrowBall() if (carrying) carry(carriedObject) else pickup() private void pickup() if (Input.GetKeyDown(KeyCode.E)) int x Screen.width 2 int y Screen.height 2 Ray ray mainCamera.GetComponent lt Camera gt ().ScreenPointToRay(new Vector3(x, y)) RaycastHit hit if (Physics.Raycast(ray, out hit)) pickupable p hit.collider.GetComponent lt pickupable gt () if (p ! null) carrying true carriedObject p.gameObject camera.enabled true camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () void carry(GameObject o) o.GetComponent lt Rigidbody gt ().isKinematic true o.transform.position mainCamera.transform.position mainCamera.transform.forward distances void CheckDrop() if (Input.GetKeyDown(KeyCode.U)) Drop() void Drop() ThrowBall() void ThrowBall() mainCamera.SetActive(false) camera.enabled true carriedObject.AddComponent lt CameraController gt () camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () carriedObject.GetComponent lt Rigidbody gt ().isKinematic false carriedObject.GetComponent lt Rigidbody gt ().AddForce(0f, 0f, speed) CameraController.cs using System.Collections using System.Collections.Generic using UnityEngine public class CameraController MonoBehaviour public GameObject icosphere public GameObject abc Vector3 offset Use this for initialization void Start () icosphere GameObject.FindWithTag("purpleball") offset transform.position icosphere.transform.position Update is called once per frame void Update () transform.position icosphere.transform.position offset


Can not tweak collider s border manually in Unity Why can not I change collider s border manually? I remember being able to do that. I just clicked the gray button under in this case Box Collider 2D component, then went to the Scene view and tweaked it as I wanted by clicking and moving collider s border. But now when I do the same procedure on trying to click and drag the border in Scene view I am just losing focus of the collider, but do not change it in any way.


How to scroll Select objects in the hierarchy tab? So I am creating breakable objects in unity and I have to select around 200 objects in the hierarchy tab so that I can apply some components to each the pieces. My problem is that once I select more than 100 objects in the hierarchy tab, it starts to bug out and it becomes incredible difficult to select objects. So I was wondering if there was a way to a scroll select or something like the box select like you can use on windows to easily select multiple items, or maybe some other way I didn't mention. It would really help me if someone could tell me a quick way to select multiple things in unity, in the hierarchy tab. Thanks, Nova


Animation imported from Maya has interpolation issues I have imported animation from Maya (.fbx) and the curves for the animation in Unity are very different than in Maya. I can clearly notice a flicker for few seconds when I am scaling the object (0 to 1) in loop. The curve for scaling is shown below. The rest in the animation work fine except for the scale. The problem is that Unity adds interpolation automatically to these curves which is why it creates an issue. I have selected the keys in the curves for the scale attribute and quot Both Tangets gt Constant quot , but it did not have any effect. How can I fix this?


(Unity) what happens if i get a transform.position of a nested object Okay so here is the example You have a plane at position 0,0,0 with a scale 15,1,15 (for demonstration) Now you have a parent object for the sake of simplicity lets call it parentObject this parent object has the following position 7,25,26 The parent DOES NOT have a mesh and is thereby an empty gameobject The parent has a child gameobject Here the issue starts the child has a transform position at 5, 25,30 however this objects transform.position is relative to the parent last take our agent i know set him to go to childObject.transform.position will he then move correctly to the object or will he, in fact, move to the position that is relative to the parent object? I know this might seem a bit messy but the general question is if i tell an agent to go to a gameobject that is a child of another object using transform.position will he go to the place we would expect?


Making a surface transparent from blackness of texture I am making a "halo" shader in unity using GLSL. And I've come to a roadblock. What I need to do is take a texture, like the following, and make it transparent according to the darkness of it. And I don't want a cutout, because that cuts it off at a hard edge. This line of code doesn't seem to work. gl FragColor texture2D( vec4( MainTex.r, MainTex.g, MainTex.b, MainTex.a), vec2(textureCoordinates))


unity2D swipe control's bool for animator doesn't work i was trying to make a control where the animation plays upon swiping one direction. each time i've make a tap swipe control, it just keeps popping messages like this. the tap animation works fine, but the animation for swipe controls just doesn't work well, the bool for them has assigned but did not make it 'true' when i swipe a direction, but the bool for the tap works, which is weird.(ignore the miss bool in the animator) it says that i need to assign the anim variable of the Swipe script in the inspector. but there is nothing left for me to assign, which doesn't make much sense for me. (refer to Region Animation) i've tried to make some adjustment with the script, but the results is the same, and it has no problems when build. which is why i need help for the animation stuff. using System.Collections using System.Collections.Generic using UnityEngine public class Swipe MonoBehaviour public Animator anim public bool tap, swipeUp, swipeDown, swipeLeft, swipeRight public bool isDragging false public Vector2 startTouch, swipeDelta private void Update() tap swipeUp swipeDown swipeLeft swipeRight false region Standalone Input if (Input.GetMouseButtonDown(0)) tap true isDragging true startTouch Input.mousePosition Debug.Log("Tapped") else if (Input.GetMouseButtonUp(0)) isDragging false Reset() endregion region Mobile Inputs if (Input.touches.Length gt 1) if (Input.touches 0 .phase TouchPhase.Began) tap true isDragging true startTouch Input.touches 0 .position else if (Input.touches 0 .phase TouchPhase.Ended Input.touches 0 .phase TouchPhase.Canceled) isDragging false Reset() endregion region Animation if (Tap) anim.SetBool("Tap", true) if (SwipeDown) anim.SetBool("Down", true) if (SwipeUp) anim.SetBool("Up", true) if (SwipeLeft) anim.SetBool("Left", true) if (SwipeRight) anim.SetBool("Right", true) endregion calculating the distance swipeDelta Vector2.zero if(startTouch ! Vector2.zero) if (isDragging) if (Input.touches.Length gt 0) swipeDelta Input.touches 0 .position startTouch else if (Input.GetMouseButton(0)) swipeDelta (Vector2)Input.mousePosition startTouch did we cross the deadzone? if (swipeDelta.magnitude gt 125) which direction? float x swipeDelta.x float y swipeDelta.y if (Mathf.Abs(x) gt Mathf.Abs(y)) left or right if (x lt 0) swipeLeft true else swipeRight true else Up or down? if (y lt 0) swipeDown true else swipeUp true public void Reset() startTouch swipeDelta Vector2.zero isDragging false anim.SetBool("Tap", false) anim.SetBool("Down", false) anim.SetBool("Up", false) anim.SetBool("Left", false) anim.SetBool("Right", false) public Vector2 SwipeDelta get return swipeDelta public bool Tap get return tap public bool SwipeUp get return swipeUp public bool SwipeDown get return swipeDown public bool SwipeLeft get return swipeLeft public bool SwipeRight get return swipeRight


Blender assets management and workflow for Unity project I'm trying to decide how to manage my 3D assets, and even how I should construct a world for my game. I should maybe explain, my game is basically a single explorable world set in a school. It's quite large. Every room and building enterable (possibly transitionless), and a large outdoor area (sports field, playground, etc.) I plan to make much of it modular (walls, floors, etc.) The world is somewhat tiled. I've create several different blocks for walls (Straight, cornered, T shaped, cross shaped, door, etc.) which I can place sequentially to create rooms and buildings. I have some blocks lined up in a row in Blender. Now I'm wondering what to do with these pieces... Issue 1) Should I use Unity to place my assets to create my world, or do I create another blender file with all my assets linked? I'm tending towards the latter because I feel I can do a lot more within Blender, but it doesn't appear very easy. However in order for the game to function I'd imagine I'd have to cut up my world into pieces. Problematically I'd also like to use Unity's terrain tool, so if I'm creating a single world object in Blender I'm not sure how I'd do this. Issue 2) I'm not very experienced in 3D game development, I've mainly worked with Flash up until recently. In Flash, you can create movieclips which nest other movieclips. Preferablly I'd like a system as close to this as possible within Blender or Unity. So for instance, I'd like to have a 3D asset of a table. Without affecting the original asset, I want to place objects on the table like books and whatnot, and then control this as a single instance called 'Table with books', maybe duplicate it elsewhere, if I change the position of the books on one it should update all other instances. In Blender, I use alt D to duplicate an object and link it to the original, however it's very easy to duplicate an object without selecting it's children and creating a variety of differently childrened duplicates, which in a vast world which is hard to keep track of, would become a massive headache to deal with. I can just imagine spending hours upon hours correcting a single silly mistake I produced and repeated without noticing for several days. Within Blender I've tried making each wall object it's own group, however they're all in one file and have different xyz positions. I don't want to separate them into dfferent files, in order to create seamless walls I need to have them all in one place. When I create a group instance with shift A, the origin is of the original group object's xyz position I know there's an offset option in the groups panel where I could set it to 2,4,0 to counteract this but I don't like this at all. If I move 10 original grouped objects I have to update each of their offsets! I suppose I could create an empty axis for each wall object, but this also seems an odd way of doing things. Issue 3) Walls are 2 sided objects, the design of one could be different on either side, one could be pink on one side with a skirting board, the other side could be exposed brick work. How would I do this? Lets say I use Unity to position all my assets (which I'm now assuming is probably the right way), ideally I'd like to select a load of walls faces and change their design with a combo box of styles and a color picker in the inspector (a script would be necessary obviously). Sorry, that's a lot of questions for a single post, I hope someone can point me in the right direction.


Road Intersection mesh generation For the last month I was learning about meshes and how procedurally generate them. For what I need it looks very straightforward. For my little app I planning to have a road tool (very simple), user draws lines and curves and road is generated with specific width (flat). So I can now create a drawing tool and generate simple mesh along the curve or line. Next step is to be able to construct intersections... I looked at lots of example but couldn't find any descriptions how it is done. Could you please advice what approach to take, how to identify intersection of two or multiple curves and generate mesh junction? Also could you please advice on bigger picture, should I have sort of underline system for city building app, like graph, to know where to place road intersections, buildings and so on? Thank you This is a quick prototype I did (not in code) https youtu.be 1TxxB ofLAo


Set Parent to Instantiated Objects in Unity i am having problem in attaching parent to the instantiated objects. I have attached the code below. please tell me where i am doing wrong. Thank you. public GameObject brick public Transform BrickHolder public GameObject Bricks void Start() for (float y 2.16f y lt 4.88f y 0.34f) for (float x 2.125f x lt 2.125f x 0.85f) GameObject Bricks Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity) as GameObject if (Bricks ! null) Debug.Log("Hello") Bricks.transform.SetParent(BrickHolder)


Which GameObject should I put the animator on? I have a GameObject. One of its children is an empty GameObject, whose children are the body parts which need to be animated. Character (root) gt Body gt gt Body Parts Should I put the animator on the root GameObject ("Character")? Or on the empty child ("Body")? Does it matter? What benefits would one way offer over the other? Or is there another approach I should be taking? This is for 2D sprites animations. I am trying to figure this out before making all of the animations to avoid redoing them.


Unity Invert Movement Direction I am currently developing a 2,5D Sidescroller in Unity (just starting to get to know it). Right now I added a turn script to have my character face the appropriate direction of movement, though something with the movement itself is behaving oddly now. When I press the right arrow key, the character moves and faces towards the right. If I press the left arrow key, the character faces towards the left, but "moon walks" to the right. I allready had enough trouble getting the turning to work, so what I am trying is to find a simple solution, if possible without too much reworking of the rest of my project. I was thinking of just inverting the movement direction for a specific input key facing direction. So if anyone knows how to do something like that, I'd be thankful for the help. If it helps, the following is the current part of my "AnimationChooser" script to handle the turning Quaternion targetf Quaternion.Euler(0, 270, 0) Vector3 Direction when facing frontway Quaternion targetb Quaternion.Euler(0, 90, 0) Vector3 Direction when facing opposite way if (Input.GetAxisRaw ("Vertical") lt 0.0f) if input is lower than 0 turn to targetf transform.rotation Quaternion.Lerp(transform.rotation, targetf, Time.deltaTime smooth) if (Input.GetAxisRaw ("Vertical") gt 0.0f) if input is higher than 0 turn to targetb transform.rotation Quaternion.Lerp(transform.rotation, targetb, Time.deltaTime smooth) The Values (270 and 90) and Axis are because I had to turn my model itself in the very first place to face towards any of the movement directions.


XInputDotNet not working when building for UWP in Unity I am working on a game where a controller has to vibrate. I have found the XInputDotNet plugin which worked very well in the editor and a normal windows build, but if I build for UWP (both Xaml and D3D) the controller doesn't vibrate. When building in unity for UWP it also gave me an error saying this Plugin 'XInputInterface.dll' is used from several locations Assets Plugins x86 XInputInterface.dll would be copied to lt PluginPath gt XInputInterface.dll Assets Plugins XInputInterface.dll would be copied to lt PluginPath gt XInputInterface.dll Plugin 'XInputDotNetPure.dll' is used from several locations Assets Plugins x86 XInputDotNetPure.dll would be copied to lt PluginPath gt XInputDotNetPure.dll Assets Plugins x86 64 XInputDotNetPure.dll would be copied to lt PluginPath gt XInputDotNetPure.dll Please fix plugin settings and try again. UnityEditor.Modules.DefaultPluginImporterExtension CheckFileCollisions(String) UnityEditorInternal.PluginsHelper CheckFileCollisions(BuildTarget) (at C buildslave unity build Editor Mono Plugins PluginsHelper.cs 25) UnityEditor.HostView OnGUI() The only way I found to remedy this is by deleting one of the plugin folders. I tried manually copying the ddl's to the build folder, but this didn't help. I tried using the 32 bit dll's and the 64 bit dll's, I tried building for x86 and x64 and I tried all three modes in visual studio(Debug,Master,Release). I found some links to the Windows.Gaming.Input namespace, but I dont't know if it is possible to add this namespace to unity and if so how. Does anybody have an idea how to fix my problem?


how can i create a snake with a single piece look I want to create a 3d snake with a single piece look, i have tried separate head and body parts following each other with Vector3.SmoothDamp but some quaternion issues occurred (when y axis gt 90, pieces turning upside). What I want is exactly like in the video https youtu.be uWlMvHU2wfQ Could you tell me the unity components I need to know research? Are the snake models in the video rigged?


How to interpolate colors around the spectrum of hues? I wanted to generate a 7 segment display whose color brightness varies with time, this can be done by just using linear relationship. Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) So in 1 complete second, it produce color in the range of (1,0,0) to (1,1,1) as in the code below using System using UnityEngine public class ClockDigit2 MonoBehaviour static readonly bool , SEGMENT IS ACTIVE new bool , true, true, true, true, true, true, false , 0 false, true, true, false, false, false, false , 1 true, true, false, true, true, false, true , 2 true, true, true, true, false, false, true , 3 false, true, true, false, false, true, true , 4 true, false, true, true, false, true, true , 5 true, false, true, true, true, true, true , 6 true, true, true, false, false, false, false , 7 true, true, true, true, true, true, true , 8 true, true, true, true, false, true, true 9 public Color32 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) var digit number 10 if (digit lt 0) digit 1 for (int i 0 i lt 7 i ) if (SEGMENT IS ACTIVE digit, i ) segments i .color activeColour2 else segments i .color inactiveColour void Update() Display(DateTime.Now.Second) However, now I want to interpolate through all the colors in the circle above over 1 second. I don't know how to express this as a formula for R, G, and B. The RGB value is not linear relationship as you spin the selected color in the chart, you can notice the RGBA components vary together in a nonlinear form. I considered using Lagrangian interpolation. However, this will not be accurate or might fail greatly because if you take a reference point at the circle and assume in 1sec, it made a complete revolution, you will notice there is a certain period of time where the RGB value is constant along the path either 0 and 1. So is there any method to get a formula that perfectly fits the color chart with respect to time?


Why the Render texture is not working when trying to preview a camera on a object? In the editor in Assets right click Create Render Texture Then changed the Render Texture name to SecurityCameraTexture Dimension 2D size 480 x 256 Then created a new material Assets right click Create Material Then changed the material name to SecurityFootage Then changed the material shader from Standard to Mobile Diffuse Then dragged the render texture(SecurityCameraTexture) to the top right image place of the SecurityFootage(material) Next I have a tv object in the scene. In the tv screen I dragged the new material The SecurityCamera. On the SecurityCamera I attached the script that rotate the camera from side to side And the script using UnityEngine using System.Collections public class scr camera MonoBehaviour public float rotate amount Use this for initialization void Start () Update is called once per frame void Update () transform.rotation Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) rotate amount) transform.eulerAngles.y, transform.eulerAngles.z) Last step I did was to drag the render texture(SecurityCameraTexture) to the camera Target Texture. When running the game and watching the tv I don't see the camera preview in the tv. It should the show the camera preview the camera moving from side to side and what the camera is showing. The camera preview was working fine before I started working with the render texture. But it's not showing the preview in the tv.


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?


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


How to represent a modular FSM for AI using ECS? I am considering to implement AI using ECS which actually contradicts working with naive FSMs. My current idea is to have multiple components which represent the particular state an Entity that has a AIControllerComponent is currently in. Let's say an enemy starts out with the mentioned AIControllerComponent as well as a EnemyIdleComponent. Now an EnemyIdleSystem would handle all those idle enemies and if it happens that a player comes too close it'd replace the EnemyIdleComponent with an EnemyChasePlayerComponent leaving the handling of this to EnemyChasePlayerSystem. This approach is rather generic and I would basically end up with a bunch of enemies that have the very same behaviour. I was curious to know how I should combine this approach with some more modular states. At first I thought about adding an enum variable to AIControllerComponent which holds the type of the enemy but I can't really think of a decent solution to call different implementations inside of the EnemyFooSystems based on that particular enum value. Do you have any suggestions? EDIT I am using pure ECS patterns and Jobs, as such MonoBehaviours and non blittable types inside of IComponentData are not usable.


How to apply code of certain script to another? I have a code in my "OnCollider" script to respawn whenever the player dies and has taken an object containing tag 'Respawn'. 1st script OnCollider using System.Collections using System.Collections.Generic using UnityEngine public class OnColllider MonoBehaviour public GameObject Doorfinder public GameObject Door2 public Transform Camera public Transform target public GameObject Coin public bool collided public GameObject Playee public GameObject currentRespawn void Start() Door2 GameObject.Find ("Door0.2") Playee GameObject.Find ("Player") public void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.name "scroll") Destroy (collision.gameObject) Destroy (Doorfinder) if (collision.gameObject.tag "Fire" ) Playee.SetActive (false) if (collision.gameObject.name "PathFinder") Destroy (collision.gameObject) Destroy (Door2) if (collision.gameObject.tag "Coin") Destroy (collision.gameObject) if (collision.gameObject.tag "subVillains") Playee.SetActive (false) if (collision.gameObject.tag "Bramble") Playee.SetActive (false) Respawnable (collision) public void Respawnable (Collision2D collision) if (collision.gameObject.tag "Respawn") collided true collision.gameObject.SetActive (false) if (collided true amp amp Playee.activeInHierarchy false) transform.position currentRespawn.transform.position Playee.SetActive (true) collided false if (currentRespawn.activeInHierarchy false amp amp collision.gameObject.tag "Respawn") currentRespawn collision.gameObject 2nd Script Enemy using System.Collections using System.Collections.Generic using UnityEngine public class MaxyMory MonoBehaviour public Vector2 origin public float distance public int layerMask public float sider public Vector2 secondorigin public float bringer public float lesngther public GameObject destroy public Vector2 origination public float middle public float lengther Use this for initialization void Start () origin new Vector2 (transform.position.x bringer, transform.position.y sider) origination new Vector2 (transform.position.x bringer, transform.position.y middle) secondorigin new Vector2 (transform.position.x bringer, transform.position.y lengther) Update is called once per frame public void Update(GameObject Playee) Debug.DrawRay (origin, Vector2.right distance, Color.red) Debug.DrawRay (secondorigin, Vector2.right distance, Color.cyan) Debug.DrawRay (origination, Vector2.right (distance 30f), Color.gray) RaycastHit2D hit Physics2D.Raycast (origin, Vector2.right, distance) RaycastHit2D anotherhit Physics2D.Raycast (secondorigin, Vector2.right, distance) RaycastHit2D checker Physics2D.Raycast (origination, Vector2.right, distance 2f) if (hit.collider.tag "Player" anotherhit.collider.tag "Player") Playee.SetActive (false) OnCollider is attached to the player while the enemy script is attached to the enemy itself.


Positioning 2D (non UI system) game objects As an old Flash dev I'm slightly confused about how you position game objects on the screen in Unity since game objects have no width or height (only a scale). Let's say I have a container gameobject that has several child game objects with sprite renderers representing tiles on them. If I set the container to x0, y0, the whole tile layout will extend from the screen center upwards and to the right. What are the commonly used ways to position the game object so that it would be centered on the screen? I could calculate the width height of my container but that would still not be very useful because the x y coordinates work in a different scale than pixel (right?). E.g. my test screen is 640x1024 and to center my container (while running in the editor) I'd have to set x y to 4.5. How does that make any sense? Of course Unity's UI system would be a solution but I don't want to create the playfield with the UI system.


Clearing a gizmo list (OnDrawGizmos) I have a list of gizmos in a simple gizmo drawing manager. This list is updated from different parts of the codebase, usually from Update() methods. It goes something like this public class RenderGizmos Singleton lt RenderGizmos gt private List lt GizmoData gt gizmos new List lt GizmoData gt () public void AddNewGizmo(GizmoData gizmos) this.gizmos.AddRange(gizmos) public void AddNewGizmo(GizmoData gizmo) this.gizmos.Add(gizmo) void OnDrawGizmos() if (gizmos null) return for (var i 0 i lt gizmos.Count i ) draw gizmos Can you advise me on when to clear the gizmo list? Ideally I would like to clear it every frame. However Clearing it at the end of the OnDrawGizmos() method will render no gizmos (as I suspect this method might be called several times a frame). Clearing it in an LateUpdate() Update() method is dependent on execution order, sometimes it draws gizmos, sometimes it doesn't Clearing it in a Coroutine has rendered no gizmos (but it might just be dependent on the execution order as well) I would like not to be dependent on the execution order so I prefer not to use the Script Execution Order system.


Unity a ball bounce inside a sphere sometime will penetrate and drop outside i'have made a ball within a sphere (which imported from blender, with mesh collider), see the pic after the scene started, the ball bounce inside around 5 seconds, and then the ball will penetrate (see the arrow) the sphere and drop out of sphere, anyone knows the reasons?


Control the Transform component of an object while the animation is playing It seems the the animation controls the Transform component of the gameobject, hence making it not possible to control the transform properties while the animation is playing. Is there any way to control the Transform component of an object while the animation is playing, like rotating it for example?


Camera stacking for first person view weapon in Universal Render Pipeline I just added URP to my project then upgraded the materials to URP and now it's not rendering the environment anymore I found the problem is that I have 2 cameras which are stacking on each other one with a priority of 1 and the other 0 . The camera that has higher priority is blocking the lower priority camera. How can I fix that? I want to render the higher priority camera on top of the lower priority one.


Unity Logic for saving and loading objects with both static and dynamic data I need help to get some structure for my save and load. I am making a city builder, so I have Buildings thats need to be saved. Each building has a lot of static Data, for example name, description, etc. However it also has a lot of dynamic Data, for example worldPosition, id, etc. My current structure looks like this On each Building GameObject I keep a reference to a ScriptableObject that stores all the static data. I also store a reference to an Object that stores all the dynamic data. This means I need 2 classes for storing Building data, which I already don't like (BuildingStaticData amp BuildingDynamicData) When I Save Load my game I only need to store the Dynamic data, so for saving I just save the DynamicData. For Loading I load the DynamicData, and instantiate a Building GameObject that is associated with it, then the GameObject has the reference to the StaticData. While this works, I would prefer to have a structure where I only have a single class for BuildingData, but I also don't want to lose the power of a ScriptableObject where I can reference other Prefabs etc. I need some help with this logic.


Checkerboard like rendering does not save performance I have a simple scene in Unity with a camera and a quad facing the camera filling the whole viewrect. The quad has a material with the following shader Shader quot Skip quot SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct appdata float4 vertex POSITION struct v2f float4 vertex SV POSITION float4 screenPos TEXCOORD0 v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.screenPos ComputeScreenPos(o.vertex) return o fixed4 frag(v2f i) SV Target int2 screenUV (i.screenPos.xy i.screenPos.w) ScreenParams bool skip (screenUV.x screenUV.y) 2 0 if (skip) return fixed4(1,0,0,1) else fixed4 clr fixed4(0,0,1,1) for (int i 0 i lt 10000 i ) clr i 2 0.5 return clr ENDCG The shader returns simple color for an even pixel and runs an expensive computation for an odd pixel. There is no performance difference between running the expensive operation on all the pixels and running it on just half the pixels. bool skip (screenUV.x screenUV.y) 2 0 13fps bool skip true 2300fps bool skip false 13fps Why is there no improvement in performance?


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