Am I experiencing a gimbal lock problem when rotating my cube? So I'm trying to build a simple mechanic where the player see's 3 sides of a cube at a time top, left and front(I called the front side "Right" in my code, due to the orthographic view). The player can click on the front side or left side of the cube to rotate the cube so that the side that was pressed moves and becomes the top face. I want to smooth animate the rotation. The red faces are the faces that the user can click on. My Logic seems to work quite well when I click on the left face (Rotating along the x axis), but doesn't seem to work well for the front right face(It usually works once and then does weird stuff on the next click, this is on the z axis) public class CubeRotator MonoBehaviour private const float STOP THRESHHOLD 0.1f private const float ROTATE AMOUNT 90f SerializeField, Header("Touch Quads Colliders") private Collider touchQuadLeft SerializeField private Collider touchQuadRight SerializeField, Space(10) private float timeToRotate private bool mustRotateLeft false private bool mustRotateRight false private float targetX 0.0f private float targetZ 0.0f private float xVelocity 0.0F private float zVelocity 0.0F int layerMask private void Start() layerMask LayerMask.GetMask("Touch Quad") void Update() ListenForTouch() RotateCube() private void ListenForTouch() if (Input.GetMouseButtonDown(0)) Vector2 touchPoint Input.mousePosition RaycastHit rayCastHit Ray ray Camera.main.ScreenPointToRay(touchPoint) if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask)) if (rayCastHit.collider touchQuadLeft) mustRotateLeft true targetZ targetZ ROTATE AMOUNT zVelocity 0f else if (rayCastHit.collider touchQuadRight) mustRotateRight true targetX targetX 90f xVelocity 0f private void RotateCube() float zAngle transform.rotation.eulerAngles.z float xAngle transform.rotation.eulerAngles.x if (mustRotateLeft) zAngle Mathf.SmoothDampAngle(zAngle, targetZ, ref zVelocity, timeToRotate) if (Mathf.Abs(zVelocity) lt STOP THRESHHOLD) mustRotateLeft false if (mustRotateRight) xAngle Mathf.SmoothDampAngle(xAngle, targetX, ref xVelocity, timeToRotate) if (Mathf.Abs(xVelocity) lt STOP THRESHHOLD) mustRotateRight false transform.rotation Quaternion.Euler(xAngle, 0f, zAngle) Inspector Values I've tried several things, the only problem I can think of is, gimbal lock. Thanks in advance.


Spot Light color fade in Unity 3d I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight. void Update() if(Time.time() 120 0) transform.light.color new Color(Random.Range(0,255),0,0,1) I know I am missing something big here. Help is appreciated. Thanks in advance.


No Support for UnityScript (JavaScript) on 2018.3 Hey I ve been working on a project for over 3 years and yesterday I have updated the unity from 2018 to 2018.3 and lost support for JavaScript. All of my scripts attached to gameobjects are there but not working while playing the game. I ve tried the UnityScript to C website but didn t work. I m a macOS user so couldn t use the converter tool on git (because it s been developed only for windows). I ll appreciate any suggestions.


Why transform.find() does not need actual object unity I m new to unity and C . I suspect that transform.find() function below does not need actual object reference like player.transform.find() because it transform find is already applied to the gameObject the script is attached to? Am I right? Why transform.find() does not have any game object in front of it? public class PlayerControl MonoBehaviour private Transform groundCheck void Awake() groundCheck transform.Find("groundCheck")


Unity3D and Photon Networking RPG Good time of the day. My question might sound stupid, due to the knowledge you might have, but here it is. I've purchased Diablo 3 a long time ago and been enjoying it since then. Since many of my friend are playing other Blizzard titles, i tried to convince them to purchase Diablo and to play all together. However, they don't want to invest money in the game they don't understand (yet). So i've decided to write a game, which will be similar to the Diablo in the way of interaction and gameplay, but will (obviously) have some unique points in it (since i'm not only doing this for them, but also to educate myself in the game development area). Other this is, i've decided to take Masters in the Game Development (later this march, just got my bachelors in computer security) and wanted to have some basic knowledge about game development. I used to make "RPG" games before, tho only browser style ones using LAMP stack, and have some basic knowledge on storing retrieving data to from server. In order to implement multiplayer part of the game, i've decided to use free package PUN (Photon Unity Networking). Had no problem with creating my first room and spawning a player prefab for every new connection (tho they all move no matter on which client action is performed). Now to the question(s) By using PUN, i'm able to create new room for players (limited to 5), is it possible to set room names BEFORE they are actually initialized by the player? (set of rooms might be stored on MySQL server and retrieved by the API call) Is it possible to save progression of the player on the server, and later pass it back to the spawned player (by PUN). This is my main concern, since i've no actual access to the data processed by the server. (Solution is to create another connection to the "storage" server, and keep both of them "online"?) Does PUN allows you to select which scene should be loaded upon first player entering the room, if so, a bit of pseudo code might be helpful. What will happen to the player, if there is no spots left to join the server (this is just theoretical question, since i'm not going to publish this game, and amount of friends playing games is less than 20) How would one deal with the item equipped, which is received during the gameplay? (This one links to the second question) What i'm talking about is, is it possible to restore player object with the set of data received form the server (if possible, ofcourse) I know, the first suggestion will be to go and to read documentation (i'm in the process of reading it, don't worry). But i've decided to write here, since there are many skilled people out there in this area, who can give me basic understanding on how this whole PUN system works. I would like to thank you for all of the responses, which you are about to post (or maybe not), and again, have a great day.


How can I speed up Unity3D Substance texture generation? I'm working on an iOS Android project in Unity3D. We're seeing some incredibly long times for generating substances between testing runs. We can run the game, but once we shut down the playback, Unity begins to re import all off the substances built using Substance Designer. As we've got a lot of these in our game, it's starting to lead to 5 minute delays between testing runs just to test a small change. Any suggestions or parameters we should check that could possibly prevent Unity from needing to regenerate these substances every time? Shouldn't it be caching these things somewhere?


Unity 3D How to stop reset 2D sprite animation after releasing key? Im following a tutorial to create animations with a 2D sprite character. But i put in my own. Which has 8 animation positions. For some reason when my guy walks around,then stop, the walkings animation continues to play out then resets to idles. I need the animation to reset as soon as i release the key. Im using Animator if you are wondering. EDITED Original video with all the keys for each animations. Youtube video Second video with only 2 keys per animation, it was a test. Second Video Here Code Snipet! using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float speed private Animator animator private Rigidbody2D rigidbody2D Use this for initialization void Start () animator GetComponent lt Animator gt () rigidbody2D GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () CheckDirection() void CheckDirection() if (Input.GetKey (KeyCode.A)) WalkAnimation( 1,0,true) else if (Input.GetKey (KeyCode.D)) WalkAnimation(1,0,true) else if (Input.GetKey (KeyCode.W)) WalkAnimation(0,1,true) else if (Input.GetKey (KeyCode.S)) WalkAnimation(0, 1,true) else animator.SetBool("Walking", false) void FixedUpdate () Move() void Move() float dirX animator.GetFloat("VelX") float dirY animator.GetFloat("VelY") bool walking animator.GetBool("Walking") if (walking) rigidbody2D.velocity new Vector2(dirX,dirY) speed else rigidbody2D.velocity Vector2.zero void WalkAnimation (float x, float y, bool walking) animator.SetFloat("VelX", x) animator.SetFloat("VelY", y) animator.SetBool("Walking", walking)


Can you create input actions using more than one key in the editor with the new Input System? The new input system documentation says it's possible to add actions that require input combinations within the editor or code. I only see an option to add one binding path per action within in the Actions UI. From the documentation ... require the left trigger to be held and then the A button to be pressed and held for 0.4 seconds? var action new InputAction() action.AddBinding(" lt gamepad gt leftTrigger") .CombinedWith(" lt gamepad gt buttonSouth", modifiers "hold(duration 0.4)") Again, setting this up with the inspector in the editor is an alternative to dealing with the path strings directly.


