I need to replace the sprite at runtime Unity 2d I need a help, I have some code in Unity that should replace the player's sprite at runtime. But this code does not make it correctly, it does't make the change. Could you help me? Thanks using UnityEngine using System.Collections public class PlayerBehavior MonoBehaviour public enum Skins normal, verde private Skins skinAtual private Rigidbody2D player public float height private Transform posicao public float jumpForce 10f private AudioSource audio public DeathMenu deathMenu private float initialX public float goBackSpeed 10f Object BGMusics private SpriteRenderer sprite public SpriteRenderer sprites public Sprite skinVerde, skinNormal void Start () skinAtual Skins.normal skinAtual Skins.verde sprite GetComponent lt SpriteRenderer gt () player GetComponent lt Rigidbody2D gt () BGMusics Resources.LoadAll ("Music BG") initialX transform.position.x skinVerde Resources.Load lt Sprite gt ("Sprites BOYrECORTADOvERDE") skinVerde Resources.Load lt Sprite gt ("Sprites PersonagemFatiado verde") skinNormal Resources.Load lt Sprite gt ("Sprites PersonagemFatiado") private void UpdateSkin(Sprite novaSprite) foreach (var item in sprites) item.sprite novaSprite void Update () switch (skinAtual) case Skins.normal UpdateSkin (skinNormal) break case Skins.verde UpdateSkin (skinVerde) break default break if (Input.GetKeyDown (KeyCode.Escape)) Pause.INSTANCE.Pausing () if (Pause.isPaused) return if (Application.isEditor) inputComputer () else if(Application.isMobilePlatform) inputMobile () FixePosition () void FixePosition() if (transform.position.x lt initialX) return var newPX Mathf.Lerp (transform.position.x, initialX, Time.deltaTime goBackSpeed) transform.position new Vector3 (newPX, transform.position.y) private void inputMobile() if(Input.GetMouseButtonDown(0)) playerJump () private void inputComputer() if(Input.GetKeyDown(KeyCode.Space)) playerJump () private void playerJump() if (player.transform.position.y lt 8.93000f ) player.AddForce (new Vector2 (0, height jumpForce), ForceMode2D.Impulse) MusicManager.INSTANCE.JumpSound () void PlayRandom() int i Random.Range(0, BGMusics.Length) index sortido AudioClip m (AudioClip) BGMusics i uma referencia ao audioclip sortido GetComponent lt AudioSource gt ().PlayOneShot(m) tocamos esse audioclip void Reset() GetComponent lt AudioSource gt ().playOnAwake false aqui tira o play on awake do audio source CONFIGURANDO OS TRIGGERS E SUAS ACOES void OnTriggerEnter2D(Collider2D col) if(col.gameObject.CompareTag("Heart")) Score.INSTANCE.AddPoints () col.gameObject.SetActive (false) Handheld.Vibrate () TOCAR PlayRandom () else if (col.gameObject.tag "Doctor") MusicManager.INSTANCE.DeathSong () player.gameObject.SetActive (false) Handheld.Vibrate () ToggleEndMenu() void ToggleEndMenu() deathMenu.ToggleEndMenu (Score.INSTANCE.GetScore ()) Send to DeathMenu the Score value


How do I parent an object to a bone in the blender hierarchy? So, I'm trying to make a simple RPG game using Blender and Unity. I would like to have an empty object to be used as a weapon holding position parented to my right hand bone so that I can switch weapons in and out and they'll be able to animate along with my character by being the child of the empty position. The problem I am having is that I can't get the empty position to be a child of the specific right hand bone, only the armature. Is there a way to make this work? Also, if this isn't a good procedure to accomplish what I am trying to do, please enlighten me with the proper way, I'm kind of a noob, thanks.


How to Use Text in Unity3d How Can i Create Text in Unity3D? I Use "3D Text" But Its Always on Top Of Everything! Can You Suggest Anything? I creating a 2D Game So its not Necessarily a 3D Text.. Edit Because I Building a 2D Game My Scene is Full of Planes in Front of Camera And I want My Text to be Over One of the Planes and when plane is moving My Text appears behind it. But When I Use "3D Text" Its Always In Front of Everything. Sorry for My Bad English...


How do i draw a ray in unity So i am trying to scrap together something for vr in which the locomotion is about the player holding the direction where he wants to go to(basically planning what he is going to do)while holding down the button a ray is beeing drawn and when the player lets go the character moves until he reaches the end of the ray i tried looking up something but couldnt find anything regarding something like this


How do I use playerprefs to make ui slider keep the sound settings? I have not use playerprefs before, I want to know how to keep the change of the audio when the player change it throughout the game.


Best Way To Make Responsive UI Buttons in Unity I've been stuck on this for quite some time. I'm trying to make a platformer game for android so I need some touch buttons. I made some buttons in Photoshop but I can't figure out how to make them move the player right. I've tried implementing the IPointerDownHandler interface but once I get the player moving I can't stop it, even if I call a function in OnPointerUp to set the players velocity to a new vector3 where all values are zero. I've also tried attaching event triggers to the buttons I made, but it's the opposite the player only moves for one frame and then I have to press the button again. I don't want to import any assets from the asset store and I don't want to use gui system. I want to learn how to do it myself. Thanks in advance. Here is the script in which I call functions from my PlayerController. using UnityEngine using UnityEngine.UI using UnityEngine.EventSystems using System.Collections public class LeftButton MonoBehaviour, IPointerDownHandler, IPointerUpHandler public Image leftButton private PlayerController player private void Start() leftButton GetComponent lt Image gt () player FindObjectOfType lt PlayerController gt () public virtual void OnPointerDown(PointerEventData ped) Debug.Log("LeftButton Pressed!!") player.moveLeft ( 2) public virtual void OnPointerUp(PointerEventData ped) player.stopMoving () Debug.Log ("Button Lifted!!") Here is my PlayerController script. using UnityEngine using System.Collections public class PlayerController MonoBehaviour private Rigidbody2D myrb Use this for initialization void Start () myrb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () public void moveLeft(float moveSpeed) myrb.velocity new Vector3 (moveSpeed, myrb.velocity.y, 0f) public void moveRight(float moveSpeed) myrb.velocity new Vector3 (moveSpeed, myrb.velocity.y, 0f) public void stopMoving() myrb.velocity new Vector3 (0f, 0f, 0f)


Smoothly resize minimap camera rect width and height I have an orthographic camera that is working as a mini map. Now I want to make it resizeable using mouse drag. I have applied some UI beside my minimap camera rect and those UI resizing perfectly with this code. But I have no clue that how to resize my camera rect with mouse drag void Awake() rectTransform transform.GetComponent lt RectTransform gt () public void OnPointerDown(PointerEventData data) if (!resizePanelFeatureActive) return rectTransform.SetAsLastSibling() RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition) public void OnDrag(PointerEventData data) if (!resizePanelFeatureActive) return if (rectTransform null) return Vector2 sizeDelta rectTransform.sizeDelta RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out currentPointerPosition) Vector2 resizeValue currentPointerPosition previousPointerPosition sizeDelta new Vector2(resizeValue.x, resizeValue.y) sizeDelta new Vector2( Mathf.Clamp(sizeDelta.x, minSize.x, maxSize.x), Mathf.Clamp(sizeDelta.y, minSize.y, maxSize.y) ) rectTransform.sizeDelta sizeDelta previousPointerPosition currentPointerPosition


How can "Box Collider is trigger" apply to the Player, not the enemies (make them collide, not pass through)? So, in my game, the Powerup (capsule) has a RigidBody and a Box Collider. I ve set the Box Collider to is trigger . When the player hits the powerup, it disappears just as it s supposed to. Is it possible to let the enemies collide with the powerup (bump into it) instead of just passing through it? From the Enemy script void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") Update is called once per frame void Update() if (player ! null amp amp gameManager.isGameActive) enemyRb.AddForce((player.transform.position transform.position).normalized speed) if (transform.position.y lt 4) Destroy(gameObject) gameManager.UpdateScore(pointValue) From the PlayerController script private void OnTriggerEnter(Collider other) if (other.CompareTag("Powerup")) hasPowerup true Destroy(other.gameObject)


Voxel Lighting in Unity3D I'm working on a Voxel project in Unity3D for fun and learning. I've been reading up on how this is done and have implemented a simple Voxel map in my project. My question is about the lighting. I've read several articles on how Minecraft implemented lighting. It doesn't seem too complicated but I'm wondering if it's necessary in Unity (and also I'm unsure how I would actually implement that in Unity) So far I'm just using Point Lights on blocks that should emit light. Is Unity's Point Light efficient enough on a Voxel map if there are many light sources? So far on my scene it works OK with several lights on it. Adding many lights slows down the game as expected but since my computer is not a gaming beast I don't know if it's because Unity's Point Light is not optimized for this type of map or if it's just due to my low end computer. (To give you a point of comparison, I run Minecraft with a lot of lag but Eldritch with absolutely no lag, if you're familiar with both those games) I would like some thoughts from more experienced users on this subject. If you had to develop a Voxel game in Unity, that may include 100 torches and 100 cubes of glowing lava, would you just use the Point Lights? If the answer is no, is playing with the RGB values of the block textures the way to go?


Getting grid coordinates of cells bordering a square region I have a board that is 4x4 ( the blue cells) with the origin (0 , 0) being in the bottom left for example, how can I get the coords which are adjacent to the board (the red cells) to store them in an array?


Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop? using System.Collections using System.Collections.Generic using UnityEngine public class Spin MonoBehaviour public Vector3 targetRotation public float duration public bool spinInUpdate false Start is called before the first frame update void Start() if (spinInUpdate false) StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration)) Update is called once per frame void Update() if (spinInUpdate true) transform.Rotate(new Vector3(0, 1, 0)) IEnumerator LerpFunction(Quaternion endValue, float duration) float time 0 Quaternion startValue transform.rotation while (time lt duration) transform.rotation Quaternion.Lerp(startValue, endValue, time duration) time Time.deltaTime yield return null transform.rotation endValue slant I mean this is how it's rotating with the Coroutine the small cube that rotate is in slant When using the Update way it's rotating fine and this is how it should rotating also with the Coroutine for example on the X only The small cube when rotating either in update or in the Coroutine should not be slant. but it's slant in the Coroutine. And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ? About controlling the speed in the Update I just added a global float variable and in the Update transform.Rotate(new Vector3(0, Time.deltaTime rotationSpeed, 0)) and it's working for the speed.


Unity hangs when saving prefab asset For game saving purposes, I'm keeping track of references to ScriptableObjects through a lookup table, so that I can serialize deserialize using the SO's position in that table. I have a lot of individual SOs that I want to be able to serialize, so I wrote an editor script to populate that table automatically. The table exists in a MonoBehaviour on a prefab. Originally, I wasn't saving the prefab, because in the inspector it looked like the changes were successfully applying. However, those were showing in memory changes when you open the asset, the changes don't exist. The problem is, when I added the line to save the asset (PrefabUtility.SavePrefabAsset) Unity started hanging at the end of every import while showing that it was importing SO Lookup Table. I feel like I'm missing something obvious here, but Google hasn't been any help. What's wrong with my code? Here's the editor script. Every time assets finish loading, it adds any ScriptableObjects that aren't in the lookup table and exist in one of the specified directories, and removes any that were deleted from or moved out of those directories. public class SOLookupTableAutoPopulator AssetPostprocessor const string SO LOOKUP TABLE PATH quot Assets Prefabs SO Lookup Table.prefab quot every ScriptableObject in these directories is automatically added to the lookup table prefab static readonly string DIRECTORIES TO TRACK new string quot Assets ScriptableObjects ExampleDirectory1 quot , quot Assets ScriptableObjects ExampleDirectory2 quot static void OnPostprocessAllAssets (string importedAssets, string deletedAssets, string movedAssets, string movedFromAssetPaths) var lutPrefab AssetDatabase.LoadAssetAtPath(SO LOOKUP TABLE PATH, typeof(GameObject)) as GameObject var soLookupTable lutPrefab.GetComponent lt SOLookupTable gt () remove first in case asset moved between two tracked directories foreach (var path in pathsInTrackedDirectories(deletedAssets.Concat(movedFromAssetPaths))) soLookupTable.LookUpTable.RemoveAll(o gt o.Path path) var toAdd pathsInTrackedDirectories(importedAssets.Concat(movedAssets)) .Where(p gt AssetDatabase.GetMainAssetTypeAtPath(p).IsSubclassOf(typeof(ScriptableObject))) foreach (var path in toAdd) if (!soLookupTable.LookUpTable.Any(o gt o.Path path)) soLookupTable.LookUpTable.Add(new ScriptableObjectPathTuple(path)) PrefabUtility.SavePrefabAsset(lutPrefab) static IEnumerable lt string gt pathsInTrackedDirectories (IEnumerable lt string gt pathList) return pathList.Where(p gt DIRECTORIES TO TRACK.Any(d gt p.StartsWith(d))) The lookup table looks like this public class SOLookupTable MonoBehaviour public List lt ScriptableObjectPathTuple gt LookUpTable public int GetID (ScriptableObject so) return LookUpTable.FindIndex(o gt o.Asset so) public ScriptableObject GetSO (int id) return LookUpTable id .Asset And here's the class that the lookup table contains. I track the path in addition to the asset itself for the deletion phase of OnPostprocessAllAssets you can't retrieve an asset from a path that points to a deleted asset. Serializable public class ScriptableObjectPathTuple public ScriptableObject Asset public string Path public ScriptableObjectPathTuple (string path) Path path Asset AssetDatabase.LoadAssetAtPath(path, typeof(ScriptableObject)) as ScriptableObject


Animate a 3D boss with some parts that become independant I would like to create a boss but first, I want the player to fight the head. Then the head flies to the body and becomes attached to it. Later, the boss will throw an arm to the player and the arm will chase the player, becoming independent with its own AI. Do I have to render 3 models separatly? (The head one arm the body) If I do this, how am I supposed to animate the complete body when everything is attached together? Do I have to render the 3 models (The head one arm the body) 1 model without the arm (Head body) 1 model with everything attached? If so, how do I handle animations with these 5 models?


How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction? Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead. It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre existing momentum will carry it wildly off course, and not straight toward PointB. It could turn exactly 180 around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions. It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course correcting so that it is now moving toward PointB. I'm trying to figure out how to calculate that quot specific direction quot that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed. Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc. Can anyone help me out?


My Raycast2D doesn't go where I want and it doesn't return a GameObject I want my Objects to teleport when they hit a wall. For that, I want to shoot a Ray backwards and teleport it to where the ray hits the wall, but whatever I try, it always teleports to the centre of the scene and the ray hit doesn't return a GameObject. This version I tried runs on OnTriggerEnter2D RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up, 300) Debug.DrawLine(transform.position, hit.point) transform.position hit.point I tried some other variations too. If you have any idea, please let me know.


How to make variables restart when the game restarts? My game is all in one scene so when my player dies and the user clicks restart the game (when it shows the game over screen) the script below doesn't restart with it so the enemies are still going fast when the user is replaying the game. How do I make it restart when the game restarts? if (Score 10 0) Increment movespeed variable from Movement script Movement.movespeed 4 This is used in my score script. The Movement.movespeed is a reference to my movement script attach to my enemies making them go faster when the player collects 10 points.


Unity assembly files missing from "Temp bin Debug" I'm trying to use VS Code on a Mac with Unity and C . When I try to open a Unity project in VS Code, it can't load Assembly.dll files from few locations which are defined by default in .csproj files "Temp bin Debug ". When I check the Temp bin Debug paths, while Unity is running, they are empty they doe not contain the assembly files, where I assume they should. The files are in "Library ScriptAssemblies". Moving them is not an option, because I would have to do that manually every time I change sth. in any script file. Changing the path in the .csproj files is also not a good idea, because those files get rewritten every time you open a project in Unity. This issue causes lot of problems in the editor WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp firstpass.dll' INFORMATION OmniSharp MSBuild Update project Assembly CSharp Editor firstpass WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp firstpass.dll' INFORMATION OmniSharp MSBuild Update project Assembly CSharp Editor WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp Editor firstpass.dll' WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp firstpass.dll' All type references coming from my custom scripts and the UnityEngine namespace are missing, and highlighted as errors However, intellisense seems to be working fine for UnityEngine types I tried to reinstall MonoDevelop it a few times, including a brew and downloadable package. MonoDevelop seems to be installed properly mono version Mono JIT compiler version 4.6.2 (mono 4.6.0 branch ac9e222 Wed Dec 14 17 02 09 EST 2016) Copyright (C) 2002 2014 Novell, Inc, Xamarin Inc and Contributors. www.mono project.com emsp emsp TLS normal emsp emsp SIGSEGV altstack emsp emsp Notification kqueue emsp emsp Architecture x86 emsp emsp Disabled none emsp emsp Misc softdebug emsp emsp LLVM yes(3.6.0svn mono master 8b1520c) emsp emsp GC sgen .NET works as well dotnet version 1.0.0 preview2 1 003177 How do I fix this?