Bold black bar on right side of game in Unity (Android) I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone. Here are the screenshots One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left. Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go. I hope I can get some help. Ask me if you need any piece of code. EDIT "CameraFollow" script using UnityEngine using System.Collections public class CameraFollow MonoBehaviour public GameObject targetObject private float distanceToTarget Use this for initialization void Start () distanceToTarget transform.position.x targetObject.transform.position.x Update is called once per frame void Update () float targetObjectX targetObject.transform.position.x Vector3 newCameraPosition transform.position newCameraPosition.x targetObjectX distanceToTarget transform.position newCameraPosition My "GeneratorScript" using UnityEngine using System.Collections using System.Collections.Generic public class GeneratorScript MonoBehaviour public GameObject availableRooms public List lt GameObject gt currentRooms private float screenWidthInPoints Use this for initialization void Start () float height 0.0f Camera.main.orthographicSize screenWidthInPoints height (Camera.main.targetDisplay) Update is called once per frame void Update () void FixedUpdate() GenerateRoomIfRequred () void AddRoom(float farhtestRoomEndX) int randomRoomIndex Random.Range (0, availableRooms.Length) GameObject room (GameObject)Instantiate (availableRooms randomRoomIndex ) float roomWidth room.transform.FindChild ("floor").localScale.x float roomCenter farhtestRoomEndX roomWidth 3.0f room.transform.position new Vector3 (roomCenter, 0, 0) currentRooms.Add (room) void GenerateRoomIfRequred() 1 List lt GameObject gt roomsToRemove new List lt GameObject gt () 2 bool addRooms true 3 float playerX transform.position.x 4 float removeRoomX playerX screenWidthInPoints 5 float addRoomX playerX screenWidthInPoints 6 float farhtestRoomEndX 0 foreach(var room in currentRooms) 7 float roomWidth room.transform.FindChild("floor").localScale.x float roomStartX room.transform.position.x roomWidth 6.0f float roomEndX roomStartX (roomWidth 13.0f) 8 if (roomStartX gt addRoomX) addRooms false 9 if (roomEndX lt removeRoomX) roomsToRemove.Add(room) 10 farhtestRoomEndX Mathf.Max(farhtestRoomEndX, roomEndX) 11 foreach(var room in roomsToRemove) currentRooms.Remove(room) Destroy(room) 12 if (addRooms) AddRoom(farhtestRoomEndX) (I tried playing with the numbers on GeneratorScript, but nothing seemed to help.


Function Not Storing New Value of Variables? I'm currently building a small scope RPG and running into an issue with modifying variables. My goal is to alter my character's stats when I run a procedure to change their equipment. My code is as follows public class Player MonoBehaviour Base stat variables public static int PAtk 12 public static int PDef 6 Battle exclusive stats. Will have equipment added onto them. public static int Attack PAtk public static int Defense PDef Equipment variables. public string weapon public string armor private void Awake() Get equipment EquipWeapon( quot Bronze Sword quot ) EquipArmor( quot Bronze Armor quot ) void EquipWeapon(string WeaponName) weapon WeaponName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, WeaponName) void EquipArmor(string ArmorName) armor ArmorName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, ArmorName) public class Equipment MonoBehaviour Create dictionary to give each weapon a key ID. This will be used for calling items in another array. Dictionary lt string, int gt WeaponDictionary new Dictionary lt string, int gt () Create weapon array for stats. public int , WeaponStats Start is called before the first frame update void Awake() Declare weapon IDs WeaponDictionary.Add( quot Bronze Sword quot , 0) WeaponDictionary.Add( quot Bronze Armor quot , 1) Declare stat array Table ID, Atk, Def WeaponStats new int , 0,4,0 , 1,0,4 public void EquipStatIncrease(int BaseAtk, int BattleAtk, int BaseDef, int BattleDef, string Equipment) BattleAtk BaseAtk WeaponStats WeaponDictionary Equipment , 1 Debug.Log(BattleAtk quot Battle Power quot ) BattleDef BaseDef WeaponStats WeaponDictionary Equipment , 2 Debug.Log(BattleDef quot Battle Defense quot ) The general gist of it is once EquipWeapon or EquipArmor is ran, the equipment variables in the Player class will be updated. Afterwards, another function in the Equipment class will be ran with variables from the Player class passed over, in order to be modified by the WeaponStats array. The Debug logs in EquipStatIncrease show me that I am getting the desired results. However, the Attack parameter that is being placed into the function is not being permanently modified. During the first execution of the EquipStatIncrease method, I will get a result of 16 BattleAtk and 6 BattleDef, due to the weapon being equipped. However, once it's run a second time to equip the armor, I'm shown a result of 12 BattleAtk and 10 BattleDef, even though BattleAtk should have stayed at 16. This leads me to believe that the variables I'm trying to transform are not being modified, and I'm not sure what to do about this. In the EquipStatIncrease parameters, BattleAtk gives the message Parameter 'BattleAtk' can be removed if it is not part of a shipped public API its initial value is never used However, I don't know what action to take to resolve this. I'm aware of being able to use an int function instead of void, but unless I'm missing something, that only works if I'm trying to change one variable. If I want to have an equipment object that affects 2 different stats at once(ex. a weapon that increases BattleAtk and BattleDef), then I don't see how an int function would work.


How do I install the Unity Editor on Linux? I have installed Unity trough the Hub but still need the editor. I cannot for the life of me figure out how to do that? I'm running a Ubuntu based Linux system. I already have MonoDevelop installed I just need the darn editor. I then get greeted with the following popup but nowhere does it give me the chance to install the editor.


Photon Unity Instantiation not working I use Unity and Photon for the multiplayer. I Instantiate my gameObjects using this method void LoadGameObject(PhotonPlayer player,bool isMaster) if (isMaster) GameObject baby PhotonNetwork.InstantiateSceneObject(babies 0 .name, babies 0 .transform.position, Quaternion.identity, 0,null) baby.SetActive(true) Debug.Log("playerpref created on " player.ID) else Nothing for the moment I call the method in "OnJoinedRoom()" and "OnPhotonPlayerConnected(PhotonPlayer other)", but when the second player join the room, he can't see the gameObjects because they aren't activated on his scene. Any Idea of the mistake ?


Melee Range trigger collider does not detect object with Player tag In my 2D game, I have a Player which has a BoxCollider2D with isTrigger false a dynamic Rigidbody2D a Player script ...tagged as quot Player quot and in the quot Player quot Layer. Also I have an Enemy in the scene which has a BoxCollider2D with isTrigger true an EnemyMelee script ... tagged as quot Enemy quot and in the quot Enemy quot Layer. The Enemy has its own collider because when to handle taking damage or changing colors when shot by the Player's bullets. The Enemy has an empty child game object following it where it goes, called MeleeRange and it has a BoxCollider2D with isTrigger true a kinematic Rigidbody2D an EnemyMeleeAttack script ...tagged as quot MeleeRange quot and in the quot MeleeRange quot Layer. What I want is When Player is inside of the MeleeRange area, the EnemyMeleeAttack script will detect this and call the Coroutine from the EnemyMelee script. I want my Enemy to trigger its quot attackMove quot animation and attack my Player every 1.5 seconds. It has an exit time to the idle animation, and because the Player is still in the MeleeRange collision area, the attack will start again and return to idle again. The problem is MeleeRange simply cannot see the Player tag in the area. I put Debug.Log if it detects the player but nothing happened. EnemyMeleeAttack script public class EnemyMeleeAttack MonoBehaviour public EnemyMelee enemyMeleeScript void OnTriggerEnter2D(Collider2D coll) if(coll.tag quot Player quot ) Debug.Log( quot MeleeRange Collision Reached! quot ) enemyMeleeScript.anim.SetBool( quot isRunningBool quot , false) enemyMeleeScript.StartCoroutine(enemyMelee.attackStance()) EnemyMelee script public class EnemyMelee Enemy region Variables public bool inRange endregion region Attack public float attackTime public float timeBetweenAttacks endregion region Movement with AI public bool isRunningBool public AIPath aipathScript public EnemyMeleeAttack emeleeattackScript endregion public override void Start() base.Start() anim gameObject.GetComponent lt Animator gt () aipathScript gameObject.GetComponent lt AIPath gt () aipathScript.OnTargetReached() private void FixedUpdate() Code for if Enemy dies, disable all functions attached to Enemy. if (health lt 0) GetComponent lt AIPath gt ().enabled false StopCoroutine(attackStance()) DamageColorUpdate() Reference from A Pathfinding for following player and running animations when following occurs. if (aipathScript.reachedEndOfPath false) anim.SetBool( quot isRunningBool quot , true) inRange false else anim.SetBool( quot isRunningBool quot , false) inRange true StartCoroutine(attackStance()) public IEnumerator attackStance() if (Time.time gt attackTime) anim.SetBool( quot isRunningBool quot , false) player.GetComponent lt Player gt ().TakeDamage(damage) attackTime Time.time timeBetweenAttacks anim.SetTrigger( quot attackMove quot ) yield return null