How do I raycast to detect which hexagonal tile was clicked? I want to detect the hexagonal tile a unit is on upon clicking on the unit. I was thinking of using a ray cast I can't get it to work. I'm trying to get the raycast to shoot from the bottom of the unit and change the material of the collided object. if (Input.GetMouseButtonDown (0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if(Physics.Raycast(ray, out hit)) Debug.Log (hit) string hitTag hit.transform.tag if(hitTag "player") if(Physics.Raycast(user.transform.position,Vector3.down,10)) Debug.Log ("I'm on something!") hit.collider.renderer.material.color Color.red What might be going wrong?


Unable to add button in Unity I am wanting to add a button to my scene in order to mute unmute music. I can add the button to my scene, but it's not appearing on the UI. I can't see it anywhere, not on the scene nor the game when running. Below is a screenshot of the editor. You can see the button in front of the camera and in front of the scene itself, but it doesn't appear. I can't actually see a button, just a 'move' control'. Things I have tried Changing the 'Layer' of the button to default Adjusting the z axis (I've tried 0, 1 5, 1 5) Giving the Image (Script) a material inside the Inspector The button has text, which isn't visible either. I could create a sprite and do a raycast, but that seems like overkill just to do a simple click action. Any ideas?


Unity How to add bones to procedural mesh Basically this is the set up An N amount of prefabs are bundled together into a new GameObject. This is then merged into a single main mesh composited of M amount of material submeshes. The shape is standing upwards on the Y axis and is a bunch of arms. The goal is to move these by adding bones. I wasn't able to find many examples on how to properly assign bones to a procedural mesh which isn't a simple cube. The problem is assignment of vertices to the boneweights. I'd like for the transform Y 0 vertices to have no weight and the Y furthest vertices have full weight. I am not sure how the assignment should be done.. Any pointers? ) So far the Lower and Upper bone transforms are in the right place, but when moving them the mesh isn't bending as I hoped it would in a nice curve, half of the vertices are simply moved uniformly with a thin mesh line connecting the two halves. private void AddBones() if(m SkinnedRenderer ! null) Make bone weight for vertices BoneWeight weights new BoneWeight m MainMesh.vertexCount int halfway (weights.Length 2) for (int i 0 i lt weights.Length i ) if(i lt halfway) weights i .boneIndex0 0 weights i .weight0 1 else weights i .boneIndex0 1 weights i .weight0 1 m MainMesh.boneWeights weights Make bones and bind poses Transform bones new Transform 2 Matrix4x4 bindPoses new Matrix4x4 2 bones 0 new GameObject("Lower Bone").transform bones 0 .parent m MergedRoot.transform bones 0 .localRotation Quaternion.identity bones 0 .localPosition Vector3.zero bindPoses 0 bones 0 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix bones 1 new GameObject("Upper Bone").transform bones 1 .parent m MergedRoot.transform bones 1 .localRotation Quaternion.identity bones 1 .localPosition new Vector3(0, 1.5f, 0) bindPoses 1 bones 1 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix m MainMesh.bindposes bindPoses m SkinnedRenderer.bones bones m SkinnedRenderer.sharedMesh m MainMesh m SkinnedRenderer.rootBone bones 0


Detecting Left and Right Mouse clicks on UI Text objects that are dynamically created So, in my game I create a bunch of UI Text game objects dynamically (in the C script), but I just can not find out how to properly detect Left and Right mouse clicks on these UI Text that were dynamically generated. I have tried adding Colliders and Colliders2D to the UI Text game objects for raycasting, but with no luck. And differently from UI Button, it seems that Unity has left proper "on mouse click" functions out from UI Text Can anyone help out on how to accomplish that? PS no, I can not use UI Buttons, it has to be Texts. And the UI Texts have to be generated on the fly, not in the editor


Issue calculating new angle for player to look at some 3d world object I am working on a Unity game where the Euler angles of the player display some weird behaviour that I cannot understand. There seem to be two full 360 degrees rotations, one positive and one negative. Depending on the direction you go when you are at 0 degrees, it will either take the negative path or the positive path. This means the player can have totally different yaw values depending on if it takes the green or red path. See the following image to get an idea of what is happening The issue now comes when I want to calculate the new angle for the player to look at some specific object in the 3d world space. I calculate this angle using some simple math make player the origin, so the target is relative to the player Vector3 delta player.angles target.angles float magnitude delta.Length() float pitch asin((delta.y) magnitude) (180 M PI) float yaw atan2(delta.x, delta.z) (180 M PI) This will give me back correct angles, but the yaw is from 0 to 180, then 180 to 0 again. I correct for this doing this makes sure the calculated angle is from 0 360 if (yaw lt 0) yaw 360 normalize yaw So, right now this is aligned with the red rotation line illustrated in the picture above. If I would set the players rotation to the new calculated angle, it would look correctly at the target object directly. But ONLY when the player is on the red rotation path. If the player for example is on the green rotation path the calculated angle doesn't fit for the current users rotation. If I would set the rotation now, things get quirky. Somehow I need to compensate the calculated new player angle. What is going on here? and is it possible to manipulate the new calculated angle (which ranges always from 0 360) so it is based on the current players rotation path (either green or red)? I hope my question makes sense, I found it quite hard to follow what is going on. I hope someone could explain me the situation and ultimately help me out to fix the new calculated angle so it adjusts to the current player rotation path! Any help is appreciated, thanks in advance! EDIT So I came up with the following to make sure the player is always rotated the shortest amount, taking both green and red rotation paths into consideration normalize angles for when using negative rotation if (localAngles 1 lt 180) angles 1 360 double diffPitch (angles 0 localAngles 0 ) double diffYaw (angles 1 localAngles 1 ) this makes sure we always take the shortest amount of degrees to target if (diffYaw lt 180) diffYaw 360 if (diffYaw gt 180) diffYaw 360 I will have to test some more to be sure this is the solution.


How do I fix the YAML error in Unity 5? I'm using Unity 5 and I'm getting an error in a YAML file. The error is "Unable to parse YAML file mapping values are not allowed in this context at line 1" This comes up every time I open the engine. I've seen some say to open the YAML file and change some stuff in it. But I can't even find the YAML files. I've also seen that it's caused by meta file issues and version control. The project is local but I don't know if it matters if it's local or cloud based. Does anyone have a solution for this issue?


How can I toggle enabled on a specific script within an object in Unity? I have the CarController script inside my car GameObject. I need to set it to disabled at the start so the countdown timer can start the race. I thought I knew how to do it but once again I have failed Any ideas why this doesn't work?? void TogglePlayerEnabled(bool b) playerCar.GetComponent lt CarController gt ().enabled b void ToggleAiCarEnabled(bool b) aiCar.GetComponent lt CarController gt ().enabled b If I use a print line saying "Toggled" or something, that appears in console as expected. But the CarController script seems like it stays active as both me, and the AI car can just drive whilst the countdown is happening still. Here's the full class public class GameManagerControl MonoBehaviour public GameObject playerCar public GameObject aiCar public int sceneChangeZValue private string countdown "" private bool showCountdown true Use this for initialization void Start () Update is called once per frame void Update () TODO This will change the scene when the track ends. if (player.transform.position.z gt sceneChangeZValue) SceneManager.LoadScene("race track lake") if (showCountdown) StartCoroutine(GetReady()) call this function to display countdown IEnumerator GetReady() countdown "3" TogglePlayerEnabled(false) ToggleAiCarEnabled(false) yield return new WaitForSeconds(1.5f) countdown "2" yield return new WaitForSeconds(1.5f) countdown "1" yield return new WaitForSeconds(1.5f) countdown "GO" TogglePlayerEnabled(true) ToggleAiCarEnabled(true) yield return new WaitForSeconds(1.5f) showCountdown false countdown "" GUI void OnGUI() if (showCountdown) GUI.color Color.red GUI.Box(new Rect(Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box(new Rect(Screen.width 2 90, 75, 180, 140), countdown)


Unity game crashes when opened on some computers but not all I'm facing a weird issue where every time I attempt to run a Unity application, it just crashes with no error message or log being generated. I tried running the game, it works on some computers (3) but fails on most (35). Upon attempting to run the application, I get a box that pops up for a second with a red exclamation point, which then crashes. See screenshot below I have found people having similar problems, but no real solution. https forum.unity.com threads solved crash when running any unity application.599953 https forum.unity.com threads crash when opening any unity application.873133 My game is made in Unity (v2018.1.9f2). Attaching the error logs for your reference. Unfortunately, I do not have the admin privileges to try the citrix solution in lab computers (since they are controlled by the University office). Error logs https pastebin.com mcMaD9im https pastebin.com M0e9a9GG https pastebin.com DSRrU8bZ


Unity3d iOS build restarts when regaining focus from browser I have an app made in Unity3d for android and iOS. In it, the user has the ability to link their accounts with Facebook and Twitter. For Facebook I use their Unity plugin, for Twitter, I open an external browser page that lets them accept or decline Twitter integration that then redirects to a php page the calls the app URI to return focus to Unity. On Android this all works perfectly using an Intent in the Manifest. In IOS I'm running into issues though and I don't really know my way around XCode. I'm using the newest version, XCode 7 Beta 2. The App runs as expected but for both the Facebook and Twitter authentications, upon returning focus to the App from the Browser, it completely restarts the App as if just launched rather then returning from a suspended state. In the Unity build I have "Run in Background" selected. I setup the URL Scheme in XCode. Its a pretty basic app so I don't think its being closed due to Memory usage. Any ideas or any settings I can change in XCode that might be preventing it from resuming? Note, if I just hit Home and send the App to the background it will properly resume, its only when called by the URI from the browser that it seems to completely restart.


Accelerometer input for flying game I'm trying to create an infinite flying game where the gameobject (a plane) keeps moving forward and at a particular height throughout the game. I want to be able to roll and pitch the plane but not move it up down. I added a rigid body to the plane and selected "y" position constrain. However the plane doesn't stay in the 'y' position but starts move up or down. I just have a script that translates the plane in the z direction. Not sure how to implement the mobile input and keep at the same "y" position throughout. Update Here is the code for the plane. Its very basic as I'm not sure how to use the accelerometer public class Player MonoBehaviour public float speed 1.0f void Update () float tempx Input.acceleration.x float tempy Input.acceleration.y float tempz Input.acceleration.z transform.Translate(0, 0, 10) move forward in z transform.Rotate( 0, tempy speed, tempz speed) As for the freezing of the 'y' position, I'm just selecting the y constraint available in the inspector that comes along with the rigidbody.


How can I create a custom PropertyDrawer for my Point struct? I created a Point struct System.Serializable public struct Point public int x public int y I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a Vector2 field. I have the following script in the "Editor" folder using UnityEditor using UnityEngine CustomPropertyDrawer(typeof(Point)) public class PointEditor PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) EditorGUI.Vector2Field(position, label, property.vector2Value) It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the Point instance from inside the OnGUI method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective Point is also changed?


How do you make the first person object the main camera? How can a first person object character be made to be the primary viewing camera in unityscript? Do I remove the main camera? or just turn one or the other on off?


Move camera around player while facing player My player has the following hierarchy Hero (GameObject) Model (child of "Hero", centered at 0 0 0) Camera (child of "Hero") The camera should be allowed to change its position around the Model in a circle ("rotate around the center") rotate so that it always faces the Model move up and down move nearer and further from to the Model I know how to do that using Quaternions, but as I'm doing this in a coroutine and using Lerp, I found myself in situations where the camera would get right through the model as this was the shortest path between the destination and the target vector. I would now like to use pure angles (Sin and Cos), preferrably without LookAt. Can somebody share how I would position and rotate the camera according to the angle, perhaps even taking a camera height variable into account as the camera should also be able to move up and down, still facing the player? That would be the bomb!


Why can't I play 2 animation track at the same time in Timeline for additional Camera? I try to move and rotate camera at the same time in timeline. To do this, I added two animation track to camera. One animation track changes position of the camera. And the other one changes rotation of camera. But they are not working at the same time. When I press quot preview quot button, only rotation of camera changes This video may help understanding if question is not clear https vimeo.com user133731359 review 517045792 43b6c6ec49


Can ARToolKit be used for color detection? I'm trying to make an app that will show an object from different sides, but the target will be too small for any real marker detection. Think of a cube with one or two centimeter sides. The camera distance is not a problem but it has to be at least ten centimeters out or what I'm trying to do won't work. I was wondering whether it was possible to color one side of the cube differently than others and make ARToolKit recognize the color to know which side it's looking at. Is this possible or just not in the range of things ARToolKit can do? If so, is there any kind of AR that can do this.


Performance problem when multiple enemies are grouped up I have enemy with simple behavior Reach the player's current position. In game are increasing waves, which are increasing the number of enemies. But when are more enemies (like 14), and they got too close to each other, there is big physics spike in profiler. There are significant drop of performance... And as Profiler says, it's because of Physics... Now I am little lost, I tried turn of the ignore collision on layer (which was turned on), so they don't overlap, but there is still little touch of course, when they group up, so still so much to process... What is the best solution here? I build it around rigidbodies for the use of Velocity, and detection of collisions with walls (edge collider), so when the object reaches there, it is easily stopped... But for this cases it seems now like not the best solution.


How to force play area corners to Lighthouses in Unity I'm working for a guy that wants to recreate real environments in VR and superpose them for business demos. Think of one of those mall kiosks where you "enter virtual reality" and at first it looks exactly the same as regular reality until you start interacting with objects and the virtual elements start being superposed. Basically, AR in VR. To do this, I have an exact model of the kiosk, but I need to be able to force the play area in vive and unity to be always the same and equal to the dimensions of the real space, so that my model can superpose the actual world objects. Is there a way to force the play area to be the same as the distance between the lighthouses? Additionally, is there a way to force the lighthouses to never recalibrate after the initial setup(as it does when someone moves in front of them for example)?


Rotate an object on itself, from one random Quaternion to another I have a situation I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector vector A, and vectorB My question is How to I rotate over time my object, from A to B ? The vector A is important I don't want to simply rotate the forward of the object from current forward to B. I know I can use the function vector3 C Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A amp B. but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do gameObject.transform.forward C I want something like gameObject.transform.rotation SomeQuaternion(C, initial rotation A). or something. Thank you for help ! PS I don't want to parent unparent gameObject or something like that, i want the math answer, using Quaternion.


Unity3d calling a web service in unity editor works, but not in standalone. Why? I have this line of code SDE3D webService new SDE3D() int result webService.UserLogin(txtLoginUsername.text, hashString) My UserLogin function looks like this System.Web.Services.Protocols.SoapDocumentMethodAttribute("http www.something.com UserLogin", RequestNamespace "http www.something.com ", ResponseNamespace "http www.something.com ", Use System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle System.Web.Services.Protocols.SoapParameterStyle.Wrapped) public int UserLogin(string username, string password) object results this.Invoke("UserLogin", new object username, password ) return ((int)(results 0 )) In the Unity Editor it works well. At runtime, in my Unity game build, it doesn't work and doesn't return any error message! What is the issue? Thanks


transform.Rotate needs to change axis of rotation So I'm making a game in Unity. After many failed attemps from either being bored of the idea, or something going wrong and me giving up I think (hope) that will be the good one. I have made a simple racing game with a track and a car. I am using transform.Translate to move it, but when I use transform.Rotate to turn it goes around the x axis. How do I change the axis it goes around? I cant find anything online. if (Input.GetAxisRaw("Horizontal") gt 0.5f) transform.Rotate(Vector3.right Time.deltaTime handling) if (Input.GetAxisRaw("Horizontal") lt 0.5f) transform.Rotate(Vector3.left Time.deltaTime handling) if (Input.GetAxisRaw("Vertical") gt 0.5f Input.GetAxisRaw("Vertical") lt 0.5f) transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") moveSpeed Time.deltaTime, 0f)) Thanks for any help you can give me.


How can i loop over all the childs of childs? In top of script i added public Transform parentToSearch Then private void OnGUI() if (hasDescription true amp amp clickForDescription true) foreach (Transform child in parentToSearch) if (child.GetComponent lt ItemInformation gt () ! null) ItemInformation iteminformation child.GetComponent lt ItemInformation gt () if (child.name objectHit) var centeredStyle GUI.skin.GetStyle("Label") centeredStyle.alignment TextAnchor.UpperCenter GUI.Label(new Rect(Screen.width 2 50, Screen.height 2 25, 100, 50), iteminformation.description, centeredStyle) But when i make the loop foreach (Transform child in parentToSearch) It will find the first level childs of the first parent but this childs have also childs and so on. And i want to loop all the childs and childs of childs under the Transform. For example in the Hierarchy i have Test Test1 Test2 Test3 Test31 Test32 Test4 Test5 Test51 So now it will loop only over Test 1,2,3,4,5 but I want also to loop over Test31,Test32,Test51


AddForce results in stuttering movement I'm currently developing a simple breakout arkanoid mobile game. Now, I noticed that my ball movement is noticably stuttering. I've read various approaches about how to make the ball move and decided to go for AddForce so I don't have to do any physics calculations myself. The only thing im currently doing is using AddForce on my ball's rigidbody2D and have it collide with the walls and blocks. There's nothing done manually in Update or FixedUpdate and there are no other scripts running while the ball is moving. The scene is pretty empty actually. Things I have tried so far without success Disable V Synch Increase the velocity iterations (I tried values 15 500) Set the RigidBody2D's interpolation mode to Interpolate Extrapolate Using different mass values and force values in AddForce Checking, whether it's just an optical illusion (it seems to run more smoothly in editor and other breakout arkanoid games don't have that problem on my Galaxy S7) RigidBody settings of the ball Body Type Dynamic Material Friction 0 Bounciness 1 Mass 0.025 Linear Drag 0 Angular Drag 0 Gravity Scale 0 Collision Detection Continous Sleeping Mode Start Awake Interpolate Interpolate The walls and blocks are simple BoxCollider2D components. And I'm calling AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) on the ball's RigidBody2D. Edit public void OnPointerUp(PointerEventData eventData) if(! ballStarted) PaddleController.ShootStickingBalls() ballStarted true public void ShootStickingBalls() int stickyBallsAmount stickingBallsRigidBody2D.Count for (int i 0 i lt stickyBallsAmount i ) stickingBallsRigidBody2D i .AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) stickingBallsRigidBody2D i .transform.SetParent( nonStickyBallsTransform) Sticky false