Strange warping shimmering effect with Unity Tilemap and Cinemachine I'm using a Cinemachine Virtual Camera in a 2D project to follow around a target. The ground background is a Unity Tilemap GameObject. As you can see in the gif above (or on Imgur), when following around the player (a 24x24 sprite), the background tiles seem to warp or shimmer a bit. I've tried to script all types of solutions to adjust the Virtual Camera transform position and hopefully snap move it "correctly" to no avail. I don't even know for sure that the source of the issue is with the camera setup. I'm running out of solutions to something that seems like a pretty straightforward and very common scenario. I've created a sample project illustrating the issue which can be downloaded here. Using Unity 2017.3.1f1 Personal. The background sprites are 32x32, with a PPU of 32. No compression, Point (no filter), rendered using a material with Shader Sprites Default, and Pixel snap. Cinemachine Virtual Cam is set to Ortho lens size 16, Body Framing Transposer with default settings. Thank you so much for any suggestions or tips!!! It feels similar to what's being described here with sub pixel movement but I don't know for sure, and the solution in that blog post seems like it should be unnecessary (but again maybe not). I've created camera scripts and attached them to the virtual camera as follows float maxPixelHeight 32 CinemachineVirtualCamera vcam public void Awake() float scale Screen.height maxPixelHeight float orthographicSize (Screen.height scale) 2f vcam GetComponent lt CinemachineVirtualCamera gt () vcam.m Lens.OrthographicSize orthographicSize public void Update() Vector3 tempPos vcam.transform.position Vector3 newPos new Vector3(Mathf.RoundToInt(tempPos.x), Mathf.RoundToInt(tempPos.y), Mathf.RoundToInt(tempPos.z)) vcam.transform.position tempPos I've also tried public void Update() Vector3 tempPos vcam.transform.position Vector3 newPos new Vector3((float)System.Math.Round((decimal)tempPos.x, 2) , (float)System.Math.Round((decimal)tempPos.y, 2), (float)System.Math.Round((decimal)tempPos.z, 2)) vcam.transform.position newPos and something like public void Update() Vector3 tempPos vcam.transform.position vcam.transform.position new Vector3(RoundToNearestPixel(tempPos.x), RoundToNearestPixel(tempPos.y), RoundToNearestPixel(tempPos.z)) public float RoundToNearestPixel(float unityUnits) float valueInPixels unityUnits maxPixelHeight valueInPixels Mathf.Round(valueInPixels) float roundedUnityUnits valueInPixels (1 maxPixelHeight) return roundedUnityUnits


Object array in unity not instantiating properly I'm trying to instantiate my CarMovement class with my population class for a Genetic Algorithm, but when i run the project, the car prefab doesnt spawn. Everything is wired up in the inspector correctly. Anyone know whats going on? Here's the population class using System.Collections using System.Collections.Generic using UnityEngine public class Population MonoBehaviour public int populationSize 10 private CarMovement cars Use this for initialization void Start () cars new CarMovement populationSize for (int i 0 i lt populationSize i ) cars i new CarMovement () cars i .score 1 i Debug.Log (cars i .score) cars 0 .Start() Update is called once per frame void Update () Here's the CarMovement Individual class public class CarMovement MonoBehaviour public float speed 2f public Rigidbody2D rb2d public Vector2 spawnPosition new Vector2((1.0f) 0.1f,3.83f) public int score public GameObject carPrefab Use this for initialization public void Start () rb2d GetComponent lt Rigidbody2D gt () GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity) Debug.Log ("YAAAA") Update is called once per frame public void Update() rb2d.transform.Translate (speed Time.deltaTime, 0, 0)


How can I unregister an event from another scene or another script? This is where and how I register the event void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (Time.timeScale 0) DisableEnableUiTexts(true) SceneManager.UnloadSceneAsync(0) if (fadeImage ! null) fadeImage.SetActive(true) GetGameMusicVolume() Cursor.visible false Time.timeScale 1 else Time.timeScale 0 MenuController.LoadSceneForSavedGame false SceneManager.LoadScene(0, LoadSceneMode.Additive) SceneManager.sceneLoaded SceneManager sceneLoaded Cursor.visible true And the event private void SceneManager sceneLoaded(Scene arg0, LoadSceneMode arg1) I need to be able to unregister the event either from another scene or another script.


How to make an event happen only at the first start of the game? I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again. I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ... So I want to know how to make something happen only once in a game application.. I hope you get my point ... thanks ..


Getting child collider when collision occurs in compound object in unity3d? I have a compound object. The parent of the compound object hierarchy has a script that is listening to the OnTrigerXXX callbacks of the children. When this compound object collides with other objects is there any way to get both colliders? I mean the "other" collider and the collider that belongs to the compound object itself that collided? P.D All rigid bodies must be kinematic, so, I can't use OnCollisionXXXX with the collision info param that has all the information I need in the contacts array. Edit to add a bit more information as Savlon suggested When we are not using compound objects and we want to have a centralized place to handle children collision events, we could have something like this In Children void OnTriggerEnter(Collider c) (parent's script).TriggerHandler(this, c) In Parent public void TriggerHandler(GameObject theChild, Collider c) do stuff This is ok and will work. The "problems" with this way are I could have a lot of children, so, using compound objects I would need to add just a rigid body component to the parent. This could be a pretty good memory reduction usage. However if I don't use compound objects I will have to add a rigid body to every child like in the previous code. In my case children under a parent are always touching. Not intersecing but touching. Think about a set of blocks one beside the other. They do not intersect but there are no gaps between them. With compound objects I don't have to mess with it. It authomatically treats all the children as a whole and no collision callbacks will be fired among them. On the other hand when using compund objects, you get all the advantages listed before but if you need information about what children collided with another collider you won't be able to get it because your script listening to callbacks is in the parent and you will only receive as parameter the "other" collider when unity calls you back through OnTriggerXXXX callback. I was asking if there is any way to get both colliders using a compound object. Hope everything is clearer now. Cheers


Cannot use imported image with Unity's UI controls I know this question sounds banal but its a problem. I received a project and opened it. Now I try to edit it by adding my own images. I do the import but the image does not show up when selecting images, for example, for a button What is the correct folder in this case?


Get the current time of animation using script Unity3d I want to know the current time of the played animation using script in Unity3d. I tried using currentState.normalizedTime but this time is not the time of the animation, like it's the time of the runtime I think. Any advice please?


How can I prevent seams from showing up on objects using lower mipmap levels? Disclaimer kindly right click on the images and open them separately so that they're at full size, as there are fine details which don't show up otherwise. Thank you. I made a simple Blender model, it's a cylinder with the top cap removed I've exported the UVs Then imported them into Photoshop, and painted the inner area in yellow and the outer area in red. I made sure I cover well the UV lines I then save the image and load it as texture on the model in Blender. Actually, I just reload it as the image where the UVs are exported, and change the viewport view mode to textured. When I look at the mesh up close, there's yellow everywhere, everything seems fine However, if I start zooming out, I start seeing red (literally and metaphorically) where the texture edges are And the more I zoom, the more I see it Same thing happends in Unity, though the effect seems less pronounced. Up close is fine and yellow Zoom out and you see red at the seams Now, obviously, for this simple example a workaround is to spread the yellow well outside the UV margins, and its fine from all distances. However this is an issue when you try making a complex texture that should tile seamlessly at the edges. In this situation I either make a few lines of pixels overlap (in which case it looks bad from upclose and ok from far away), or I leave them seamless and then I have those seams when seeing it from far away. So my question is, is there something I'm missing, or some extra thing I must do to have my texture look seamless from all distances?


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


Rendering Mode transparent is not applying in webgl build I am using this method to convert opaque rendering mode to transparent. item.color new Color(1, 1, 1, value) item.SetFloat( quot Mode quot ,3) item.SetOverrideTag( quot RenderType quot , quot Transparent quot ) item.SetInt( quot SrcBlend quot , (int)UnityEngine.Rendering.BlendMode.One) item.SetInt( quot DstBlend quot , (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha) item.SetInt( quot ZWrite quot , 0) item.DisableKeyword( quot ALPHATEST ON quot ) item.DisableKeyword( quot ALPHABLEND ON quot ) item.EnableKeyword( quot ALPHAPREMULTIPLY ON quot ) item.renderQueue (int)UnityEngine.Rendering.RenderQueue.Transparent This is working fine but not working in my webgl build.


Changing handedness coordinate system between unity and opencv For my problem given System A, opencv and unity. I have the Inversed extrinsic parameters in the quot System A convertion quot . Intrinsic parameters (Can form into projectionMatrix) in the quot Opencv convention quot . My first question is When I'm doing the projection. Do i need to convert a convention to have the same direction as opencv then I do the projection. Or I can do it directly without any negated axis?. The step you can see below. I want to set the camera from System A into the unity. What I did is following the image. I rearrange the axis from System A to be the same as Unity. (Rotating Negated the sign) Once it had the same convention to the unity.I took the rotation matrix and use the scipy.transform.as euler(R, order 'zxy'). Then negated the sign the get the angle for left handed. Rotation into Euler angles by using scipy.transfrom.as euler (order of 'zxy' following unity document). Since the scipy accept the right handed coordinate system. Then i will got an angle of rotation. Then negated the axis. Translation I don't know that this should got negated the direction of an axis My second question is I think my procedure is wrong. Since the scipy libs accept the right handed system. So I don't know that how to find the euler rotation angle from given rotation matrix in the right handed system and change it into the left handed system. Thank you very much, Regards, Puntawat Ponglertnapakorn


Trying to Access Components of an Object in another class I think my C is a bit lacking here but I am trying to access a component in a list of objects in another class. I am trying to access UnitController from MultiSelectClient and I'm not sure how to do this. I can remove the objects from the list but I can't seem the access each one even if I try a ForEach loop, I can't wrap my head around it. UnitController.SelectedUnits Is the list I'm trying to access. Ive tried doing UnitController.SelectedUnits.Find FindAll(gameObject) but that returns an error This is where the list is defined public class UnitController MonoBehaviour bool clicked false bool dragging false public float speed 10f public float rotationSpeed 10f public LayerMask groundLayer public NavMeshAgent playerAgent public static Vector3 mouseDownPoint public static Vector3 mouseUpPoint public static Vector3 currentMousePoint public static Rect selection new Rect(0, 0, 0, 0) private Vector3 startClick Vector3.one public Texture2D selectionHighLight public static List lt GameObject gt SelectedUnits public RaycastHit firstRay public RaycastHit secondRay private void Start() SelectedUnits new List lt GameObject gt () This is the script that needs to access it. At least I want to be able to iterate through the list and access each unit in the list and its components. public class MultiSelectClient MonoBehaviour public bool Selected false void Update() if (Input.GetMouseButton(0)) Vector3 camPos Camera.main.WorldToScreenPoint(transform.position) camPos.y Screen.height camPos.y if inside the cameras drag selection area then mark player as selected Selected UnitController.selection.Contains(camPos) Debug.Log("Selected") if (Selected) addTo() else UnitController.SelectedUnits. something UnitController.SelectedUnits.Remove(gameObject)


Pathfinding in a 2D "sidescrolling" strategy game I've been thinking up a real time strategy game that plays on a platformer type of map. The collidable portion of these maps will be made up of square tiles. I've done A pathfinding in top down tile based games before, but I'm unsure how to lay out my tile map in such a way that allows for easy pathfinding. I've thought up some examples, but I'm not sure if it's the right way to go about it, so I thought I'd throw it out here and see if someone who knows what they're doing can give me some tips. The first solution I thought of was to use a 2D array storing all of the tiles and empty space, similar to what I would most definitely do in a top down tile based strategy game. The 2D grid would be invisible in the background but really store whether each grid section is empty, or has a tile on it. like this In this example I'm unsure as to how I would pathfind up hills, or in that specific example, determine that a wall is too high to cross. Lets say that dude can jump over 1 tile high blocks, but 2 tiles is too much. How would I effectively determine that through a pathfinding algorithm? The other example I was thinking of was to place pathfinding nodes on top of traversible terrain, like this Each node might be able to give directions or commands on how to get to the next (Like the need to jump to cross a gap, or it's faster to go under rather than over, etc). Now I would want to do this logically through code, and not manually place them at design time. This might be a better solution, but something I'm thinking of in this game is to have destructable terrain. Say an explosion happens and leaves a big hole like this Suddenly those nodes I placed earlier won't work. I'd need to remake them on the fly. In this case the 2D grid sounds like the better option since I can just flip the value of that tile from full to empty. So hopefully those 2 examples made sense, and I'd like some opinions on which might be the best option, or even if there's some other solution I didn't think about I would be glad to hear it! I'm using Unity if that helps. I just want to get this design choice out of the way early, as it would be a pain to have to tear it apart later. Thanks!


Unity3d Rigidbodies overlap even at low speeds I have an issue that I can't solve. There are many questions relating to similar issues and they come down to "change some settings" and "object is travelling too fast". My problem doesn't seem to equate to either of these. I am running through the basic tutorial for the Breakout Game and have added some of my own tweaks to the code, my issue is that even at low speed my ball overlaps with the bricks, rather than bouncing off them. I have read various related questions but nothing seems to fix this for me. Things I've done Set Project Settings Physics2d Maximum penetration For Overlap 0.0001 Set Ball RigidBody Collision detection to "Continuous Dynamic" . Set Brick RigidBody Collision Detection to "Continuous" Forced a speed limit on the ball of 25 15. Which I think is not fast at all, as most the given solutions are talking about situations arising when the offending object is travelling at much higher speeds. Bricks are standard rigidbody cubes and ball is a standard rigidbody sphere. According to this answer I have also set the rigidbody interpolation to "interpolation" for both ball and bricks. But this seems processor expensive and doesn't solve the issue. As well as set the Project Settings Physics Solver Iteration Count to 25. This does seem to have helped somewhat (ball no longer gets "stuck" inside brick wireframes, but still overlaps). Below are some screenshots of my issue and my code. The only aspect that I can't fully account for is that I've added an acceleration function so when ball is launched it accelerates over a course of several seconds to it's max speed. It's start speed is 8 (although the force applied is actually 1000 when launched, ignore that figure), and the max speed is set to 25 15. I don't know enough to say if this is somehow "breaking" rigidbody overlap detection but it seems pretty silly if so. See line 63 below Ball Source Code using UnityEngine using System.Collections public class Ball MonoBehaviour public float initialVelocity 500f public float accelerationSpeed 5f public float MaximumSpeed 15f private Rigidbody rb private bool ballInPlay false void Awake () rb gameObject.GetComponent lt Rigidbody gt () void Update () if (Input.GetButtonDown("Fire1") amp amp ballInPlay false) transform.parent null rb.isKinematic false rb.AddForce(new Vector3(initialVelocity,initialVelocity,0)) ballInPlay true void FixedUpdate () Gradually increase ball speed if (ballInPlay true amp amp rb.velocity.magnitude lt MaximumSpeed) speedUp() Debug.Log("Ball Speed is " rb.velocity.magnitude) Clamp to maximum speed if (ballInPlay true amp amp rb.velocity.magnitude gt MaximumSpeed) rb.velocity rb.velocity.normalized MaximumSpeed rb.velocity.magnitude void speedUp() This is line 63 rb.AddForce(rb.velocity.normalized accelerationSpeed,ForceMode.Acceleration) Why are the rigidbodies not detecting and preventing overlap?


Grid movement of game units I am trying to achieve a grid movement for a character and enemies. This is what I have so far. public float moveSpeed 5f Rigidbody2D rb public Animator animator Vector2 movement private void Start() rb GetComponent lt Rigidbody2D gt () void Update() animator.SetFloat("Horizontal", movement.x) animator.SetFloat("Vertical", movement.y) animator.SetFloat("Speed", movement.sqrMagnitude) private void FixedUpdate() rb.velocity movement public void MoverHaciaDelante() movement.y 1 moveSpeed public void MoverHaciaAtras() movement.y 1 moveSpeed public void MoverHaciaDerecha() movement.x 1 moveSpeed public void MoverHaciaIzquierda() movement.x 1 moveSpeed public void Parar() movement Vector2.zero And on the part of the enemies I carry this movement system. private Animator myAnim private Transform target SerializeField private float speed SerializeField private float maxRange SerializeField private float minRange void Start() myAnim GetComponent lt Animator gt () target FindObjectOfType lt Player gt ().transform void Update() if(Vector3.Distance(target.position, transform.position) lt maxRange amp amp Vector3.Distance(target.position, transform.position) gt minRange) FollowPlayer() public void FollowPlayer() transform.position Vector3.MoveTowards(transform.position, target.transform.position, speed Time.deltaTime)


Best way to save game data in Unity I am currently developing a game in unity and I want to add some sort of saving system that saves the following Locked unlocked level. The amount of money the player has. Items perks that the player has. As you can see, the data I want to save is global, and has nothing to do with any specific scene. How would you reccomend save this kind of data? I have heard about the EasySave asset but I don't know if it is the right choice it is pretty expensive and I belive that there has to be some easier, cheaper (even free) way to save the data. I'll appreciate any answer or consideration.


How do I create a prefabs when a button is clicked(Unity) So I want to be able to spawn prefabs when a button is pressed Shop script using System.Collections using System.Collections.Generic using UnityEngine public class Shop MonoBehaviour public static string Item01 public static string Item02 public static string Item03 public static string Item04 public static int ShopNum Update is called once per frame void Update() if(ShopNum 1) Item01 quot Cannon quot Item02 quot Tower quot Item03 quot army Camp quot Item04 quot Baracks quot if(ShopNum 2) Item01 quot Archer quot Item02 quot Barbarian quot Item03 quot Goblin quot Item04 quot Wizard quot And then my Shop Access script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Shop01Access MonoBehaviour public GameObject ShopInventory public GameObject Item01Text public GameObject Item02Text public GameObject Item03Text public GameObject Item04Text public GameObject ItemCompletion public GameObject CompleteText void OnTriggerEnter() ShopInventory.SetActive(true) Screen.lockCursor false Shop.ShopNum 1 Item01Text.GetComponent lt Text gt ().text quot quot Shop.Item01 Item02Text.GetComponent lt Text gt ().text quot quot Shop.Item02 Item03Text.GetComponent lt Text gt ().text quot quot Shop.Item03 Item04Text.GetComponent lt Text gt ().text quot quot Shop.Item04 public void Item01() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item01 quot ? quot public void Item02() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item02 quot ? quot public void Item03() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item03 quot ? quot public void Item04() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item04 quot ? quot public void Cancel() ItemCompletion.SetActive(false) How could I spawn a cannon when button item01 is pressed into my 3d scene


Why I cant change the GUILayout.Button color to green when click on a button? I used a break point and it's getting to the line style.normal.textColor Color.green But not changing the color of the clicked button. And there are no any errors or exceptions. using System.Collections using System.Collections.Generic using System.Diagnostics using System.Linq using UnityEditor using UnityEngine using System.IO public class Manager EditorWindow MenuItem("Tools Manager") static void Manage() EditorWindow.GetWindow lt Manager gt () private void OnGUI() var style new GUIStyle(GUI.skin.button) style.normal.textColor Color.red style.fontSize 18 string assetPaths new string 2 string 0 "Test" string 1 "Test1" foreach (string assetPath in assetPaths) if (assetPath.Contains(".test") var i assetPath.LastIndexOf(" ") var t assetPath.Substring(i 1) if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50))) style.normal.textColor Color.green