How do I avoid fetching duplicate tetromino shapes from a Shape array in Unity C ? I'm working in C in Unity on a tetrominoes game. I have seven basic shapes (I, J, L, O, S, T, Z) but each of the four component squares on each shape is labelled with an identifier unique to the shape set. So the shapes include, e.g., an S 1,2,3,4, S 5,6,7,8, S 9,10,11,12, J 13,14,15,16, J 17,18,19,20, Z 21,22,23,24.... Currently, in my Spawner class, I have the following to fetch a shape randomly from the shape array, m shapeSet1 public class Spawner MonoBehaviour public Shape m shapeSet1 Shape GetRandomShape() int i Random.Range(0, m shapeSet1.Length) if(m shapeSet1 i ) return m shapeSet1 i else return null I thought it would be simple to use m shapeSet1.RemoveAt(i) before the final closing brace after each fetch to avoid fetching, and later spawning (there is another function to spawn shapes), a duplicate shape. BUT, Visual Studio responds with (1) the RemoveAt request is unreachable and (2) Shape has no definition for RemoveAt and no extension for it. (I'll have to add a Do While or another control to this as I cannot retrieve a shape from the empty array I hope to create once I'm able to get only a unique shape.) Anyway, how do I get a shape without duplication?


Offsetting ground texture doesn't work in WebGL so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving. The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again. heres the code attached to the ground to keep it offsetting constantly using System.Collections using System.Collections.Generic using UnityEngine public class Offset MonoBehaviour public float scrollSpeed public Material mat private float offset Use this for initialization void Start () mat GetComponent lt Renderer gt ().material Update is called once per frame void Update () offset Mathf.Repeat(Time.time scrollSpeed, 1) mat.mainTextureOffset new Vector2(offset, mat.mainTextureOffset.y) What may I be doing wrong, and how can I fix it? Thanks in advance!


Only part of my model animates, the rest stays still I made an animation for when my character grabs a ledge, which has him set his arms and head into a position, and have him swing his legs back and forth, however only his legs move and his arms and head stay in the default resting position of the model. I have a video of what's happening. you can see the intended animation on the bottom right, and you can see what happens instead in the video. Video link https youtu.be PwrBdEsvgpY


When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?


Is there a way to start UI animation transition with code in unity? I have made an animation for a button in unity's UI prefab, but i want it to start only at certain times, when i command it with code. How can i do this?


CS0118 framerate is a field but a type was expected I'm making a mobile game in Unity and I'm trying to write a script that will set the game to either 30 or 60 frames per second based on a public bool, but I am getting error CS0118 on line 12 with fps.framerate is a 'field' but a 'type' was expected. I am pretty new to Unity so I need help with this? using System.Collections using System.Collections.Generic using UnityEngine public class fps MonoBehaviour public fps framerate Use this for initialization void Start () framerate GameObject.Find("gameSettings").GetComponent lt framerate gt () lt error CS0118 if (framerate true) Application.targetFrameRate 60 else Application.targetFrameRate 30


Unexpected results during collisions in Unity I've got a basic car based game I'm starting in Unity. Currently the scene has only a floor, a car (player controlled), and one building. Bumping into the building at low to medium speeds works as expected. When getting the car up to max speed and smashing into the building, though, weird results happen. Originally, the car was being pushed through the floor and falling off the map. I changed the floor from a plane to a cube that was stretched to be broad and flat (scale 2 height), and that helped. Now the car seems to clip right through the building at top speed, sometimes flipping itself into the air when it emerges. So what gives? The car and building are both imported .fbx models and both have box colliders stretched to the outer bounds of the models. The car has a rigid body with gravity. The building used to have a rigid body, but I removed it once I realized it was making the building fly into the air on impact (which was definitely not what I wanted). Here are the relevant parts of the movement code bool key up false float top speed 1f float current speed 0f float acceleration .01f void Update () if (Input.GetKeyDown (KeyCode.UpArrow) amp amp !key up) key up true if (Input.GetKeyUp (KeyCode.UpArrow) amp amp key up) key up false if (key up) if (current speed lt top speed) current speed acceleration else if (current speed gt .1f amp amp current speed lt .1f) current speed 0f if (current speed ! 0f) current speed current speed 0.9f transform.Translate (0f, 0f, current speed) Update After switching the camera to a fixed position (rather than following the car), I've gotten better observations. The car will clip right through at any speed if I keep pushing forward. There's initial resistance from the collision detection and some stuttering from the car, but it always breaks through and then flips into the air on its way out. I've added the following function to the car code void OnCollisionEnter (Collision collision info) current speed 0f current speed is what's being used to translate the car forward each frame. This has slowed the bug down, but the car always eventually pushes through if I hold down the gas long enough. It looks as if Unity's collision detection isn't moving the car back far enough on each frame that the car is colliding. Must I handle that portion on my own?


How to fix this NullReferenceException error? I am trying to fix an error that says quot Object reference not set to an instance of an object quot . The purpose of this script is to spawn a prefab that follows the mouse when you click a UI button. The script works fine despite showing the error(yellow triangle), but when I add a line referencing another scripts array(marked gt gt gt ) in the HandleNewObjectHotkey function) the game refuses to run(red stop sign). For context, this script shown is attached to an empty game object. The button retrieves the script from this game object, and specifically uses the HandleNewObjectHotkey Function. I would like to know how I can fix the placeable Object Prefab from producing an error, or a suggestion to bypass it. Things I've tried making placeableObject prefab public, removing serialize field, attaching the prefab to the script itself in assets, change everything from private to public. SerializeField private GameObject placeableObjectPrefab shows error here in visual studio, suggesting to make read only (doesn't fix the problem) private GameObject currentPlaceableObject private float mouseWheelRotation public int objectsSpawned Money stuff private float money private MoneyDisplay moneyDisplay private ObjectCostDisplay objectcostDisplay private void Awake() moneyDisplay GameObject.FindObjectOfType lt MoneyDisplay gt () objectcostDisplay GameObject.FindObjectOfType lt ObjectCostDisplay gt () private void Update() if (currentPlaceableObject ! null) MoveCurrentPlaceableObjectToMouse() RotateFromMouseWheel() ReleaseIfClicked() private void ReleaseIfClicked() if (Input.GetMouseButtonDown(0)) currentPlaceableObject null private void RotateFromMouseWheel() mouseWheelRotation Input.mouseScrollDelta.y currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation 10f) private void MoveCurrentPlaceableObjectToMouse() Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hitInfo if (Physics.Raycast(ray, out hitInfo)) currentPlaceableObject.transform.position hitInfo.point currentPlaceableObject.transform.rotation Quaternion.FromToRotation(Vector3.up, hitInfo.normal) public void HandleNewObjectHotkey() error says issue is in this function. money objectcostDisplay.CostsList 0 gt gt gt adding this is what causes unity to refuse to run the game due to error mentioned. Deleting this lets game run, error still present. if (objectsSpawned lt 3 amp amp money lt moneyDisplay.currentMoney) if (currentPlaceableObject null ) currentPlaceableObject Instantiate(placeableObjectPrefab) objectsSpawned moneyDisplay.UpdateMoney(money) if(objectsSpawned 3 amp amp money lt moneyDisplay.currentMoney) Debug.Log( quot You have reached the limit for this item! quot ) if(objectsSpawned lt 3 amp amp money gt moneyDisplay.currentMoney) Debug.Log( quot You don't have enough money for this! quot )


Is there any way to automaticaly rig a sprite? I'm making an AR test where the player takes a photo, them i get the bones from the pose and set a t shirt sprite's bones position to match the ones from the photo. I was wondering if there's any way to make the sprite rigging process, with just the main bones like LRshoulder,LRelbow and LRHip, automatic in Unity.


How do I get a Light's Range value in Shader? I'm trying to write a simple frag vert shader that, depending on whether it is in the range of a light, will paint the appropriate colour from either the 'lit' texture or from the 'unlit' texture. Therefore, I need to compare the distance between the light to the range of the light. I've been googling all kinds of things, but I can't seem to find a way of accessing the range value of the light. Is there a way to do so? If not, is there some kind of derived data I could use as an alternative? I was able to find this method here, which seems to be the most promising so far, however after playing around for a bit, I still can't seem to get what I need. There's some talk about LightMatrix0 not being populated. Can anyone confirm? I've also had it suggested to use SetFloat() and pass in the range like that...however, that provides no easy way of telling one light apart from another short of using the light's position as a key. As several key lights in the game will be moving this is just ugly and inefficient. Update I found the variable unity LightAtten in the Unity Shader Variables documentation. However, this is only used for Vertex Lit shading, which isn't exactly ideal, especially considering the lack of console support. Could there be a way to pipe this variable to Forward Rendering? Update 2 For clarification, shading should otherwise be 'flat' (ie no need for diffuse etc) Also, what I've currently got (albeit, not currently working as desired and currently using a workaround) Shader "Lantern Flat Pullup" Properties LitTex ("Lit (RGB)", 2D) "white" UnlitTex ("Unlit (RGB)", 2D) "white" Falloff ("Falloff", 2D) "white" Pullup ("Pull up Point", Range(0,1)) 0.7 SubShader Pass Tags "LightMode" "ForwardBase" LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) float4 color Improve for light color etc if(length(flatReflection) gt Pullup) color tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw) else color tex2D( UnlitTex, i.tex.xy UnlitTex ST.xy UnlitTex ST.zw) return color ENDCG FallBack "Diffuse"


Efficiently rendering lots of the same mesh in Unity3D, but with different colors? I'm working on a tile based game, where grass is spreading from tile to tile, so soon lots of grass appear on the board. Instancing is on, so the FPS is kind of good, even with 300k triangles (1 grass leaf consists of 90 triangles). BUT Tiles can be wet and dry on floating scale, which makes the grass leaves turn from green to yellow. Currently I implemented this simply as such var r originalColor.r 0.27f (1f (ground.Status 100)) renderer.material.color new Color(r, originalColor.g, originalColor.b) Which creates a new material for every grass... Obviously I can't change the sharedMaterial's color, because that would change all other grass' colors as well. So how could I efficiently render grass on a big spectrum from yellow to green? One thing I came up with is that I create only like 100 materials, with 1 percent steps. first material is 100 yellow, and the last one is 100 green. And when a grass turns a bit more green, it doesn't have to create a whole new material with 3.47 green, but instead can use the already created 3 green material. Any better ideas? Thanks!


How do I enable a Box Collider when a timer reaches 0? I'm pretty new to Unity, and I am trying to enable a BoxCollider from another object when the timer reaches 0, using this code using UnityEngine public class Testv2 MonoBehaviour public GameObject otherGameObject private BoxCollider Target public float timeLeft 30.0f void Awake() Target otherGameObject.GetComponent lt BoxCollider gt () void OnMouseDown() timeLeft Time.deltaTime void Update() if (timeLeft lt 0) Target.enabled true My issue is that the timer won't go down unless I keep clicking on the object. How do I enable the timer to start when someone clicks an object, and start counting down?


Get all objects of Additively loaded Scene? (LoadSceneMode.Additive) I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive. I like to spit up my scenes as much as possible and retain the stuff I need as I go along. I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them. For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround. Is there an easier way?


Unity, Replace or modify camera with own script I am making an RTS game which has a slowdown when many units are on screen at once. I have a plan to write my own camera script to speed this up. Since I have an efficient way to find where units are without the raycast, I want to write scripts to replace the camera and check raycasts against only the few objects that my scripts will identify as in the correct area for that raycast? Alternatively is is possible to have the camera ignore certain entities on one part of the screen, and then a different set on another part of the screen? Edit I am very grateful for people helping in anyway, but I wanted to know if this Could be done even if in my case it shouldn't be.


How can I make Maya or Blender model work with mecanim? I'm working on a simple game project, where I need a stick figure. Due to being stubborn and the desire to learn a new skill, I want to make the stick figure myself! I have followed several tutorials in both Maya and blender. For Maya, I'm using the student version. I have my stick figure rigged within Maya and blender, both utilizing their respective bone tools. I can manipulate their limbs well, enough. However, I can't seem to get the models to work with Mecanim. I have the Kinect adapter for the PC and would like to be able to use it to create the animations utilizing a tool such as the Kinect v2 mocap animator. How I can get my model to work with Kinect based mocap?


UIButton fails to play sound I'm doing this game where with cards you assign different beats to different channels. You drag and drop the beat to a channel and it gets added to the mixer. What I'm having trouble with is when i try to play each channel individually with an UI Button. This is the script attached to the channels public class ManageChannel MonoBehaviour public AudioSource thisAudioSource bool chequeo string Nombre public AudioMixer audioMixer public void AsignaCanal () Nombre this.name tomo el nombre del canal actual thisAudioSource this.GetComponent lt AudioSource gt () var carta this.transform.GetChild(0) llamo a la carta hija de este objeto thisAudioSource.clip carta.GetComponent lt AudioSource gt ().clip thisAudioSource.outputAudioMixerGroup audioMixer.FindMatchingGroups(Nombre) 0 asigno al AudioSource el grupo correspondiente public void comienzaAudio () if (!thisAudioSource.isPlaying) thisAudioSource.Play() else thisAudioSource.Stop() Start is called before the first frame update void Start() chequeo true Update is called once per frame void Update() if (this.transform.childCount ! 0 amp amp chequeo) AsignaCanal() chequeo false thisAudioSource.Play() What the script does is when a card is dropped, it takes the clip of the card and get its into the AudioSource of the channel, and that AudioSource gets outputted to its respective channel (for example, the GameObject quot Channel 1 quot goes to the mixer group quot Channel 1 quot and so on). Then i've tried to build the buttons to reproduce the track of each channel individually, but using AudioSource.Play() since I believe I cannot do it with the AudioMixer directly. What i did is create a UIButton and then assign the respective GameObject Channel to the OnClick() section on the inspector, and then i choose the following function on the script that i showed before public void comienzaAudio () if (!thisAudioSource.isPlaying) thisAudioSource.Play() else thisAudioSource.Stop() Then, every time i press the button, that function should be called. The problem is nothing happens. I'm positive the button is working because i tested with a bool value and a Debug.Log() to see if it changes values with every click, and it does. So, i honestly have no clue what the issue is. Any help would be appreciated. Thanks!


Show Sprites on Overlap (Shader Graph) 2D I have a character sprite mesh and mesh renderer (The black wavy box). I am hoping to be able to overlay the black box onto the character covering the sprites but I am not sure how to do that. I looked at this question Unity How do I only show parts of objects that overlap 2D But this works more as a cover that you can see through. I am hoping to have the variable black mask the sprites of the character but I cant seem to layer these correctly. Is there a way to do this using the LWRP and shader graph? The over arching idea is to use this as a damage marker. Moving the black box up or down depending on the health lost.


How to recycle unity scroll list of game objects? In my game, I have a scrollrect which its content have a VerticalLayout component. When I fill that with so many count of GameObjects, the game will fall in problem! I know that I have to recycle my objects, but I don't know how!


How do I slow down my character while running? void Movement() transform.Translate(Vector3.forward 10 Time.deltaTime) if(Input.GetKey(KeyCode.S)) transform.Translate(Vector3.forward 3 Time.deltaTime) if(Input.GetKeyUp(KeyCode.S)) transform.Translate(Vector3.forward 10 Time.deltaTime) I tried this code but seems to me, it didn't work as I expected it to. What I expect my character moves along at a speed of 10 automatically when the S key is held, the character slows down to a speed of 3 instead when the S key is released, the character goes back to their default speed of 10 What I observe the character does not slow down when the S key is pressed How can I fix this?