How can I find when moving the mouse pointer over raw image to what file it belong to? I have on the hard disk some images and saved files. Each image have his saved file. 10 images and 10 saved files Then I'm loading the images to rawimages and when running the game it looks like that This script is loading the images to raw images using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName go.GetComponent lt RawImage gt ().texture thisTexture Update is called once per frame void Update() And the last script is for moving the mouse over the raw images and then it's making each image the mouse cursor is over to be brighter using System.Collections using System.Collections.Generic using System.Drawing using System.Drawing.Imaging using UnityEngine using UnityEngine.EventSystems using UnityEngine.UI public class MouseHover MonoBehaviour public SaveLoad saveLoad public SceneFader sceneFader public RawImagePixelsChange rawImagePixelsChange private bool loadGame false public void OnHover() Debug.Log( quot Enter quot ) rawImagePixelsChange.modifyPixels(0.3f) PlaySoundEffect() loadGame true public void OnHoverExit() Debug.Log( quot Exit quot ) rawImagePixelsChange.restorePixels() loadGame false private void Update() if(loadGame) if (Input.GetMouseButtonDown(0)) StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, quot Game quot )) loadGame false private void PlaySoundEffect() transform.GetComponent lt AudioSource gt ().Play() In this script the MouseHover I want to find and get the save file name the mouse cursor is over the image that belong to the saved file. Either inside the OnHover function or inside the GetMouseButtonDown. Maybe it's be if I will save each image and it's saved file in another folder to identify easier what image belong to what saved file. now the way the images and saved files are on the hard disk each image the saved file to his left are belong to each other they have saved the same time. So when I click the button mouse down in the MouseHover script it should load the specific saved file the mouse cursor is over the image.


Vision Cone for Enemy AI in Unity 2d I am trying to develop an Enemy AI with vision cone in unity 2d top down game, can you please suggest me some approach or sample script, so I can get an idea.


How to instantiate a prefab only when something is hit, and for some seconds? How do I instantiate a prefab only when something is hit for a few seconds? I mean, I just need to activate the particle system when something is hit. Now it always runs, even before I hit something. I need it to activate the particle system when something is hit and for 2 3 seconds. This is what I do now public void Shot() Destroy(gameObject) Instantiate(effect, transform.position, transform.rotation)


Do i need to integrate leader board and achievement in my game and then publish in alpha testing for google play? I'm confused about whether I need to publish my .apk file on Google Play Console with or without achievements and leaderboard. If I publish the game without achievements and leaderboards, then, how can I integrate the google play service at a later date? The first thing I saw was that I should go for alpha publish. Is that necessary? If I do publish the alpha version for the game without including achievements and leaderboard, how can I add these later? In this video, first the game is published without the achievements leaderboard, and later he integrates them. So how does it show results since we didn't include these buttons for leaderboard and achievements?


Inspector stuck on Editor Settings Probably a silly question, but I'm having an issue where I can't view the properties of an object in the inspector window. It seems to be stuck on "Editor Settings". If I click an object I can't view its properties. Any idea what's going on it's confused me for the past 20 minutes.


Can I create new UI elements and use them from Unity? I created the following class, that should be used to display numeric text in a UI canvas (score, lives, etc.) public class NumericField UnityEngine.UI.Text SerializeField int value 0 override protected void Start() base.Start() text value.ToString() public int Get() return value public void Set(int newValue) value newValue text value.ToString() public void Add(int toAdd) Set(value toAdd) Now, I would like to add a NumericField into my Canvas, instead of adding a Text. But, when I right click the Canvas object, I do not see my NumericField. How can I add it to the menus, so that I can add it to the canvas?


How do I make an object destructible? How do I make one of my objects break into random pieces? I've tried Add Ons, Blender, and a few other things that I can't remember of the top of my head.


Unity LoadLevelAdditive and baked light scene settings I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light. So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive). Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ... So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override? Thanks.


How to stop camera rotation after reaching a specific angle? I have a camera in my scene that I want to rotate around the player. The rotation is done when the camera rotation state is at CameraRotation.Left or CameraRotation.Right and CameraRotation.None indicates that the camera should stop rotating and just follow the player. I want the camera to rotate around the player and stop after it reaches a specific angle (180 degrees) in the y axis in the CameraRotation.Left or CameraRotation.Right from the position the camera was at the start of the rotation. It would also be helpful if some direction is given on how to edit the SmoothFollow() method so that it follows the player with the camera still rotated. The problem is I'm not familiar with rotations and not sure whether to use Euler angles or quaternions so any tips would help. private void LateUpdate() if (GameManager. RotateCamera CameraRotation.None) SmoothFollow() else if (GameManager. RotateCamera CameraRotation.Left) transform.RotateAround(player.transform.position, Vector3.up, rotationSpeed Time.deltaTime) else if (GameManager. RotateCamera CameraRotation.Right) transform.RotateAround(player.transform.position, Vector3.down, rotationSpeed Time.deltaTime) Make the Camera follow the player smoothly private void SmoothFollow() Vector3 desiredPoistion player.position offset Vector3 smoothedPosition Vector3.SmoothDamp(transform.position, desiredPoistion, ref velocity, smoothSpeed) transform.position smoothedPosition transform.LookAt(player.transform)


How to get the loudness of the real world environment using the device's microphone in Unity? I am trying to create a game where the character's movement is dependent on the loudness of the real world environment. So if the person playing the game screams or do something loud the character will move accordingly. What I need is a function returning the loudness of the real world environment and use it in the Update() to control the character. Is there such a function or if not how can I make one?


How do you make objects be pushed away from you? like pain from naruto, I wanna be able to press a button and be able to push objects here's my push method void DoPush() Collider colliders Physics.OverlapSphere(transform.position, pushRadius) foreach (Collider pushedObject in colliders) if (pushedObject.CompareTag( quot Enemy quot )) Rigidbody pushedBody pushedObject.GetComponent lt Rigidbody gt () pushedBody.AddForce( transform.forward 500, ForceMode.Force) the problem with this method is when I go behind the objects I push, they go towards me


3D player movement with Unity's new input system So, I trying to get used to the new Unity input system. "Back in the days" I just got the Vertical Horizontal axis, put them into a Vector3, multiplied them by a certain value and then moves the player. Now, with the new input system, that changed quite a bit. So, what I'm trying to do is, to get the input of a 2D Vector, earlier called DPAD in the new system. My approach was, like private void Awake() InputAction.performed ctx gt Movement(ctx.ReadValue lt Vector2 gt ()) InputAction.canceled ctx gt Movement(ctx.ReadValue lt Vector2 gt ()) private void OnMovement(Vector2 dir) moveDirection dir This performed in FixedUpdate private void Move() transform.position moveDirection moveSpeed Time.deltaTime Buut, you know, kinda worked, but not really. The player did unintended things like keep moving or not reacting at all to my button press. Maybe I set something wrong up. You might help me please, thanks!


How to set "useGravity" for Rigidbody to entities in Unity For the position you can use this Inject private ComponentDataFromEntity lt Position gt position But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities?


Behaviour Trees How to clean up when a sequence is interrupted? I'll try to show my problem on a minimal example, in reality it's more complex It's a simple behaviour, that repeats quot an action quot that has a certain animation. If a player gets close, this sequence gets interrupted and the AI executes the quot Flee quot action. The interruption happens because the top level selector is quot dynamic quot which in Unity NodeCanvas means, that its higher priority nodes get executed every frame and if they succeed they interrupt the lower priority ones. My problem is shown via the red arrow if the quot action quot gets interrupted, the clean up (in this case quot stop animation quot ) doesn't execute. What is the best practice to handle the clean up? Is my setup flawed? Or should I just be using a different interrupting mechanism? Thanks for any help!


How to create a high score in Unity from a Time.deltatime float? When I play my game, it sets my score to 0 and does not change, no matter how high my float gets. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class highscore MonoBehaviour public Text Highscore void Start () Highscore.text PlayerPrefs.GetFloat ("Highscore", 0).ToString() This is where the next page starts using UnityEngine using UnityEngine.UI public class Score MonoBehaviour public Text ScoreText public float playerScore 0 void Update () playerScore Time.deltaTime 10 ScoreText.text playerScore.ToString("0") private void OnCollisionEnter (Collision collisionInfo) if (collisionInfo.collider.tag "Obstacle") PlayerPrefs.SetFloat ("Highscore", playerScore)


Using .svg in unity(2D) Creating resolution independent sprites is tough and memory consuming. How can .svg assets be used in unity for any kind of 2d game? What are alternatives to .svg that can be used in unity? Can sprites with various shapes be generated within unity? Would like creating universal art asset that'll support all devices with different resolutions.(we'll handle the aspect ratio )