Draw trajectory arc predictor in game I found this tutorial on youtube and it works pretty well, but I want to add more to it. How can I draw a smooth arc path in the game view (right now the path is only visible in the editor)? Here is the code public class BallLauncher MonoBehaviour public Rigidbody ball public Transform target public float h 25 public float gravity 18 public bool debugPath void Start() ball.useGravity false void Update() if (Input.GetKeyDown (KeyCode.Space)) Launch () if (debugPath) DrawPath () void Launch() Physics.gravity Vector3.up gravity ball.useGravity true ball.velocity CalculateLaunchData ().initialVelocity LaunchData CalculateLaunchData() float displacementY target.position.y ball.position.y Vector3 displacementXZ new Vector3 (target.position.x ball.position.x, 0, target.position.z ball.position.z) float time Mathf.Sqrt( 2 h gravity) Mathf.Sqrt(2 (displacementY h) gravity) Vector3 velocityY Vector3.up Mathf.Sqrt ( 2 gravity h) Vector3 velocityXZ displacementXZ time return new LaunchData(velocityXZ velocityY Mathf.Sign(gravity), time) void DrawPath() LaunchData launchData CalculateLaunchData () Vector3 previousDrawPoint ball.position int resolution 30 for (int i 1 i lt resolution i ) float simulationTime i (float)resolution launchData.timeToTarget Vector3 displacement launchData.initialVelocity simulationTime Vector3.up gravity simulationTime simulationTime 2f Vector3 drawPoint ball.position displacement Debug.DrawLine (previousDrawPoint, drawPoint, Color.green) previousDrawPoint drawPoint struct LaunchData public readonly Vector3 initialVelocity public readonly float timeToTarget public LaunchData (Vector3 initialVelocity, float timeToTarget) this.initialVelocity initialVelocity this.timeToTarget timeToTarget I found a way to Instantiate projectile along the path. Now I just need to know how to convert that line in debug mode to make it visible in game mode


An object reference is required to access non static member UnityEngine.Material.GetTextureOffset(string) I am watching a tutorial where it seem to work. But in my case, I am getting this error. I get it that non static members have to have an object. But, I don't know much about how to fix this error. using UnityEngine using System.Collections public class AnimatedTexture MonoBehaviour public Vector2 speed Vector2.zero private Vector2 offset Vector2.zero private Material material void Start() material GetComponent lt Renderer gt ().material offset Material.GetTextureOffset (" MainTex") void Update() offset speed Time.deltaTime material.SetTextureOffset (" MainTex", offset)


Shadows in Android using Unity 5 The point lights in my scene cast shadows when it's in the editor mode but the light passes through walls in the build or play mode. I checked the quality settings and set it to hard and soft shadows for all quality settings but that didn't fix it. It does work when I increase the quality when I build it for Standalone but not when I build for Android. I've removed the dx11 option in the PC Mac Standalone settings. I've changed both forward and deferred rendering options. I'm testing it on a Moto G 1st Gen XT 1033 .


Light point buggy on old device after migrating to URP Light point is very buggy on Samsung A5 after migrating to URP, it works well on PC and Samsung A7. Altought it has light points, these are really few and using lowest settings by default, all other graphic stuff is lightweight and runs well. Does someone know if it's expected or what can I do? I tried to reduce the lightning settings and add OpenGL ES 2, but I've got the same results.


Follow Player which moves over a sphere After hours of googling and pulling several hairs out, I decided to open this thread. I want to make a game, in which the player walks around a sphere (like super Mario galaxy) and the camera should stay fixed over the player and point down on its head but I can't seem to get anywhere near of the right method. So, how can I realise this? Thanks.


Perlin Noise Problem with Falloff I know this might be a bit of a noob question, but I can't figure out what I'm doing wrong, and the math that I have done should make this work correctly. I am trying to make a perlin noise map that is normal until a specific range, at which point it would decrease to where all the values trend towards zero, creating an island in an ocean. I am currently generating perlin "sample" values, and then dividing them by a factor which stays close to one up to a specific bound, and then increases polynomialy. The problem however, is that the noise stays stuck in the top right corner, and is darker than I would expect. Here is the mathematical function I am using graphed on Desmos where n is the boundary and x is the distance from the center of the map And here is the main body code I am using to generate the noise map using System.Collections using System.Collections.Generic using UnityEngine public class GenNoise MonoBehaviour public int width 256 public int height 256 public float scale 20f public float offsetX public float offsetY public float falloffRange 100 public float falloffPower 10 public void RenderNoiseMap() Renderer renderer GetComponent lt Renderer gt () renderer.sharedMaterial.mainTexture GenerateTexture() Texture2D GenerateTexture () Texture2D texture new Texture2D(width, height) for (int x 0 x lt width x ) for (int y 0 y lt height y ) Color color GenerateColor(x, y) texture.SetPixel(x, y, color) texture.Apply() return texture Color GenerateColor(int x, int y) float xCoord ((float)x width scale) offsetX float yCoord ((float)y height scale) offsetY float falloffFactor FalloffFactor(x, y, width, height) float sample Mathf.PerlinNoise(xCoord, yCoord) sample sample falloffFactor return new Color(sample, sample, sample) float FalloffFactor(int x, int y, int width, int height) float falloffFactor 1 float centerX (float)width 2 float centerY (float)height 2 float distanceFromCenter Mathf.Sqrt(Mathf.Pow(2, ((float)x centerX)) Mathf.Pow(2, ((float)y centerY))) falloffFactor Mathf.Pow(2, (Mathf.Pow(falloffPower, (distanceFromCenter falloffRange)) 1)) return falloffFactor And Here is the code that I am using to generate the image in the editor using UnityEngine using UnityEditor CustomEditor(typeof(GenNoise)) public class NewBehaviourScript Editor public override void OnInspectorGUI() DrawDefaultInspector() GenNoise script (GenNoise)target if (GUILayout.Button("Generate")) script.RenderNoiseMap() Here is a picture of the result


Can I run my own loading script during the Unity splash screen? Can I load data in the background while the Unity splash screen is up? If so, how? I am trying to run code during the splash screen, not just load assets. I have not been able to find any information on this in Google or the Unity Documentation.


Keeping instantiated grid in the centre of the screen? everyone, I'm making a mobile game and I need help. In the game, I instantiate a grid of dots as seen in the first attached file below. My problem is the grid is not in the centre of the screen I could just position my main camera so the grid is in the centre the only problem with this approach being that the grid changes in size depending on your level as shown in attachment 2 here's my spawn code for (int x 0 x lt gridX x ) for (int y 0 y lt gridY y ) SpawnDelay Random.Range(0.2f, 0.5f) yield return new WaitForSeconds(SpawnDelay) Instantiate(Dot, transform.position, transform.rotation) NumberOfdots transform.position new Vector2(transform.position.x distanceBetween, transform.position.y) if (y MutpleNum ByMutpleNum) transform.position new Vector2(GridoffsetX 2, transform.position.y GridoffsetY) Is there anyway I can have the grid centre regardless of its size Thanks, David


Unity How to realize a modal message box? I'm developing a simple "modal" MessageBox. This is the code inside Message Box panel public void Show(string title , string message, bool showYesButton, bool showNoButton, bool showCancelButton) this.gameObject.SetActive (true) Title.text title Message.text message btnYes.SetActive ( showYesButton) btnNo.SetActive ( showNoButton) btnCancel.SetActive ( showCancelButton) And here how I call it outside MyMessageBoxScript script MyMsgBoxGameObject.GetComponent lt MyMessageBoxScript gt () script.Show("Hey..","Are you sure you want to overwrite this save ?",true,true,false) Ok.. the problem is that I can't do a "modal" window, like in .NET version, returning what user pressed. Something like buttonPressed script.Show("Hey. ", "Are you sure...") So, searching with Google someone use this Way script.Show(CallBackFunction "Hey..","Are you sure you want to overwrite this save ?",true,true,false) and void CallBackFunction () ... But I can't understand how it works How to pass CallBackFunction as parameter and how to execute (after clicking yes,no or cancel) ? Thanks


Looping world for a top down space shooter? I am trying to understand how to make a seamless looping world for my top down space shooter. First thing I tried was using multiple cameras, and teleporting the player when he reaches the edge, but it is not working well, and I don't like that I have to use 4 cameras. I wanted to test making the objects in the world teleport around the player, but I will have problems with the fact that each object is a different size, and teleporting them around will for sure create problems with moving objects. (Big obstacles could be teleported away and not collide with, for example, bullets until the bullet gets teleported too but inside the big obstacle) Are there other ways to accomplish this? Screen of the game (everything is still a placeholder) https i.stack.imgur.com 8FWCE.png


Attach movement to each list object How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N 1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere. using System.Collections using System.Collections.Generic using UnityEngine public class Spawner MonoBehaviour public GameObject prefabs public List lt GameObject gt listBalls new List lt GameObject gt () private GameObject x public int timer 0 private float movementSpeed 5f void Start() createBall() void Update() if (Time.time timer gt 0.8f) createBall() timer 2 listBalls listBalls.Count 1 .transform.position new Vector3(0, 0, movementSpeed Time.deltaTime) void createBall() x prefabs Random.Range(0, prefabs.Length) Instantiate(x, x.transform.position, Quaternion.identity) listBalls.Add(x) void moveBall(GameObject x, GameObject y) x.transform.position y.transform.position new Vector3(0,0, 1) Loop added but movement staggered void Update() if (Time.time timer gt 0.8f) createBall() timer 2 foreach (GameObject item in listBalls) item.transform.position new Vector3(0, 0, movementSpeed Time.deltaTime)


Move object towards the center of coordinating system I would like to move a object towards Vector2(0, 0), but every time I use this script, the object always goes down, instead of going towards the center of the coordinate system. void Update() Object rotation if (!Input.GetMouseButtonDown(0)) angle speed Time.deltaTime var offset new Vector2(Mathf.Sin( angle), Mathf.Cos( angle)) radius transform.position centre offset else Moving object towards center rb.transform.position Vector2.MoveTowards(transform.position, Vector2.zero, speed Time.deltaTime)