Component Class Renderer Class I found some code I needed online, but I want to understand how it works. Renderer c (Renderer)b What is this (Renderer)b action called so I can Google about it? It looks like it's trying to get a Renderer instance from b, but isn't b a Component of type Renderer already? Or is this because Renderer is a subclass of Component? void SetTargetInvisible(GameObject Target) Component a Target.GetComponentsInChildren(typeof(Renderer)) foreach (Component b in a) Renderer c (Renderer)b c.enabled false Code is from https forum.unity.com threads how to make all children invisible.27259 Thanks for taking the time!


How to handle multiple enemies with the same script? i'm working on a basic Top Down Shooter, kind of like... Nuclear Throne or The Binding of Isaac, but since i'm new to Unity, and it's something i'm required to do for school, i'm quite in a rush so i didn't have enought time to look at all the documentation i should've, so i apologize if i'm asking too much. The thing is like this I have the Player that moves around, and a Sword that rotates in the mouse direction, clicking the mouse activates a Trigger Collider around the Sword, and it's suposed to Hit all enemies inside its range The problem How should i "plan" my Scripts? i mean, i have a Sword script that handles the click and the OnTriggerEnter, and it should, somehow (Working on it), check if it hit an enemy, and access the Enemy Script to modify its Life Points, but how do handle the GameObject Enemy GameObject.FindObjectWithTag("Enemy") ... ? since this just gives me one enemy... I apologize again since i'm really bad at focusing on one point, i dont think it's neccessary to provide all the code since i dont really need you to provide me with code, just... guidelines or a basic pattern of doing this kind of things. Thank you a lot!.


Reducing disk space needed to use TextMeshPro in AssetBundles My game uses AssetBundles, and quite often each of those bundles use TextMeshPro. The project is at a stage where it would be unwise to change to Addressables. Anyway, I noticed that when a bundle has TextMeshPro involved, it easily adds roughly 2mb to the bundle I assume it's a copy of all the dependencies to make it work. Ideally all bundles should simply point to one copy which is guaranteed to always be present in the game, which I think Addressables sort of does, but as mentioned we cannot use it for this project for various reasons. One way is to create add the TextMeshPro components at runtime (e.g. have some kind of "placeholder dummy" component that, upon Awake() will add TextMeshPro with various preset attributes). That would work fine, and I'm willing to do that but perhaps there are less tedious alternatives (other than Addressables) that I haven't thought of. The goal is to be able to reduce the disk space required for each bundle just because it is using TextMeshPro components.


How to figure out what's moving my GameObject? I have a GameObject as part of a complex scene with a handful of interconnected parts, that's moving when it shouldn't be. I've tried running under the debugger and setting breakpoints on all of the script points that are supposed to move its Transform, and ensured that none of them are firing. There seems to be some "spooky action at a distance" going on, some rogue script doing something I don't want it to be doing, but I can't for the life of me figure out where it is. What I'd really like is some way to set a "breakpoint" on the object's Transform that will break me into the debugger when it gets moved by any script, but that doesn't appear to be supported. Is there any way to figure out exactly what it is that's moving my object around when it shouldn't be? (And before anyone says "trial and error, disable components and see when it stops moving," I already know exactly which component to disable to make it stop moving. Unfortunately, that isn't helping track down the problem because the movement isn't coming directly from that component's MonoBehaviour script.)


Why is my texture array getting only the last link index? Here's my code SerializeField GameObject uitex new GameObject 3 void GetTextureFromServer() string dealer img "" for (int i 0 i lt PlayInfo.Instance.gametablelist.Count i ) dealer img PlayInfo.Instance.gametablelist i .dlrimage dealer img "," Debug.Log("HERE ARE THE LINKS " dealer img) string links dealer img.Split(',') for (int j 0 j lt links.Length 1 j ) Debug.Log("HERE ARE THE NEW LINKS " links j ) new BestHTTP.HTTPRequest(new System.Uri(" amazonaws.com resources " "dealer pic " links j ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt for (int k 0 k lt uitex.Length k ) var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex k .GetComponent lt UITexture gt ().mainTexture tex ).Send() The problem with this code is that it's only getting the last index of my links. What could be the problem on my iteration? Here's an approach that works that shows what the expected behavior is for (int i 0 i lt tzPlayInfo.Instance.bc gametablelist.Count i ) dealer img tzPlayInfo.Instance.bc gametablelist i .dlrimage dealer img "," string newLinks dealer img.Split(',') new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 0 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 0 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 1 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 1 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 2 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 2 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 3 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 3 .GetComponent lt UITexture gt ().mainTexture tex ).Send() It's working perfectly, but now the problem is that it is not very clean code.


How can I get the Selector dialog to include my prefabs When setting a variable for an object in Unity, for built in types there is an option on the right hand side to bring up a dialog that lists the possible values that can be chosen for that variable, for example when selecting a Sprite for a Sprite Renderer Is it possible, and if so what do I need to do, to have that list populated with the prefabs within my project? In this example, there are a number of Item prefabs (both inside and outside the Resources folder if that makes a difference), however they do not appear in that dialog. Is there an attribute I am missing that needs to be specified on the Item class, or something else to enable this? using UnityEngine using System.Collections.Generic public class Item MonoBehaviour, IIdentifiable, IFilterable SerializeField private int IdField SerializeField private bool ActiveField public int Id gt IdField public bool Active gt ActiveField public class ItemRandomiser MonoBehaviour, IWeightedObject SerializeField private List lt string gt NamesField SerializeField private List lt Item gt ItemTemplatesField


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


Latitude and Longitude to Vector3 Not Aligning I am trying to align a marker sphere to certain places on a bigger Earth sphere based on the inputted latitude and longitude. The following is my code for this conversion, this code is based on the code here void createLand() double radius radiusEarth 2 double latitude rad latitude Math.PI 180 double longitude rad longitude Math.PI 180 double xPos (radius Math.Sin(latitude rad) Math.Cos(longitude rad)) double yPos (radius Math.Cos(latitude rad)) double zPos (radius Math.Sin(latitude rad) Math.Sin(longitude rad)) move ObjectMarker to position ObjectMarker.position new Vector3((float)xPos, (float)yPos, (float)zPos) radiusEarth 6371f I am also using a Mercator projection texture for my Earth object. Here is what it looks like for the coordinates of London, UK, 51.509865, 0.118092. As you can see, the marker is in almost the correct position but not quite there. Here is what it looks like for the coordinates of Chennai, India, 13.067439, 80.237617. As you can see here, the marker is completely off, it's been placed somewhere on top of Russia, although it does seem to be directly on top of Chennai. Is there any way I can fix this and make the marker more accurate?


How to make progress bar adapt to various aspect ratios in Unity3d Can anyone help me with this problem I want to make a time progress bar in my game. I have two textures progressBarFrame and progressBar. Currently I'm doing the following void OnGui() GUI.DrawTexture ( Rect(x,y,width,height), progressBar ) It works, but it doesn't adapt to different screen sizes. I also tried this Create GUITexture in the hierarchy and add a texture to it, after adjusting its size and location as I need, progress bar stretches squishes with different aspect ratios and keeps its position relative to other GameObjects (that's what I want). But I don't know how to animate it properly because the figure of the textures is not a simple line.


Keep a rigidbody velocity constant I have a "board" with a ball (rigidbody) moving over it and colliding with obstacles. I want its velocity magnitude to remain constant throughout time. How do I achieve this? What I've tried achieved so far My first guess was to use OnCollisionExit to set the velocity manually, but that lead to weird physics. I don't see how to use AddForce to do this since the previous movement would still be factored. To be clear, what i want is to set the velocity at all times to rigidbody.velocity.normalized x magnitude, where magnitude is a float I set previously. This would allow the physics engine to make all impact math to decide the direction of the ball after the collision, but my math would keep the velocity intact. I then decided to add UpdatedFixed and on every call set the velocity as stated above. It's working, but feels like a bad hack because I'm updating the velocity every frame and forsaking the physics engine.


Ball always showing in Unity Some weird "ball" is showing when I select an element in Unity, preventing me to see the object itself I've tried to hide some layers, but even with all layers hidden it's still here Do you know how to hide this thing? Any idea is greatly welcomed )


why use Resources.Load() in changing the animator controller? I wanted to change the AnimatorController of a gameobject during runtime, and when I searched for the method, it used this code animator.runtimeAnimatorController Resources.Load( quot main colors controllercolors ControllerRED quot ) as RuntimeAnimatorController My question is, why don't we use a public AnimatorController and assign it from the animations folder, then set this equal to the runtimeAnimatorController ... Why use Resources.load? .. What's wrong with making a public variable rather than loading it from the Resources file? I am asking cause no one on the forums or any other websites used the public variable method, which suggests that means that the first way is better. public AnimatorController ac anim.runtimeAnimatorController ac


Download Progress bar from Firebase Storage Im trying to make a progress bar based on downloaded images from Firebase storage, now firebase does provide a snipper which works per image Create local filesystem URL string localUrl quot file local images island.jpg quot Start downloading a file Task task reference.GetFileAsync(localFile, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) task.ContinueWithOnMainThread(resultTask gt if (!resultTask.IsFaulted amp amp !resultTask.IsCanceled) Debug.Log( quot Download finished. quot ) ) but i would like to make that appear on a UI text based on the percentage of the Bytes downloaded like starting from 0 to 100 .Now i have come to this function so far which does work in the sense of downloading from storage and i do get the percentage in the console but im not sure how to convert that to a percentage to show on UI. if (CheckConnectivity) if the device is connected to the internet, initiate download. Debug.Log( quot Initiating download of quot platform file) if (!File.Exists(localPath)) Task task storageRef.GetFileAsync(localPath, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) await storageRef.Child( child).Child( file).GetFileAsync(localPath).ContinueWithOnMainThread(files gt if (!files.IsFaulted amp amp !files.IsCanceled) if download is successful. Debug.Log( quot file saved as quot localPath) else otherwise report error. Debug.Log(files.Exception.ToString()) ) else Debug.Log( quot files Exist quot ) else otherwise don't bother. Debug.Log( quot Cannot Download file due to lack of connectivity! quot ) in which case my debug is this Progress 1731 of 52804 bytes transferred. Which i would like to say 0 and counting up to 100! Thanks!


Mesh Generation In Code My camera looks like this I am trying to add 2D polygons to the screen based on the percentage that they take up of a 1920x1080 pixel canvas. Therefore, I calculate this and then use Camera.ViewportToWorldPoint() to determine the world point for the mesh vertices. Below you can see how I declare vertices and uvs (I am confident my triangles are correct) for the polygon. foreach (var point in poly.path) uv.Add(new Vector2((float)(point.X envelope.left) (envelope.right envelope.left), (float)(point.Y envelope.bottom) (envelope.top envelope.bottom))) I assume this is the correct way to calculate the uvs since they are basically the percentage that vertices lie within the bounds of the polygon's bounding envelope. Here is what I am not so sure on. When I set the vertices like so (assume temp is the array of vertices used) var temp new List lt Vector3 gt () var envelope GetEnvelope() foreach (var point in path) var vect new Vector3((float)(point.X envelope.left) (envelope.right envelope.left), (float)(point.Y envelope.bottom) (envelope.top envelope.bottom), 1.0f) temp.Add(camera.ViewportToWorldPoint(vect)) return temp.ToArray() everything works and the polygon is displayed to my screen except it scales so that the polygon draws as though the viewport is the entire envelope. I expect this, however it is not the functionality I want. So instead I try and declare vertices like so in order to have the polygon displayed in its correct relative position on the screen var temp new List lt Vector3 gt () foreach (var point in path) var vect new Vector3((float)point.X 1920, (float)point.Y 1080, 1.0f) temp.Add(camera.ViewportToWorldPoint(vect)) return temp.ToArray() however when I set the vertices this way, I no longer see the meshes being rendered. My goal with changing the code to this is to have the polygons be their true size on the screen as they are on the 1920x1080 canvas rather than being skewed as they are in the code that I said was working. Am I misunderstanding how vertices and uvs relate? Thank for any help!


How can I wait for all lines and instances to finish moving and then to destroy them? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(startPos, endPos, counter 25f speed) for (int i 0 i lt allLines.Length i ) if (instancesToMove i .transform.position endPos) DestroyImmediate(instancesToMove i ) DestroyImmediate(allLines i ) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) When doing for (int i 0 i lt allLines.Length i ) if (instancesToMove i .transform.position endPos) DestroyImmediate(instancesToMove i ) DestroyImmediate(allLines i ) It's destroying only some of the lines and instancestomove and then give the exception MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.


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 do I load a specific Asset Bundle Manifest, but not the Asset Bundle itself? I have a bunch of Asset Bundles. I load the generic Asset Bundle Manifest to get the names of all of my asset bundles. I want to load only a specific asset from the bundle, but I need to retrieve the names of the assets so I can choose which one. The names of these assets are in the asset bundles manifests associated with each asset bundle. How can I load just the manifest for a particular asset bundle? This is the closest I have come, but it does not work private IEnumerator LoadAssetNames() foreach (var bundleName in assetBundleNames) string url "my server " bundleName ".manifest" var www UnityWebRequest.GetAssetBundle(url) yield return www.Send() if (www.isError) Debug.LogError(www.error) yield break var bundle ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle www.Dispose() assetNames bundleName bundle.GetAllAssetNames() It returns to me a failed to decompress error Error while downloading Asset Bundle Failed to decompress data for the AssetBundle 'my server bundleName.manifest'. I can download the manifest directly as a string or set of bytes, but then how can I cast it to an AssetBundleManifest?


Predicted trajectory becomes less accurate in a side on collision In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball. If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line. However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate. Why is this and how can I fix it? This is the prediction code I use if (Input.GetMouseButton(0) amp amp cueBall) Vector2 mousePos cam.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.CircleCast(cueBall.position, radius, direction, Mathf.Infinity) if (hit) lineMain.Draw(cueBall.position, hit.point) ghostBall.SetPosition(hit.point (direction radius)) lineTarget.Draw(hit.point, hit.point hit.normal) This is the predicted trajectory.


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?


Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.


Unity Event Pause Unpause jump frame Hello, I would like to get in a script the event whenever we click on the pause button, or the Jump frame button. I have already manage the Pause button private void OnEnable() EditorApplication.playmodeStateChanged HandleOnPlayModeChanged private void OnDisable() EditorApplication.playmodeStateChanged HandleOnPlayModeChanged private void HandleOnPlayModeChanged() if (EditorApplication.isPaused) do stuff when the editor is paused. else do stuff when the editor is unpaused But How to get the "jump frame" button ? Thanks !


Blender mesh mirroring screws up normals when importing in Unity My issue is as follows I've modeled a robot in Blender 2.6. It's a mech like biped or if you prefer, it kindda looks like a chicken. Since it's symmetrical on the XZ plane, I've decided to mirror some of its parts instead of re modeling them. Problem is, those mirrored meshes look fine in Blender (faces all show up properly and light falls on them as it should) but in Unity faces and lighting on those very same mirrored meshes is wrong. What also stumps me is the fact that even if I flip normals in Blender, I still get bad results in Unity for those meshes (though now I get different bad results than before). Here's the details Here's a Blender screen shot of the robot. I've took 2 pictures and slightly rotated the camera around so the geometry in question can be clearly seen Now, the selected cog wheel like piece is the mirrored mesh obtained from mirroring the other cog wheel on the other (far) side of the robot torso. The back face culling is turned of here, so it's actually showing the faces as dictated by their normals. As you can see it looks ok, faces are orientated correctly and light falls on it ok (as it does on the original cog wheel from which it was mirrored). Now if I export this as fbx using the following settings and then import it into Unity, it looks all screwy It looks like the normals are in the wrong direction. This is already very strange, because, while in Blender, the original cog wheel and its mirrored counter part both had normals facing one way, when importing this in Unity, the original cog wheel still looks ok (like in Blender) but the mirrored one now has normals inverted. First thing I've tried is to go "ok, so I'll flip normals in Blender for the mirrored cog wheel and then it'll display ok in Unity and that's that". So I went back to Blender, flipped the normals on that mesh, so now it looks bad in Blender and then re exported as fbx with the same settings as before, and re imported into Unity. Sure enough the cog wheel now looks ok in Unity, in the sense where the faces show up properly, but if you look closely you'll notice that light and shadows are now wrong Now in Unity, even though the light comes from the back of the robot, the cog wheel in question acts as if light was coming from some where else, its faces which should be in shadow are lit up, and those that should be lit up are dark. Here's some things I've tried and which didn't do anything in Blender I tried mirroring the mesh in 2 ways first by using the scale to 1 trick, then by using the mirroring tool (select mesh, hit crtl m, select mirror axis), both ways yield the exact same result in Unity I've tried playing around with the prefab import settings like "normals import calculate", "tangents import calculate" I've also tired not exporting as fbx manually from Blender, but just dropping the .blend file in the assets folder inside the Unity project So, my question is is there a way to actually mirror a mesh in Blender and then have it imported in Unity so that it displays properly (as it does in Blender)? If yes, how? Thank you, and please excuse the TL DR style.


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


Unity3D Where to put external files? I want my game to be user translated friendly.I put .text file to Data folder from where strings will be read. What is Editor alternative for data folder ? Also i know compiler ignore some files, how i can tell compiler to include this one ? thanks.


C Events in Unity to separate GameObject features into Components Broadly speaking, this is a question about how to separate my game object's code into distinct feature components that can be added and removed as needed. More specifically, I am trying to achieve this using C events in Unity. But I am open to other solutions. Scenario We have enemies that have health. When their health reaches zero, they die. Some enemies (think asteroids) may spawn a number of child enemies (think smaller astroid pieces) when they die. Others however, just die. I want to have two scripts EnemyHealth Tracks the enemy's health and kills the enemy when its health reaches zero. EnemyChildrenSpawner Spawns child enemies after the enemy's death This way, all enemies will have the EnemyHealth script, and some enemies will have the EnemyChildrenSpawner script in addition. My idea is to have the EnemyHealth script raise an event when the enemy dies, and have EnemyChildrenSpawner subscribe to said event to spawn the children. What would be the best way of achieving this? Here's my attempt. It works. Just not sure if this is good practice, especially using the GetComponent in the second script? EnemyHealth.cs public class EnemyHealth MonoBehaviour The event to invoke when this enemy died public event EventHandler OnDied Gets called when this enemy's health reached zero private void Die() Invoke the died event OnDied?.Invoke(this, EventArgs.Empty) Destroy this enemy EnemyChildrenSpawner.cs public class EnemyChildrenSpawner MonoBehaviour private void OnEnable() GetComponent lt EnemyHealth gt ().OnDied SpawnChildren private void OnDisable() GetComponent lt EnemyHealth gt ().OnDied SpawnChildren private void SpawnChildren(object sender, EventArgs e) Spawn children