How to instantiate seamless scrolling tiles I'm trying to create in Unity an quot Endless Runner quot game, where the player remains stationary on the 0 of the axes while the tiles underneath him scroll with a fixed speed on the Z Axis. The script attached spawns 5 tiles at the start while already scrolling at the speed set in the GameManager and then keeps on spawning tiles based on a timer. The issue I'm facing is the following The tiles that are spawned with the timer are too much distant from the starting set of tiles. How can I calculate the correct distance between the set of the already scrolling tiles and those the script start to spawn after 5 seconds in order to have seamless scrolling? I'm attaching the script with what I've written so far in the hope that someone knows how to proceed, or perhaps knows a different method. Thanks! public class TileManager MonoBehaviour SerializeField private Transform player SerializeField private GameObject tilesArray SerializeField private int tilesToSpawn 5 SerializeField private float zPosSpawn 0f SerializeField private float tileLength 20f public List lt GameObject gt tilesList private float spawnRate private float timeSinceLastSpawned void Start() scrollingSpeed is 5 spawnRate GameManager.Instance.scrollingObjectsSpeed 1 StartSpawnLogic() void Update() timeSinceLastSpawned Time.deltaTime SpawnTimer() DestroyAfterSpawn() private void StartSpawnLogic() for (int i 0 i lt tilesToSpawn i ) if (i 0) SpawnTiles(0) else SpawnTiles(Random.Range(0, tilesArray.Length)) SPAWN FUNCTION private void SpawnTiles(int tileIndex) On Instantiation a list is filled to later dispose of the tiles after they reached a certain point tilesList.Add((GameObject)Instantiate(tilesArray tileIndex , transform.forward zPosSpawn, Quaternion.identity)) zPosSpawn tileLength TIMER private void SpawnTimer() if (timeSinceLastSpawned gt spawnRate) timeSinceLastSpawned 0 SpawnTiles(Random.Range(1, tilesArray.Length)) void RemoveObjFromList(GameObject tile) Destroy(tile) tilesList.Remove(tile) private void DestroyAfterSpawn() for (int i 0 i lt tilesList.Count i ) if (tilesList i .transform.position.z lt 20f) RemoveObjFromList(tilesList i )


Unity IAP through Google Play is forgotten after a day without internet connection I am trying to make a NonConsumable IAP purchase persist without internet connection. I have implemented the IAP system from Unity 5.6 through Google Play for a NonConsumable item and it is working. From a previous question I learned how to avoid using Unity's PlayerPrefs to remember purchases in favor of checking the receipt from the Unity storeController that initializes with Unity's API code below. public void OnInitialized (IStoreController controller, IExtensionProvider extensions) this.controller controller this.extensions extensions What I have observed is that the OnInitialized will run without internet connection as long as it has recently been initialized. This seems to be cached somewhere within Android because clearing the cache on my app will not force the purchase to be forgotten. The problem is after about half a day without internet connection the controller cannot initialize. Therefore I cannot check the item receipt in the controller with the code below. Product product storeController.products.WithID(productId) if (product ! null amp amp product.hasReceipt) Owned Non Consumables and Subscriptions should always have receipts. So here the Non Consumable product has already been bought. itemBought true What strategy or method should I use to persist a NonConsumable purchase during times without internet connection as it is recommended to not use Playerprefs on numerous guides.


How to create high quality and fast portal effect? EDIT So I've gotten the portal visual effect working with no performance hit, and I've got the physics set up of objects with rigidbodies moving through portals seamlessly, and objects with character controllers moving through it seamlessly. The only thing I'm trying to figure out now is blending two camera views to get the proper first person transition effect. Any ideas on how I'd blend those two? I'm thinking something using a depth only shader, or the normalized viewport rect. My main problem is calculating that in real time, and with angles. So I've been working on creating a portal effect in Unity3D. Obviously I've taken Valve's Portal as a great influence to programming this. Currently I'm simply using a camera's rendertexture to get the graphical effect across, and then some code to do the rest. The problem is at 2048x2048 it looks as high quality as Portal's, but causes heavy FPS loss. To solve this I'd either have to lower the texture quality or the number of times I update the texture. Valve has accomplished a high quality portal effect without causing high frame rate loss. How can I do the same? Does anybody have any good ideas for rendering to a high resolution texture without causing frame loss? I'm considering making my own code for rendering to textures rather then using Unity's built in system, it's doable but would definitely be a hassle. So any thoughts, ideas, or suggestions are highly appreciated.


Is it possible to get object rotation in a shader for dynamically batched objects? All the batched objects have the same rotation. To simulate the effect of directional light I need to determine the object sides actual (world) directions. Normally I would use unity ObjectToWorld amp unity ObjectToWorld for that, which is not possible when the objects are batched. Is it possible to pass the object rotation to the shader in one action (since it's the same for all of them) without breaking the batching? This is a simplified shader example (here I use colors instead of light shadow effect and only 2 sides instead of 4) Shader quot Test UnlitTest quot Properties MainTex ( quot Texture quot , 2D) quot white quot TopColor ( quot TopColor quot , Color) (1, 0, 0, 1) BottomColor ( quot BottomColor quot , Color) (0, 0, 1, 1) SubShader Tags quot RenderType quot quot Opaque quot ZTest Off ZWrite Off Lighting Off Cull Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot sampler2D MainTex float4 MainTex ST float4 MainTex TexelSize fixed4 TopColor, BottomColor struct vertData float4 vertex POSITION float2 uv TEXCOORD0 struct fragData float2 uv TEXCOORD0 float2 uvW TEXCOORD1 float4 vertex SV POSITION fragData vert (vertData v) fragData f f.vertex UnityObjectToClipPos(v.vertex) f.uv TRANSFORM TEX(v.uv, MainTex) f.uvW mul(unity ObjectToWorld, f.uv) return f fixed isTransparentPixel(fixed2 uv) return step(tex2D( MainTex, uv).a, 0.0) fixed isEdgePixel(fixed2 uv) uv mul(unity WorldToObject, uv) back to object space return isTransparentPixel(uv) fixed4 frag (fragData f) SV Target fixed isTransparent isTransparentPixel(f.uv) clip( isTransparent) fixed4 c tex2D( MainTex, f.uv) float2 borderSize float2(3, 3) border size in tex pixels float dy borderSize.y MainTex TexelSize.y fixed3 borderColor fixed3(0, 0, 0) float borderColorsCount 0 float2 uvW f.uvW UV in the world space Top edge fixed isEdge isEdgePixel(uvW float2(0, dy)) borderColor isEdge TopColor.rgb borderColorsCount isEdge Bottom edge isEdge isEdgePixel(uvW float2(0, dy)) borderColor isEdge BottomColor.rgb borderColorsCount isEdge fixed noBorderColor step(length(borderColor), 0) fixed hasBorderColor 1 noBorderColor c.rgb c.rgb noBorderColor hasBorderColor borderColor max(borderColorsCount, 1) return c ENDCG It gets a semi transparent image as a texture. The image is completely transparent at the edges and contains an opaque shape in the center. The shader colors the top edges of the non transparent shape in red and the bottom ones in yellow. It uses unity WorldToObject amp unity ObjectToWorld to check the edges facing directions in the world space.


Have a method accept generic methods for a in game console I'm making a console, like in Half Life so that the devs can add their commands. I'm making this in Unity's C . I have a problem when dealing with the commands. When you want to add a commands, you create a class Command and add it through a method to the Console List of Commands. The code of the class Command is the following one public class Command lt summary gt The string by which this command will be called lt summary gt public string commandKey lt summary gt The information of this command that the help option will show lt summary gt public string helpInfo public delegate string stringVoid() public delegate string stringString(string consoleInput) public delegate void voidCmd() public delegate void voidString(string consoleInput) public stringVoid stringVoid public stringString stringString public voidCmd voidCmd public voidString voidString public Command(string commandInput, string helpTooltip) commandKey commandInput helpInfo helpTooltip region Add Command Methods public Command addVoidCommand(voidCmd voidCommand) voidCmd voidCommand return this public Command addStringVoid(stringVoid stringVoidCmd) stringVoid stringVoidCmd return this public Command addStringString(stringString stringStringCmd) stringString stringStringCmd return this public Command addVoidString(voidString voidStringCmd) voidString voidStringCmd return this endregion As you can see users can add four types of delegates methods Void methods with no parameters. String methods with no parameters. Void methods with a string parameter. String method with a string parameter. This makes the class very heavy, and makes the users have to navigate through a lot of options to add a class. I want to have some way to add methods without having to go through so many options, and, from my side, taking out the need of searching through so many options when a command is called from console. You can find the whole script project here. In conclusion, I want to have a way that the user simply write way I want it to work new Command("commandName", "this is an example" ExampleCommand) new Command("commandString", "this is another example" ExampleString) void ExampleCommand() string ExamplesString(string ble) return ble "bla" way it currently works new Command("commandName", "this is an example").addVoidCommand(ExampleCommand) new Command("commandString", "this is another example").addStringString(ExampleString) To simplify everything. Is any way I can achieve this with delegates, Unity Actions or something else? Thank you very much.


Why when using Mathf Lerp the speed is not changing according to Time.deltatime? using System.Collections using System.Collections.Generic using UnityEngine public class DetectCollision MonoBehaviour public Transform player public Transform target public bool turnOnOffPlayerAnimator false float timeElapsed 0 float lerpDuration 3 float startValue 1 float endValue 0 float valueToLerp 0 private Animator playerAnimator private bool entered false private bool prevFacing false private Rigidbody rigidbody private bool stopped false Start is called before the first frame update void Start() rigidbody player.GetComponent lt Rigidbody gt () playerAnimator player.GetComponent lt Animator gt () if (turnOnOffPlayerAnimator) playerAnimator.enabled false Update is called once per frame void Update() var currFacing IsFacing(target) if (currFacing ! prevFacing) here you switched from facing to not facing or vise verca. timeElapsed 0 prevFacing currFacing var distance Vector3.Distance(player.position, target.position) if (IsFacing(target)) if (entered amp amp distance gt 30) if (timeElapsed lt lerpDuration) valueToLerp Mathf.Lerp(startValue, endValue, timeElapsed lerpDuration) playerAnimator.SetFloat( quot Forward quot , valueToLerp) timeElapsed Time.deltaTime playerAnimator.SetFloat( quot Forward quot , valueToLerp) valueToLerp 0 else if (valueToLerp lt 0.9f) if (timeElapsed lt lerpDuration) valueToLerp Mathf.Lerp(endValue, startValue, timeElapsed lerpDuration) playerAnimator.SetFloat( quot Forward quot , valueToLerp) timeElapsed Time.deltaTime playerAnimator.SetFloat( quot Forward quot , valueToLerp) Mathf.Lerp(valueToLerp, 0, Time.deltaTime 0.0001f) if(turnOnOffPlayerAnimator) playerAnimator.enabled false else playerAnimator.enabled true private void OnTriggerEnter(Collider other) entered true Debug.Log( quot Entered ! quot ) private void OnTriggerExit(Collider other) entered false Debug.Log( quot Exited ! quot ) private bool IsFacing(Transform target) Vector3 forward player.TransformDirection(Vector3.forward) Vector3 toTarget target.position player.position return Vector3.Dot(forward, toTarget) gt 0 I tried first 0.1f but it didn't change the lerp speed. I want that if the player is pressing the W key and moving the player forward and then stop pressing the key W it will smooth slow will lerp to 0. and it does but I also wanted to control the lerp speed. I want that when the player is starting moving backward direction if the player leave the W key the player should stop slowly to 0. This should be the line Mathf.Lerp(valueToLerp, 0, Time.deltaTime 0.0001f) but the Time.deltaTime does not seems to affect the lerp at all. the lerp is working fine I just wanted to control the lerping speed too.


Why are there weird texture artifacts in baked light which don't appear with realtime light? This is the comparison of the same scene, realtime light vs baked light. What's am I wrong ? EDIT In particular, also texture are low quality (see image 2). Why ?


Planar reflections not showing when baked reflection probes enabled I have a reflection probe that is baked that is set to capture static environment objects like buildings terrain etc. I also have a planar reflection probe that is following the player camera which is only set to capture the player. I am trying to have both of these displaying on a surface. When I have the baked reflection probe turned on the planar reflection will not show. Are they mutually exclusive? I am using Unity 2020.1.6f1 with HDRP.


How to prevent Rigidbodies with restricted movement from clipping My player is a rigidbody cube with a box collider that can push other quot NPC quot rigidbody cubes that also have a box collider. These NPC cubes have restricted movement either in horizontal or vertical direction. If the player pushes a cube that can only move horizontally into a cube that can only move vertically, the cubes start clipping. I recorded the whole situation in this video. Note that the NPC cube on the left has frozen X position, while the one on the right has frozen Z position. I know that one way of preventing this would be to increase the mass of the NPC cubes, but that would only resolve the problem proportionally to the increased mass (the higher the mass, the lower the clipping), and at some point my player is not strong enough to move the NPC cubes anymore. How can I solve this?


How to make a rigidbody come to rest faster I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C script with the basic vector3 and velocity stuff from a YouTube video using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField private Rigidbody playerBody private Vector3 inputVector private float xMovement private float zMovement SerializeField private float playerSpeed private float maxSpeed Use this for initialization void Start () playerBody GetComponent lt Rigidbody gt () playerSpeed 1 Update is called once per frame void Update () xMovement Input.GetAxisRaw("Horizontal") playerSpeed zMovement Input.GetAxisRaw("Vertical") playerSpeed inputVector new Vector3(xMovement, playerBody.velocity.y, zMovement) playerBody.velocity inputVector It works great with a cube I put it on, except for this if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster?


Unity 5 Occlusion culling at runtime I am creating a game in Unity where the game is rendered while playing. The game is made in a voxel style, and has thousands upon thousands of objects rendered while playing. Of course, this causes a huge amount of lag. Therefor I need to use occlusion culling, to make sure only the objects needed are rendered. For occlusion culling, you need to bake the area, but I'm planning on creating a huge world. So, any tips on how I could do this?


Handle two different touch gestures at same time without overlapping I'm trying to create a Character touch controls for 2d platform. In my script Im using one horizontal swipe and hold touch gesture and one vertical swipe gesture without hold.Both are different methods called in void Update (). And here is my script void Update () HorizontalSwipe() VerticalSwipe () void HorizontalSwipe() foreach (Touch FingerTouchx in Input.touches) if(FingerTouchx.fingerId lt 1) FINGERID if(FingerTouchx.position.x lt Screen.width 2) if(FingerTouchx.phase TouchPhase.Began) FingerInitialPositionx FingerTouchx.position.x else if(FingerTouchx.phase TouchPhase.Moved) FingerMovedPositionx FingerTouchx.position.x if(FingerMovedPositionx gt FingerInitialPositionx) charcter.transform.Translate(Vector2.right speed Time.deltaTime) else if(FingerMovedPositionx lt FingerInitialPositionx) charcter.transform.Translate( Vector2.right speed Time.deltaTime) else if(FingerTouchx.phase TouchPhase.Ended) FingerInitialPositionx 0f FingerMovedPositionx 0f else FingerMovedPositionx FingerTouchx.position.x if(FingerMovedPositionx gt FingerInitialPositionx) charcter.transform.Translate(Vector2.right speed Time.deltaTime) else if(FingerMovedPositionx lt FingerInitialPositionx) charcter.transform.Translate( Vector2.right speed Time.deltaTime) void VerticalSwipe() foreach (Touch FingerTouchy in Input.touches) if(FingerTouchy.fingerId lt 1) FINGERID if(FingerTouchy.position.y gt Screen.width 2) if(FingerTouchy.phase TouchPhase.Began) FingerInitialPositiony FingerTouchy.position.y if(FingerTouchy.phase TouchPhase.Moved) FingerMovedPositiony FingerTouchy.position.y if(FingerTouchy.phase TouchPhase.Ended) if(FingerMovedPositiony gt FingerInitialPositiony) charcter.transform.Translate(Vector2.up speed Time.deltaTime) if(FingerMovedPositiony lt FingerInitialPositiony) charcter.transform.Translate( Vector2.up speed Time.deltaTime) FingerInitialPositiony 0f FingerMovedPositiony 0f else Problem 1 When i swipe and hold horizontally the character moves fine but when i take my finger back it triggers the vertical swipe method. 2 When i try to swipe only vertically the horizontal swipe is also triggered. 3 The two swipe gestures are overlapping and triggered at same time on a Single touch. Solution(Guess) Dividing the touch screen equally half and forcing horizontal touch gestures strictly on left side of touch screen and vertical touch gestures on right side. But I'm beginner(You can see my coding style) and would like to know how to do it programatically. Im still learning.


On screen enemy indicating arrow I am working on indicating on screen arrow to point towards the enemy. I have a environment which consist of a player and three enemy placed at different position on the environment.I need an arrow indicating the enemy,so that the player can move towards the enemy in the environment. How can I do this?Can anybody please help me out. I have got a script on searching. public Texture2D icon The icon. Preferably an arrow pointing upwards. public float iconSize 50f HideInInspector public GUIStyle gooey GUIStyle to make the box around the icon invisible. Public so that everything has the default stats. Vector2 indRange float scaleRes Screen.width 500 The width of the screen divided by 500. Will make the GUI automatically scale with varying resolutions. Camera cam bool visible false Whether or not the object is visible in the camera. void Start () visible GetComponent lt SpriteRenderer gt ().isVisible cam Camera.main Don't use Camera.main in a looping method, its very slow, as Camera.main actually does a GameObject.Find for an object tagged with MainCamera. indRange.x Screen.width (Screen.width 6) indRange.y Screen.height (Screen.height 7) indRange 2f gooey.normal.textColor new Vector4 (0, 0, 0, 0) Makes the box around the icon invisible. visible false void OnGUI () if (visible) Vector3 dir transform.position cam.transform.position dir Vector3.Normalize (dir) dir.y 1f Vector2 indPos new Vector2 (indRange.x dir.x, indRange.y dir.y) indPos new Vector2 ((Screen.width 2) indPos.x, (Screen.height 2) indPos.y) Vector3 pdir transform.position cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y, transform.position.z)) pdir Vector3.Normalize(pdir) float angle Mathf.Atan2(pdir.x, pdir.y) Mathf.Rad2Deg GUIUtility.RotateAroundPivot(angle, indPos) Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before. GUI.Box (new Rect (indPos.x, indPos.y, scaleRes iconSize, scaleRes iconSize), icon,gooey) GUIUtility.RotateAroundPivot(0, indPos) Rotates GUI back to the default so that GUI drawn after is not rotated. void OnBecameInvisible() visible false Turns off the indicator if object is onscreen. void OnBecameVisible() visible true The problem is start when I play the scene the arrow is seen at the start but its get invisible soon


Unity blur on one camera effects the other as well I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly. So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render. I have the cameras like Cam 1 Clear flags Don't clear (this is the main, sharp cam) Culling mask sharp layer has no blur effect (or any other post proc effect). Cam 2 Clear flags don't clear (this is the blur cam) culling mask blur Has Blur (optimized). Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground. The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it. Question is, how to set this up so only the desired layers get the blur?


Initial setting of camera and ppu to match playing table My goal is to implement another board game as close as possible as I would play it on a table to not much think about how to arrange elements. The used space on table is in the dimensions of around 1x2m and most of my assets are scans of game cards with a touch of Photoshop (for personal use only). My question is regarding the camera, pixel on import of asset and converting to units. There are no physics in the game involved and it is 2D. For now it will be tailored to my own mobile but I would like to know if one way is preferred if I wanted to later change resolution or is just better best practice. From my understanding it would result both in the same outcomes but there might be some hidden trouble or side effects. Should I (convert for myself to get a feel for dimensions) take 1 unit as 10cm gt scene of 10x20 units would represent my table or rather have a 1x2 unit scene (since most take one unit as one meter) Assuming my scanned card has something like 2000x1000 pixel (and is 10x5cm big on a real table), does it make more sense to have it imported as 2000 20000 under pixel per unit or downscale the image first before importing it with a lesser value? I don't really care currently about build asset size.