Unity Change scene by drag How do I change the scene like you do on common android home screens? I know i could detect if the player swipes to the right and then change the scene but this would not look as smooth as android home screens.


How to get the closest "visible" object from my "player"? I'm using Unity 3d and i have to accomplish the following task get the closest "visible" object to my player in forward direction. It is a sort of radar. I don't know where to start. Any advice is welcomed. Thanks


Get the scene that MonoBehaviour belongs to (multi scene setup) Is there a way to get the scene that a MonoBehaviour component belongs to? The MonoBehaviour is part of a setup with several additivly loaded scenes. What I'm looking for is not the currently active scene but an additionally loaded one.


Rotate player to vector3 point? I want my player object rotate to face vector3 point on terrain. public Vector3 RocketPointer public Transform pointer,Player public bool rocket , button move Update is called once per frame void Update() if (button move true) Ray mouseRay Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit mousePoint if (Physics.Raycast(mouseRay, out mousePoint, 100)) RocketPointer mousePoint.point pointer.transform.position RocketPointer if (button move true amp amp Input.GetMouseButtonDown(0)) rotate player object to face rocketpointer point rocket true button move false if (button move false amp amp Input.GetMouseButtonUp(0)) rocket false public void move button() UI button button move !button move


Frustum culling with a single large object I am helping to optimize performance in a mobile game. The artists who built a particular scene added a wall around the scene. The wall is a single mesh with 100k triangles. Because it goes around the entire scene, at least some of the wall is visible from all angles and is always being rendered. While running the game in the Editor with the Statistics panel enabled, I can see that hiding the GameObject containing the wall always reduces the current number of tris by 100k regardless of how much of the wall is actually visible. Does this mean that the entire wall is always getting rendered, rather than only the triangles that are actually in front of the camera? Obviously the artists need to reduce the overall polygon count of the wall, but I'm wondering if they should also break it into several separate pieces so that the entire wall doesn't need to be rendered at once.


In a JRPG Battle system. Who executes the selected action? Throughout the JRPG history, we've seen the introduction of many a battle system type. Like the classic turn based. The ATB. The action battle system (Most Notable is Kingdom Hearts) In these systems, there's a variety of skill handlers like a queue or gauge to determine turn. My question put simply is who handles the executing of skills? Is it the Battle system? The Players? The Skill queue if there is one? Right now I'm working on an ATB styled Final Fantasy in Unity. I'm leaning towards either the player or the battle system executing the commands. I have my players with each a separate state machine (WAIT, COMMAND, ACTION) And a command queue that holds the queued up actions. I can either have the player in the ACTION state and the battle system process the logic(Execute whatever queued up action). Or the player handle that. Outside of that. I'm curious how it works for the other types of battle systems since I hope others in the future with a similar question can see this.


How to use a .mtl file in Unity? I want to use a .mtl file to draw my objects in unity. Can I somehow convert a .mtl file into a normal Unity material? My .mtl file is like this newmtl phongE1SG illum 4 Kd 0.00 1.00 0.00 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 Ni 1.00 Ks 0.50 0.50 0.50 Is this the same as a Unity material which has the sliders "albedo", "metallic", "smoothness", etc? Or is there any shader to do it?


How to Make a Ladder Climbing Script I'm inexperienced and I'm trying to understand the mechanism for using a ladder with my character or climbing over small walls. To move I use a Rigidbody, not Kinematic, but with AddForce. I tried to create an object to simulate a ladder to climb on. To get my character into contact with the ladder I inserted a Collider trigger on the ladder and called the OnTriggerStay function. After working a bit, I used a bool such that my character can go up or down the ladder when he's close enough, but I don't understand some things. First of all, is the script better to put on the character or create one on the ladder? The second thing is once you get to the top how do I insert a function correctly and make my character complete the climb, making it arrive above the object where the staircase is located? Do I have to get to the top, destroy the game object and respawn at a point just above the ladder? What is the best way to do this? Here's my code private Rigidbody rb public bool ladderClimb false void Start() rb GetComponent lt Rigidbody gt () void Update() if(ladderClimb) directionRot new Vector3(0, 0, 0) direction of rotation movement new Vector3(0, Input.GetAxisRaw( quot Vertical quot ), 0).normalized object movement rb.useGravity false else rb.useGravity true void OnTriggerStay(Collider collider) if(collider.gameObject.tag quot ladder quot ) if(Input.GetKeyUp(KeyCode.E)) ladderClimb !ladderClimb void OnTriggerExit(Collider collider) if(collider.gameObject.tag quot ladder quot ) ladderClimb false


Is it possible to push real world, real time data into Unity? I'm pretty new to this, and I'm having trouble figuring out where to even look. If there's relevant terminology that'll be google able, that would be a great help. Suppose I want to have a monitor in game that displays the output from a camera that's in the same room as the player. Are there libraries for grabbing and rendering that data?


How to prevent cube intersecting with other objects when moved around with mouse? I want to allow the player to freely place cubes anywhere they like in 3D space, but the cube being moved around is not allowed to intersect with other objects. Currently I do a ray cast based on where the mouse is (ScreenPointToRay), and position the cube at the hit point. This allows me to move the cube around, but it's possible to intersect other objects if the raycast hit is right next to an object. I see that there is a Physics.BoxCast method, but I can't get this working based on where the mouse position is. Am not sure if this is even the best solution. I was thinking of ray casting out from each 4 points of each face on the cube (4 up, 4 down, 4 right, 4 left, 4 forward, 4 back), but I feel this is a lot of raycasts just to prevent intersecting on movement and placement for a cube. How can I prevent a cube that is being moved around, and then placed with the mouse from intersecting other objects?


The camera goes up and down when following a rolling sphere I have this CameraController script attached to my camera, to follow a sphere that moves using WSAD. public class CameraController MonoBehaviour public GameObject player private Vector3 offset Start is called before the first frame update void Start() offset transform.position player.transform.position Update is called once per frame void FixedUpdate() transform.position player.transform.position offset It follows the object fine, but it bounces up and down on the Y axis when it's moving, and I don't know how to stop the camera from doing it.


How to enable disable GameObject I have child object with ParticleSystem component. I want to have particles disabled until I press button. I unchecked child object to make it disabled but when I press play it enables automatically(with no scripts attached). Then I made this script below (with .SetActive(false) part only) and it worked. But then I needed to activate it somehow, which I did, but now when I press play, object is automatically enabled activated again. Is there another way of doing this because I need it haha. var particle1 GameObject var particle2 GameObject var particle3 GameObject public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Start() particle1.SetActive(false) particle2.SetActive(false) particle3.SetActive(false) function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) particle1.SetActive(true) particle2.SetActive(true) particle3.SetActive(true)


World position into local position I want to understand how I can convert world position of an object into local position. Especially how to deal with a rotation of objects. I'm testing transform.InverseTransform(...) methods. When parent and child has 0 rotation, this methods easily convert world into local position. I don't know how to deal with a situation, when one of the objects has not zero rotation. In the example below my parent object has (0,0,10) position and (0,0,0) rotation. Child position (0,0,0) and rotation (90,0,0). Debug.Log (string.Format ( quot World position 0 nLocalPosition 1 nInverseTransformPoint 2 nInverseTransformVector 3 nInverseTransformDirection 4 nTransformPoint 5 nTransformVector 6 nTransformDirection 7 quot , transform.position.ToString (), transform.localPosition.ToString (), transform.InverseTransformPoint (transform.position).ToString (), transform.InverseTransformVector (transform.position).ToString (), transform.InverseTransformDirection (transform.position).ToString (), transform.TransformPoint (transform.localPosition).ToString (), transform.TransformVector (transform.localPosition).ToString (), transform.TransformDirection (transform.localPosition).ToString ())) The example debug result World position ( 1.0, 0.7, 10.0) LocalPosition ( 1.0, 0.7, 0.0) InverseTransformPoint (0.0, 0.0, 0.0) InverseTransformVector ( 1.0, 10.0, 0.7) InverseTransformDirection ( 1.0, 10.0, 0.7) TransformPoint ( 2.1, 0.7, 9.3) TransformVector ( 1.0, 0.0, 0.7) TransformDirection ( 1.0, 0.0, 0.7) What should I add to transform.InverseTransformPoint (transform.position) to get transform.localPosition?


Unity 2D Sprite Bending between Hinge Joints I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built in physics, but it doesn't look very good art wise. Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort? I would prefer to keep using multiple game objects to represent the tentacle.