Push data in unity Player without Requesting I have a unity3d Player where I need some data from the server. The server code is written in python while on client side is C . Now I am searching a way that server directly post push data to my unity player. IMO! it is not possible to push data to unity player without requesting the server using WWW class. My question is can python post data to my client unity player? with something like response requests.post(client url, data request data, headers headers) I want to do this because i want to avoid repetitive calls to server which is not an efficient way.


How can I get the parents and childs from the hierarchy in the same order it is in the hierarchy the structure of the hierarchy? The line var gameObjects GameObject.FindObjectsOfType lt GameObject gt () Is getting all the parents and children but not in the order it is in the hierarchy. I tried to use the gos List and to add first the childs then the parents to create a List with all parents and it's childs but it's getting messed. I want to get the structure of the Hierarchy. var gos new List lt GameObject gt () var gameObjects GameObject.FindObjectsOfType lt GameObject gt () for (int i 0 i lt gameObjects.Length i ) if (gameObjects i .transform.childCount gt 0) get children GameObject children new GameObject gameObjects i .transform.childCount for (int z 0 z lt children.Length z) children z gameObjects i .transform.GetChild(i).gameObject gos.Add(children z .gameObject) else gos.Add(gameObjects i )


Unity Shader Outlined Uniform uses undefined Queue 'Geometry 1' my outline shader was working fine but suddenly it started throwing this error. the game still works fine in the editor though but when i try to build it gets stuck on the step Packing assets sharedassets0.assets this is my shader Shader "Outlined Uniform" Properties Color("Main Color", Color) (0.5,0.5,0.5,1) MainTex ("Texture", 2D) "white" OutlineColor ("Outline color", Color) (0,0,0,1) OutlineWidth ("Outlines width", Range (0.0, 2.0)) 1.1 CGINCLUDE include "UnityCG.cginc" struct appdata float4 vertex POSITION struct v2f float4 pos POSITION uniform float OutlineWidth uniform float4 OutlineColor uniform sampler2D MainTex uniform float4 Color ENDCG SubShader Tags "Queue" "Geometry 1" "IgnoreProjector" "True" Pass Outline ZWrite Off Cull Front CGPROGRAM pragma vertex vert pragma fragment frag v2f vert(appdata v) appdata original v v.vertex.xyz OutlineWidth normalize(v.vertex.xyz) v2f o o.pos UnityObjectToClipPos(v.vertex) return o half4 frag(v2f i) COLOR return OutlineColor ENDCG Tags "Queue" "Geometry" CGPROGRAM pragma surface surf Lambert struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 c tex2D( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG Fallback "Diffuse" i tried looking on the internet but couldn't get any help on this error.


How to make game scene bigger in 2d platformer? Hi i am current making a 2D platformer game but after i reach an end of screen then it doesn't move forward how to increase the game play screen area so that i will be able to go in vertical direction i am pasting an image of the problem i am new to unity please help me! 1


Unity networking, make player disappear for all clients As title says I need to make the player disappear when he gets in car. Right now, it works as a single player, but since I am new to unet I don't really know how to achieve this, I tried some ways, but they didn't work. Here is script Client void OnControllerColliderHit(ControllerColliderHit hit) so if we hit car if(hit.collider.tag "Vehicle") if we pressed "E" if (Input.GetKeyDown(KeyCode.E)) call method to disable some stuff taht should be disabled, like controller, shoot, weapons etc. if (isServer) CmdCall(inVehicle, hit) else RpcCall(inVehicle, hit) Command void CmdCall(bool invehicle, ControllerColliderHit hit) RpcCall(inVehicle, hit) ClientRpc void RpcCall(bool invehicle, ControllerColliderHit hit) disable(inVehicle, hit) I can't see any errors in console but I cant enter play mode cause there are some compiler errors, which again i cant see in console. thank you for any tip, comment, downvote, upvote, or hint ) Nick.


Additive scene loading to UNet I have a main scene where my player is loading as I start or join the server. On some player action, I want to load additive scenes in to my main scene. It is loading fine on the client, but not across the network. My other clients are unable to watch it. I checked different links, and found a forum post and a Unity Suggestions page. It seems, to me, that this "Additive scene loading to UNet" feature is not available in Unity. If additive scene loading in UNet is not available, then what are the alternatives? I am able to load scene through ClientRpc . Is this the correct way to do this? ClientRpc public void RpcLoadLevelAcrossNetwork() SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive)


Move Object to another Object's position on click Raycast I have one object, a knight, that I click on and want to move around on terrain. private void OnMouseDown() if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, 10000)) if (unitSelected) MoveUnit(hit) else if (unitSelected amp amp hit.collider home) GoHome(hit) And private void OnMouseDown() if (Input.GetMouseButtonDown(0)) Ray ray cam.ScreenPointToRay(Input.mousePosition) if(Physics.Raycast(ray, out hit)) MoveUnit(hit) Both scripts work fine when clicking on the terrain. The Problem I want to click on different objects and send the knight towards whatever object I click on. The knight does NOT move, though the object I click on registers a click (all objects have colliders). Is Raycast the most appropriate way to do this? Checking another users question similar to mine, (how to move one object to another objects position) they seem to use a method similar to "Vector3.MoveTowards". EDIT Moving my code from "OnMouseDown" to "Update" solves that issue. but is there a reason why OnMouseDown won't work or even how to make it work? I was trying to limit my code from going into Update as that's called every frame.


JSON deserializing 'nested' Array Greetings! I'm working on a class that loads and parses .json files and returns information from the loaded .json, but I have problems reading the nested arrays of my .json files. Turning the serialized object public and looking at the Inspector, the 'Choises' array is not being read at all. It contains four objects, each contain a string and an integer correspondingly. using SimpleJSON using System using System.Collections using System.Collections.Generic using System.IO using UnityEngine public class JsonParser MonoBehaviour private string loadedJson public StoryData storyData Serializable public struct choice public string choiceText public int choicePointer Serializable public struct storyImage public string imagePath Serializable public struct storyText public string text Serializable public struct placeholderStory public string storyText public string storyImage public List lt choice gt choises Serializable public struct StoryData public placeholderStory placeholderStory public void LoadJsonFile(string filename) loadedJson File.ReadAllText(Application.dataPath filename) storyData JsonUtility.FromJson lt StoryData gt (loadedJson) public string GetChoiceText(int storyPosition, int choiceIndex) string choiceString storyData.placeholderStory storyPosition .choises choiceIndex .choiceText Debug.Log(choiceString) return choiceString public string GetStoryText(int storyPosition) string storyString storyData.placeholderStory storyPosition .storyText return storyString public string GetStoryImage(int storyPosition) string imageString storyData.placeholderStory storyPosition .storyImage return imageString


Unity rigidbody velocity In Unity, what is the correct way to move a game object by modifying the velocity of its rigidbody? I'm having some issues with stuttering movement, so I just want to make sure I understand the basic idea. Is the following correct for moving an object vertically down the screen? Should this result in smooth, stutter free movement? using UnityEngine public class MovementTest MonoBehaviour private Rigidbody2D rb SerializeField private float speedY 250 private void Awake() rb GetComponent lt Rigidbody2D gt () void FixedUpdate() rb.velocity new Vector2( 0, speedY Time.fixedDeltaTime )


Implementing a group formation behavior I am trying to implement a group formation behavior where all the units in my group follow a leader and maintain their position throughout. So far I am able to move them, rotate and follow the leader. I have also implemented character separation and obstacle avoidance behaviors for all my units and the leader. However I want all the units to maintain the same relative position to the leader throughout the behavior ie say for example if one of the unit falls far behind the group due to an obstacle in its path, it should converge back to the main group to its initial relative position so that the formation of the group is not broken and stays the same throughout I have stored all my units in a list and offset them from the leader at the start of the game. But I want their offset position to be maintained throughout each update in the game. I am not able to do that. Below is my code so far public List lt GameObject gt followersList new List lt GameObject gt () void Start() for (int i 0 i lt followersList.Count i ) if(i 2 0) followersList i .transform.position new Vector3(gameObject.transform.position.x (2 i 2 ), gameObject.transform.position.y, gameObject.transform.position.z (2 (i 2 ))) else followersList i .transform.position new Vector3(gameObject.transform.position.x (2 i 2), gameObject.transform.position.y, gameObject.transform.position.z (2 (i 2 ))) private void VShapeFlockWander() Followers GameObject.FindGameObjectsWithTag("follower") Wander(gameObject) foreach (GameObject Follower in Followers) followerDirection (gameObject.transform.position Follower.transform.position).normalized Vector3 normal CheckFollowerCollisionAvoidance(Follower) Vector3 followerSepVector CheckFollowerSeparation(Follower) followerSepVector.y 0 followerDirection (normal followerSepVector) Quaternion rot Quaternion.LookRotation(followerDirection) Follower.transform.rotation Quaternion.Slerp(Follower.transform.rotation, rot, Time.deltaTime 3.0f) Follower.transform.position (Follower.transform.forward Time.deltaTime acceleration) if (acceleration lt vShapeWanderSpeed) acceleration 0.01f in the code above all the followers represent the units and the gameObject is the target leader to follow. All the other behaviors like separation and collision avoidance are working fine. Only thing I want to achieve now is for all the followers to maintain their relative position to the leader throughout. I tried using a Dictionary for each follower as key and its initial difference to the target as the value. Then somehow use that difference factor and make them move in a stable formation but I cannot get it to work either


Is there a way to display navmesh agent path in Unity? I'm currently making a prototype for a game I plan to develop. As far as I did, I managed to set up the navigation mesh and my navmeshagents. I would like to display the path they are following when setDestination() is fired. I did some researches but didn't find anything about it. EDIT 1 So I instantiate an empty object with a LineRenderer and I have a line bewteen my agent and the destination. Still I've not all the points when the path has to avoid an obstacle. Furthermore, I wonder if the agent.path does reflect the real path that the agent take as I noticed that it actually follow a "smoothier" path. Here is the code so far GameObject container new GameObject() container.transform.parent agent.gameObject.transform LineRenderer ligne container.AddComponent lt LineRenderer gt () ligne.SetColors(Color.white,Color.white) ligne.SetWidth(0.1f,0.1f) Get def material ligne.gameObject.renderer.material.color Color.white ligne.gameObject.renderer.material.shader Shader.Find("Sprites Default") ligne.gameObject.AddComponent lt LineScript gt () ligne.SetVertexCount(agent.path.corners.Length 1) int i 0 foreach(Vector3 v in p.corners) ligne.SetPosition(i,v) Debug.Log("position agent" g.transform.position) Debug.Log("position corner " v) i ligne.SetPosition(p.corners.Length,agent.destination) ligne.gameObject.tag "ligne" So How can I get the real coordinates my agent is going to walk throught ?


MotionBuilder Actor attached to Mocap moves fluently, but Character using Actor as source jitters and has joints occasionally pop out I'm trying to get a MotionBuilder animation to work in Unity on my custom character. I've downloaded Motionbuilder FBX mocap files with Actors already attached from http dancedb.eu main performances The thing is that when I put the Actor as the Input source for my own (Characterized) character model and hit play on MotionBuilder, my model follows the animation 80 correctly but for the other 20 my character jitters and shakes and occasionally even quot breaks a limb quot when a joint randomly pops out of its place for a second. Does anyone have suggestions on how to get the animation smoother for my Character?


Random Object in Array I am using Unity. I have created eight different types of objects, stored in an array, and I am displaying them on the scene in a grid pattern with random order. The first four objects in the array are red. The player needs to destroy all four red objects to go to the next level. The code I've writted so far uses the Random.Range method, which chooses objects completely randomly. Sometimes it generates a grid that doesn't contain four red objects, so my player can't destroy them and proceed to the next level. How do I randomly generate this grid so that it is guaranteed to have exactly four red objects? Here is my code. public int gridWidth 0 public int gridHeight 0 public GameObject facePrefab new GameObject 8 void Awake() gridHeight Random.Range (3, 5) CreateGrid(gridWidth,gridHeight) void CreateGrid(int numX, int numY) for (int x 0 x lt gridHeight x ) for (int y 0 y lt gridWidth y ) GameObject go Instantiate (facePrefab Random.Range(0,facePrefab.Length) ) as GameObject


How can I render from a buffer that exists and was created on on the GPU? I'm looking for a unity API or function call to allow me to do the following ... I wrote some really complex functions that are compute shaders. These compute shaders manage a huge compute buffer containing voxel information. I then take portions of (or the entire) voxel buffer in another compute shader and produce a vertex buffer. All of this is done on the GPU with only compute shader calls from the CPU. Now I want to render that vertex buffer but I must be looking in the wrong place because I can't find any information on how this is done within unity despite there being other examples on how to do this using raw DX or openGL approaches. Can anyone point me in the right direction to determine how I can render using a specified shader a buffer already in graphics RAM (and ideally give it some textures too)?


Command pattern for network games I am currently programming a multiplayer game. The basic idea is that the game uses Command Pattern for any actions that happens in the game. If the player right clicks to move then a command is issued to the selected object to move to the location. I implemented gRPC to include multiplayer. Here is my problem, when the player right clicks on the ground I send a gRPC call with that command then the server acknowledges the commands and sends it back to all the clients, the client then processes the command and everything goes well. Now if the player enters the game while a command is underway the client never received that command so its never process on the client. What would be a good way to fix this problem without sending the info of all the actors (x,y,z) and what they are doing at each server ticks? Thanks!


ColorMaterial AmbientAndDiffuse equivalent for CG HLSL I have this shader written on shaderlab, which replaces Ambient and Diffuse values of the material, because I need to tweak vertices colors from the script. Shader "VertexSimple" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Pass ColorMaterial AmbientAndDiffuse Lighting Off SetTexture MainTex Combine texture primary Fallback "VertexLit" I need to write an equivalent of this shader on CG HLSL to do some other routines in it. Ideally it should be vertex pixel shaders, not surface one. How can I do this?


Should I downgrade my Unity project to the latest LTS version? I created my Unity project with a 2020 version and now I'm using 2020.2.0f1. Recently, I realized that using the latest LTS version is the best choice for games that are in production or about to ship. I tried downgrading to the latest LTS (2019.4.18f1) but since Unity doesn't support downgrading, all my objects disappeared and I got a lot of weird errors in console. My question is Should I continue developing the game with the version that I'm using right now or downgrade to the latest LTS version?


Why does my custom network Manager disable the main one Whenever I add a custom Network Manager to add functionality to and override it's functions, the main NetworkManager got disabled so I could not see the NetworkManager HUD or start matches. It there a way around that? (EDIT) Thanks for the response It's not just the HUD that's the issue. The Networking is disabled entirely. Can I change this through a custom HUD?


How to create a 2d jelly soft blob body? I'm a developer looking into game development. I have an idea that requires a 'character' that needs a jelly like body. I've found this video which really demonstrates what I want. I've looked around and there are libraries assets that do this (like Jelly Sprites) but none state how they do it, and that's what I'm interrested in. What I've read so far is that a way of doing it is using multiple rigid bodies joined with joints that don't collide with each other. Witht he common sidenote that it might not perform that well. I'm hoping anyone has any pointers or tutorials that explain the concepts of jelly soft blob bodies. Any pointers towards achieving the effect shown in the video would be awesome.


How to calculate 1st, 2nd, 3rd place and draw conditions in local multiplayer game? I have a local multiplayer game with an end of round screen that pops up after each round. I'm trying to figure out the logic to calculate the 1st, 2nd, 3rd place from a maximum of 4 players. I also want draw tie conditions. It's possible for 2 or 3 players to get the same score. The score is just an int for each player. I've been struggling with this for a while... Any help appreciated, even if its just some pseudo code to point me in the right direction. Also, I'd like to avoid using Linq if possible, as I've heard it doesn't play nice with Unity. Thanks Edit Below is what I've managed to come up with for determining the draw conditions. Doesn't seem to hold up in all cases though... Surely there's a simpler approach? PlayerScore orderedScores m scores.OrderByDescending(ps gt ps.score).Take(4).ToArray() 1stPlacePlayers.Add(orderedScores 0 .playerNumber) if (orderedScores 0 .score orderedScores 1 .score) 2 player draw 1st place 1stPlacePlayers.Add(orderedScores 1 .playerNumber) if(orderedScores 0 .score orderedScores 2 .score) 3 player draw 1st place 1stPlacePlayers.Add(orderedScores 2 .playerNumber) if(orderedScores 0 .score orderedScores 3 .score) 4 player draw 1st place 1stPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 1 .score orderedScores 2 .score) 2 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 2 .playerNumber) if (orderedScores 1 .score orderedScores 3 .score) 3 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 2 .score orderedScores 3 .score) 2 player draw 3rd place 3rdPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 1 .score orderedScores 2 .score) 2 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 2 .playerNumber) if (orderedScores 1 .score orderedScores 3 .score) 3 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 2 .score orderedScores 3 .score) 2 player draw 3rd place 3rdPlacePlayers.Add(orderedScores 3 .playerNumber)


How to restrict the players movement win relation to screen bounds in Unity? (Without colliders) I am really enjoying making the switch to Unity. But here I have found one of those rare moments where it appears to make things more difficult (at least it is for me as I am crap at understanding the actual manual) Basically my 'player' is a space ship. It starts life at 0,0,0 world coordinates and I have been doing all the movement based off of that. (ie. Add force X to move left or right, and there is a constant Z speed which is done via rb.transform.Translate().) I want to restrict the movement on the X Axis, so in Libgdx id use something like if (player.position.x lt 0) player.position.x 0 if (player.position.x gt viewport.getX()) player.position.x viewport.getX() The thing is that wont work for me in Unity for several reasons (1. I dont know much about the viewport as I didnt create it. 2. the player.position is being affected by the rigidbody forces. AND i am working in world coordinates with the players position). As I said, the player is constantly moving forward on Z axis, so making colliders doesnt seem like the right choice for me. I'm pretty sure Unity devs would of put this in Unity v0.001 but I just cannot for the life of me find how to actually do it. (Any info I can find seems from like 2011 and also is pretty badly written code making this simple matter takes dozens of lines of code and some methods I'm hoping there is a Unity method already made, like player.transform.ScreenPosition or something but yeah I cannot find it!? Any help would be massively appreciated as always.


Exporting scene during gameplay to FBX In Unity is there a way to add a menu button during gameplay that allows the player to export the current scene as an fbx file? My googling and research shows that its possible to do this while developing the game but wondering if there is a way to add this functionality for the gameplay itself. Any suggestions on how if this can be done?


How can I make my tiles fall smoothly? I'm working on a Tile Based game and I can't figure out how to make my tiles fall down smoothly like in candy crush. All column tiles fall down at the same time. And spawn new like how many tile place if null. What I want Update 25.12.2015 But the my code works like this Update 26.12.2015 Hello Again, World Scale (x,y) World Scale OLD (10,10) World Scale NEW (10,11) Y 11 Tiles type Empty Now, when i click the random place like (5,7),above all blocks down to block.transform.pozition new Vector3(0, 1,0) It's working. But again, when i click same place (5,7) not working... I changed Y scale 10 to 11. Because, when i clicked tile, the tile will return to Y 11 position and fall down, how many tile place null. When Tiles state quot fallling down quot , the space between two blocks distance not more quot 0.01 quot . I do not know how to do. But I approached. I need to more improve this. Thanks... Pseudo code When I click the (4,7) coord, the tiles, tile(4,8) is smooth down the coord(4,7) tile(4,9) is smooth down the coord(4,8) tile(4,9) is generate new tile. What I have (Code not working properly ( ) World.Height 10 World.Widht 10 Tile X and Y get, protected set public void ColumnDown(int x , int yStart) if (IsColumnFull(x)) return for (int y yStart y lt World.Height y ) Yeni tile spawnla if (y 1 gt World.Height) continue Tile tile World.GetTileAt(x, y) Tile tile2 World.GetTileAt(x, y 1) GameObject go Tile GameObject.Find( quot Tile ( quot x quot , quot y quot ) quot ) GameObject go Tile2 GameObject.Find( quot Tile ( quot x quot , quot (y 1) quot ) quot ) if (tile ! null) if (go Tile null amp amp go Tile2 null) Debug.Log( quot go Tile NULL quot ) continue tile2 tile go Tile2.transform.position new Vector3(0, 1, 0) go Tile.name quot Tile ( quot x quot , quot (y 1) quot ) quot go Tile2.name quot Tile ( quot x quot , quot (y) quot ) quot


Not able to move quad wheel robot I am trying to move QWAD wheel robot, I have grouped the wheels separately and added wheels colliders for each wheel. The problem is that the wheels are moving but the robot is stationary. I have been stuck with this problem from many days. I am very new to unity3D and C scripting. At first I tried the concept of moving rigid body using car model and it is working perfectly fine. When I applied the same logic to QWAD wheel ROBOT is not woking as expeted, kindly help me out. Please find the code below using System.Collections using System.Collections.Generic using UnityEngine public class RoboMovemnt MonoBehaviour void Start() rb GetComponent lt Rigidbody gt () public void GetInput() m horizontalInput Input.GetAxis("Horizontal") m verticalInput Input.GetAxis("Vertical") private void Steer() m steeringAngle maxSteerAngle m horizontalInput FR Wheelwc.steerAngle m steeringAngle FL Wheelwc.steerAngle m steeringAngle private void Accelerate() RR Wheelwc.motorTorque m verticalInput motorForce RL Wheelwc.motorTorque m verticalInput motorForce if (m verticalInput 0) RL Wheelwc.brakeTorque brakeTorque RR Wheelwc.brakeTorque brakeTorque private void UpdateWheelPoses() UpdateWheelPose(FR Wheelwc, FR WheelT) UpdateWheelPose(FL Wheelwc, FL WheelT) UpdateWheelPose(RR Wheelwc, RR WheelT) UpdateWheelPose(RL Wheelwc, RL WheelT) private void UpdateWheelPose(WheelCollider collider ,Transform transform) Vector3 pos transform.position Quaternion quat transform.rotation collider.GetWorldPose(out pos, out quat) transform.position pos transform.rotation quat void HandBrake() if (Input.GetKey(KeyCode.Space)) IsBrake true else IsBrake false if(IsBrake true) RL Wheelwc.brakeTorque brakeTorque RR Wheelwc.brakeTorque brakeTorque RL Wheelwc.motorTorque 0 RR Wheelwc.motorTorque 0 else RL Wheelwc.brakeTorque 0 RR Wheelwc.brakeTorque 0 private void FixedUpdate() GetInput() Steer() Accelerate() UpdateWheelPoses() HandBrake() private float m horizontalInput private float m verticalInput private float m steeringAngle private Rigidbody rb private int Velocity public WheelCollider FR Wheelwc, FL Wheelwc, RR Wheelwc, RL Wheelwc public Transform FR WheelT, FL WheelT, RR WheelT, RL WheelT public float maxSteerAngle 30 public float motorForce 500 public bool IsBrake false public float brakeTorque 50000f


Unity Initializing class of a script not working I have been trying to find a solution for the last couple of hours so please hear me out. At first I got a NullReferenceException, which I resolved(?) by initializing the class first (This is my problem! I can't seem to initialize my class sucessfully). However, here are my next errors. I tried using the new keyword, which resulted in You are trying to create a MonoBehaviour using the 'new' keyword. Next I tried GetComponent lt gt (), which resulted in a CS0120, that I didn't know how to fix. The AddComponent lt gt (), resulted in a CS0103 The name AddComponent does not exist in the current context. What I tried next was GameObject.AddComponent lt gt (), which threw a CS0120, and gameObject.Addcomponent lt gt () which threw a CS0236. Here is my code for the class I am trying to initialize if it should be needed public class Dialogue MonoBehaviour public TextMeshProUGUI textDisplay public string sentences private int index public float typingSpeed public GameObject continueButton void Update() if (textDisplay.text sentences index ) continueButton.SetActive(true) public IEnumerator Type() foreach (char letter in sentences index .ToCharArray()) textDisplay.text letter yield return new WaitForSeconds(0.01f) public void NextSentence() continueButton.SetActive(false) if (index lt sentences.Length 1) index textDisplay.text "" StartCoroutine(Type()) else textDisplay.text "" continueButton.SetActive(false) Here is from where I tried to initialize public class Mace MonoBehaviour Dialogue dialogue gameObject.AddComponent lt Dialogue gt () private void OnTriggerEnter2D(Collider2D otherCollider) if (otherCollider.CompareTag("Player")) StartCoroutine(dialogue.Type())


Networking assigning IDs to entities Maybe I'm asking dumb question, but this problems bothers me... So I have my networked game in Unity (client), and server written in C (without Unity). I Use ENet library for networking. Most of networked components are written by myself (lobby, components etc.). Server doesn't know about Unity entities like players, obstacles etc. In most cases I send message ("hide object with id 4") to the server, and server pass that message to other clients where they applied message information. What my problem is, how to assign proper IDs to networked objects, that will be the same across all players? What I do is that On all clients I get all components with specific network component (e.g. NetworkRigidbody) I sort all of objects using special comparer which compares based on component name with all parents appended to it ID is just an index in sorted array Above algorithm works, but I have a feeling that in normal games that problem is handled in other manner. I searched over Mirror, MLAPI and other libraries source code and I couldn't find how entity id is generated, especially when server is not Unity application.


Custom Unity launcher localization I would like to localize Unity launcher using own texts. At the very least I would like to change "play!", "quit", "Graphics" and "Input" to own arbitrary labels. How can I achieve that?


Unity Tilemaps Best practices I'm pretty new to Unity and I just finished some courses and tutorial found in the official documentation. I'm now in the process to apply what I learned so far using different assets from the ones provided with the tutorial, to see if I understood all the material. I'm trying to build a simple top down game with some free asset I found online. My tile palette is composed, among others, of tiles like these Now, in order to create something like this sorry for the quality, I recreated it in gimp since I'm not on the computer where I have Unity now I had to create three Tilemaps under the same Grid. The botton tilemap contains the grass (sort order 2), the middle one contains the fence (sort order 1) and the top one contains the house (sort order 0). My first question is given the tileset I have, is this the most efficient way to obtain what I needed? After having solved this problem I wanted to add a collider to the fence and to the house, but since they are on two different tilemaps I cannot use a composite collider to optimize the collider's layout. Is there another way to do this in a more efficient way? Instead of using tiles for quot interactable objects quot , should I use quot proper quot game objects instead?


What's the difference between Mathf.Lerp and Mathf.SmoothDamp I want to smoothly go from one value to a new one (moving a slider or changing color). I tried using both functions and they all basically give the same result. What is the difference between them and which one should I use? How I used SmoothDamp Show the HUD private IEnumerator ShowHUD() var HUDCanvasGroup GameObject.FindWithTag("HUD").GetComponent lt CanvasGroup gt () var alphaValue 1f var velocity 0f var time 0.30f yield return new WaitForSeconds(1.5f) Gradually fade in the canvas while (!Mathf.Approximately(HUDCanvasGroup.alpha, alphaValue)) HUDCanvasGroup.alpha Mathf.SmoothDamp(HUDCanvasGroup.alpha, alphaValue, ref velocity, time) yield return null HUDCanvasGroup.alpha 1 Since float is not accurate, manually set the alpha to 1 after HUDCanvasGroup.interactable true var blur GameObject.FindWithTag("BlurryCamera").GetComponent lt BlurOptimized gt () blur.enabled true How I used Lerp public static IEnumerator Dim() while (t lt 1) t Time.deltaTime 0.4f dimRend.material.color Color.Lerp(undimColor, dimColor, t) yield return null


In Unity, how do I correctly implement the singleton pattern? I have seen several videos and tutorials for creating singleton objects in Unity, mainly for a GameManager, that appear to use different approaches to instantiating and validating a singleton. Is there a correct, or rather, preferred approach to this? The two main examples I have encountered are First public class GameManager private static GameManager instance public static GameManager Instance get if( instance null) instance GameObject.FindObjectOfType lt GameManager gt () return instance void Awake() DontDestroyOnLoad(gameObject) Second public class GameManager private static GameManager instance public static GameManager Instance get if( instance null) instance new GameObject("Game Manager") instance.AddComponent lt GameManager gt () return instance void Awake() instance this The main difference I can see between the two is The first approach will attempt to navigate the game object stack to find an instance of the GameManager which even though this only happens (or should only happen) once seems like it could be very unoptimised as scenes grow in size during development. Also, the first approach marks the object to not be deleted when the application changes scene, which ensures that the object is persisted between scenes. The second approach doesn't appear to adhere to this. The second approach seems odd as in the case where the instance is null in the getter, it will create a new GameObject and assign a GameManger component to it. However, this cannot run without first having this GameManager component already attached to an object in the scene, so this is causing me some confusion. Are there any other approaches that would be recommended, or a hybrid of the two above? There are plenty of videos and tutorials regarding singletons but they all differ so much it is hard to drawn any comparisons between the two and thus, a conclusion as to which one is the best preferred approach.


Terrain (mesh) textures in Unity blurry? I've created a 3D mesh in blender which will be used as a terrain in Unity. Additionaly, I created a 900x900 texture which I'd like to apply as material to the mesh. However, unlike with the normal Unity terrain, the material is only blurry unrecognizable, not matter how many times I repeat the texture what import settings I set for the texture. Some googling brought up that it may have to do something with the shader, but I tried many with no results. current result texture


How would I use an object from another animation in Unity? So I have two different .blend files with two different animations. Let's call my aiming with a gun animation animation A, and my other .blend file with idle, run, and jump animations animation B. If I wanted to play the aiming clip from animation A with the Animation B animator, it just looks like my character wants to shake hands, since the gun doesn't appear in the animation. The aiming animation works if I play animation A with animation A's animator. How would I use the gun object from animation A when playing animation A in animation B's animator? Here is an image of what the animation looks like in the import settings (what i want) and in the actual game (what is happening which I don't want.) The top image is what I want and the bottom image is what is happening. Thanks in advance.


How to detect a pinch in Unity? How do I detect a pinch motion on Unity for an android or Iphone? I need to also know whether the player pinches a certain character or not. How do i do that?


How can I create a mesh of triangles made from the vertices of a polygon and contained within that polygon? I'm trying to programatically generate a mesh, given the vertices of a polygon, which is contained within that polygon. For example, starting with these points I would want to generate a mesh similar to this My first port of call would be a Delaunay triangulation, but having implemented this, I came up against the problem that this was not contained within the polygon, i.e. it produced a mesh like this My question then is, is there either an algorithm which produces the desired result rather than the Delaunay result (because I can't find one online), or a modification that I can make to the Delaunay triangulation algorithm that will fix this? I'm using the Bowyer Watson algorithm, by the way. Thank you!


Unity Transforming horizontal distance between two spriteRenderers to set UnityEngine.UI.Button width to this distance In my Unity scene, I have a couple of spriteRenderers and a UnityEngine.UI.Button called thisButton. The spriteRenderers are spread horizontally across my scene. I want to change the button width to span from the leftmost spriteRenderer to the rightmost spriteRenderer. To do this, I have subtracted the x Coordinate of the rightmost spriteRenderer (fRightEndingPosition) from the x Coordinate of the leftmost spriteRenderer (fLeftStartingPosition). float fLeftStartingPosition leftmostSpriteRenderer.transform.position.x float fRightEndingPosition rightmostSpriteRenderer.transform.position.x float fButtonTargetWidth fRightEndingPosition fLeftStartingPosition Then, I try to set the width of thisButton to the value of fButtonTargetWidth by doing RectTransform buttonSize thisButton.GetComponent lt RectTransform gt () buttonSize.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fButtonTargetWidth) However, when I try to use this as the width of my button, the result is not correct. I am pretty sure this has something to do with different types of coordinates being used for the spriteRenderers and the button (world, screen, viewport, etc.), but I haven't been able to figure this out on my own. In one specific example fLeftStartingPosition is 1.1, and fRightEndingPosition is 1.1. In my scene, a button that spans this distance has a width of roundabout 40 on its RectTransform. So clearly, setting the width of this RectTransform (buttonSize) to fButtonTargetWidth (2.2) in code results in a button that is way to narrow. In fact, after setting it's width to 2.2, it is not visible at all. How do I transform this distance of 2.2 to the desired width of roundabout 40, in a way that this distance would be transformed correctly, no matter what the actual value of fButtonTargetWidth is?


Why does Unity editor freeze up if left unfocused for a while? If Unity editor loses focus for too long (such as because I'm tabbed out into my browser or Blender), then I find that it needs about 15 30 seconds until I can interact with it again when it gets focus again. It seems like it is paused. Is this a bug or my fault?


Can a MonoBehaviour be a private inner class? I want to use a private inner class MonoBehaviour as part of the internal implementation of a class (also a MonoBehaviour). Reduced to the essentials public class OuterClass MonoBehaviour public void SomeMethod(GameObject go) go.AddComponent lt InnerClass gt () private class InnerClass MonoBehaviour This appears to be all working absolutely fine, with no errors or warnings. But it also appears to violate the statement in the Unity documentation that The class name and file name must be the same to enable the script component to be attached to a GameObject. Is this a problematic violation of that rule? If so, what are the problems? I am aware that it means the script is not visible in the Editor, but that's exactly what I want it should never be added by anything other than its enclosing class.


How to prevent a duplicated shadow? It's a blob shadow which is built in Unity's standard asset package. As you see in the figure below, a shadow that is created by the Unity Projector is duplicated at the floor below. How can I prevent this duplicated shadow?


How can I create a "rain drops on camera lense" effect with the HDRP? I did follow this tutorial https www.youtube.com watch?v OG7zyogrUTs amp t 115s but I did not made it cause I am using HDRP and they are not using HDRP so the problem is I can't use the normal materials being in HDRP mode help me if there is any way to do so or if there is another good video please. In picture 1 I want these white particles on camera lens looks like the second picture I want water texture on these white particles.


Restrict render in Blender is not working I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity. How can I fix this?


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


Specular intensity not imported from Blender into Unity For my current project I'm using diffuse materials for my models in Blender but I do not want any Specular Intensity so I've set that to 0. Yet in Unity there is still a specular highlight and the material has a Smoothness of 0.5. Does Unity actually read Specular Intensity or am I missing some crucial detail? I haven't been able to find any details on what the .blend import actually reads and I can see a setting called Glossiness in the .mat files created by Unity is set to 0.5.


Input events slow on unity Update function I have this running on the Update() on Unity. I am trying to create a page swipe feature on my game, but the problem is there is a half second delay when printing "dragging" to "end drag" when I release the mouse. Does anyone have a method that will register input events faster? void Update() if(isDragOn) if(Input.GetMouseButton(0)) print ("dragging") moveContainers((Input.mousePosition.x mouseLastPosition) 0.01f) mouseLastPosition Input.mousePosition.x else if(Input.GetMouseButtonUp(0)) print ("end drag") isDragMoved false isDragOn false endDrag() else if(Input.touchCount gt 0) if(Input.GetTouch(0).phase TouchPhase.Moved) moveContainers(Input.GetTouch(0).deltaPosition.x) else if(Input.GetTouch(0).phase TouchPhase.Ended) isDragMoved false isDragOn false endDrag()


Project transfer, will re importing all my models damage my project at all? Recently I had to transfer my Unity game project to another computer and downloaded the same version of Unity I was using for my 3D project and checked that all the files and folders were in the same place and everything. When I start up the game though my models have vanished and in the hierarchy it just says missing prefab instead of telling me what it was, like it used to if I'd move a model to another folder or something like that. It shows all my files there and I was about to reimport them all but I got a warning that said "Rebuilding assets is only if your project has been corrupted due to an internal Unity bug. It can take several hours to complete, depending on the size of your project. Please submit a bug report detailing the steps leading up to here." I am sure that re importing all my models will fix this but I want to ask if this will have any negative effects on my project or possibly damage anything? This game is extremely important to me and I've been working on it for the past 3 years(being self taught which is why it's taken so long and I'm still learning) Thank you guys in advanced! D


How can I create a random deck of 7 cards every time they are all used? I'm trying to create a Tetris like game in C (Unity) and I've run into quite a problem on how I can generate 7 cards (tetrominoes) of which none are the same and when I run out of cards, I regenerate more. I can kind of see how I could do the regeneration part but I'm very unsure on getting 7 cards for which none are the same.


Problem modifying GameObject in list of GameObjects Unity So I've been working on a little project that involves Valve's quot Portal quot style portals, the type where you can seamlessly see what's on the other side and walk through. I've run into a problem when it comes to teleporting an object to it's new location upon hitting the portal. I have a List lt GameObject gt that contains all the objects that are in close enough range to feasibly travel through the portal, but when I try to modify the transform.position of one of these GameObjects, nothing happens, no error messages. So I've been going through my script line by line and writing little dummy functions to test different parts of it to see where the problem lies, and everything seems to work up until I index the list and try to modify a value, nothing happens. So was thinking that perhaps the List doesn't actually contain a reference to the GameObject in the scene, but simply a copy of the GameObject's data at the time it was passed into the list. So I checked this by making the list public so that I see it in the inspector, and when I click on an item in the list it highlights that same GameObject in the hierarchy, which suggests it is actually a reference. See bellow... I am at a loss as to what's happening here and would really appreciate if anyone could offer a suggestion, Here is the dummy function where I try to arbitrarily modify the GameObject data from the List... if (Input.GetKeyDown( quot k quot )) for (int i 0 i lt trackedTravelersObjects.Count i ) trackedTravelersObjects i .transform.position new Vector3(0, 30, 0) Debug.Log( quot K quot ) You'll notice a Debug.Log( quot k quot ), this is just to check that the code is actually being called, which it is. Thanks.


Splitting a prefab into two These hands are in a single prefab. I want to split this into two so that I can make bones for each of them separately and use them with leap motion. How can make each of these hands as a single prefab? Also, I'm using Unity 2018.


Wait until a method finish I'm using Firebase Realtime Database and I'm trying to compare if a name is available to other user. The problem is the method finish before the Firebase's method finish its execution. Here is the code private bool IsNameAvailable (string nick) bool available false FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task gt if (task.IsFaulted) Debug.LogError ("A error encountered " task.Exception) else if (task.IsCanceled) Debug.LogError ("Canceled ...") else if (task.IsCompleted) DataSnapshot snapshot task.Result available (snapshot.GetValue (true) null) ) return available This line executed before the Firebase's method end. What can i do?? Thanks in advance.


How to write depth texture and read values from it I am new in Unity and specializing in another field. But now I have to rapidly study it for a new project. I will be very thankful if anyone explain me how to read values of the depth buffer. I wrote a shader, which creates depth image Shader quot Custom MyDepthShader quot Properties MainTex ( quot Texture quot , 2D) quot white quot SubShader No culling or depth Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert compile function vert as vertex shader pragma fragment frag compile function frag as fragment shader include quot UnityCG.cginc quot struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o sampler2D MainTex sampler2D CameraDepthTexture fixed4 frag (v2f i) SV Target float depth tex2D( CameraDepthTexture, i.uv).r depth Linear01Depth(depth) depth depth ProjectionParams.z return depth ENDCG Now I need to get depth information into a texture and save float values of this texture to for example txt file for further processing. I didn't found yet answer to this question after two days of googling and reading guides. For testing this shader I am using OnImageRender(RT src, RT dst, material).


Why can't I rotate anything to be "more than 360 degrees or less than 0 degrees"? I've been trying to make an animation in Unity, but most assets already come bundled with everything facing at 0 degrees, not to say it's a bad thing. However, the problem I'm facing is that the animation keyframes aren't playing out correctly. When this is done with raw measurements (simply dragging the XYZ rotations), negative and greater than 360 degree angles are taken account. But then again Unity could be simply remapping them, whcih is not the case. For example, the prop robotArm prefab, found within Unity's Robot Factory asset pack has a rotator script that simply rotates the whole thing along the Y axis. void OnFixedUpdate() transform.Rotate (new Vector3(0, rotateSpeed Time.deltaTime,0)) Meaning that after slightly more than a full revolution, the Y rotation value should be more than 360 degrees, which it does end up becoming... Eventually. Thinking that was possible, I tried to mimic this behavior by making the arm rotate 720 degrees (twice) in an animation file (this is not using the rotator.cs script attached to the body in the example above). Instead, all I ended up was the arm's body staying still as 720 is the same as... 0 degrees in rotation changes. So, I tried a second experiment trying to rotate from 359 degrees to 1 degree (or 1 to 1 degree). Just like above, it didn't go to plan. When the animation is run, it simply runs from 359, through every angle in between before reaching 1, instead of 359, 360 (0) and 361 (1). If you don't get what I mean, see the diagram below. So, I was wondering, is there a way to allow for such rotation to be defined in an animation curve? Every time I try doing it, any value greater than 360 (or lesser than 0) is replaced by its co terminal counterpart that's between 0 and 359.999999...999.


Spawning random items to drop from the top of the screen I'm wondering how to make specific random objects drop. In my case, from the top of the screen. I have 16 objects, named recycle items 0 through recycle items 15. IEnumerator CreateRoutine() while (true) yield return new WaitForSeconds(3) CreateItems0() private void CreateItems0() Vector3 pos Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0)) pos.z 0.0f Instantiate(recycle items 0, pos, Quaternion.identity)


Unity Import a mesh that only has vertex and edge data but no faces I am working on a game that requires meshes that only have edges and vertices but no faces. In blender, you can make a mesh with only edges and vertices, but if you export it to FBX or OBJ, once it is imported into Unity, the resulting prefab has no mesh data linked to it. The prefab has no MeshFilter. It's as if I imported an mesh with absolutely no mesh data. For example, if I create a plane in Blender and then delete the face but leave the edges and vertices, and then export as OBJ, I can open the OBJ in a file editor. This is a square with no faces Blender v2.78 (sub 0) OBJ File '' www.blender.org mtllib egdes.mtl o Plane v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 l 3 1 l 1 2 l 2 4 l 4 3 So it appears that OBJ actually does export with the correct mesh data, however, it seems that Unity does not know how to import an OBJ if there are no faces. Does anyone know if anyone has come up with a solution to this problem yet? If not, I guess I'll just have to write my own parser. If that's the case, does anyone know if there is a way to extend or override Unity's built in OBJ parser?


How to find intersections using MapBox Unity SDK I'm currently using MapBox's Untiy SDK, which allows me to render 3D Buildings and roads. I want to place a gameobject at each intersection in an area. But, I'm having trouble finding a good way to do that. The roads are gameobjects attached to a quot Tile quot gameobect. The roads have a local position 0,0,0 with meshes on them that dictate their rendered position. A long road can cross multiple tiles, and thus the same quot road quot may exist as two or more gameobjects on two or more tiles. The Mesh itself is rectangular prism extruded from some line data by Mapbox. I have tried to use colliders with no success. For one, in order to get points of intersections between two colliders, they need to have rigidbodies attached to them and it's too expensive to do that, since there are hundreds of roads. Furthermore, many of the meshes have bad verts in them, which wont allow mesh colliders to work anyway, and box colliders wont work for non straight roads. Some road meshes are sprawling, twisting, and winding and could quot collide quot with a number of roads without actually touching them. I am not above brute force looping through every mesh's vertex in every tile to detect intersections, but I am as of yet unsure of the best way to do this or if it is necessary. I am also not sure if MapBox has some hidden feature for this the way Google Maps Unity SDK allows for access to the road lattice and intersections. If I could get some info about the line that represents the road, it would be easy to tell if roads overlap. The best way I can figure is to loop through the verts on a road to determine if the lines between verts overlap that of the roads within the same time, but am not sure if that is the best course of action


Spawning prefab when other prefab appears Im trying to make a bottle spawn when it is broken. This is the code that makes that public class romperobjetos MonoBehaviour public GameObject BrokenBottle public float breakVelocity 5f public GameObject NoBrokenBottle public bool rompible false public Vector3 oldPosition public Quaternion oldRotation public bool botellarota false public void Start() Use this for initialization public void Update() Debug.Log(NoBrokenBottle.GetComponent lt Rigidbody gt ().velocity.magnitude) if (NoBrokenBottle.GetComponent lt Rigidbody gt ().velocity.magnitude gt breakVelocity) rompible true else rompible false public void OnTriggerEnter(Collider other) if ((other.gameObject.name "Plane") amp amp (rompible)) oldPosition NoBrokenBottle.transform.position oldRotation NoBrokenBottle.transform.rotation Debug.Log("vamos bien") BreakBox() public void BreakBox() Instantiate(BrokenBottle, oldPosition, oldRotation) Debug.Log("se rompe") NoBrokenBottle.SetActive(false) botellarota !botellarota The broken bottle prefab has a boolean variable that is true when it appears, but the unbroken bottle doesn't instantiate. This is the script for the spawn public class SpawnBotellas MonoBehaviour public Transform spawnPoints public GameObject whatToSpawnPrefab public GameObject whatToSpawnClone public bool botella1rota false Use this for initialization void SpawnAlgo() whatToSpawnClone 0 Instantiate(whatToSpawnPrefab 0 , spawnPoints 0 .transform.position, Quaternion.Euler(0, 0, 0)) void Update() botella1 if (GameObject.Find("alidobas blanco roto").GetComponent lt alidobasrota gt ().alidobasblanco) Debug.Log("asdkj") whatToSpawnClone 0 Instantiate(whatToSpawnPrefab 0 , spawnPoints 0 .transform.position, Quaternion.Euler(90, 0, 0)) as GameObject Sorry for my bad English and thanks.


How do I get current emission intensity of a material in code? I'm unable to find how can I get current intensity level of emission in Unity. Is there some kind of method that can return its value? I need it to complete my algorithm's formula current color (intensity 10) 20


UI Bug After UI has interaction I am making a 3rd person game for pc. Space, of course, makes the player jump in game. For some reason if I interact with my menu at all and then press space it will open my menu back up. This doesn't happen if I don't interact with the UI first though. I don't know if this is a bug or what but my code does not contain anything that would take input from the keyboard in general so the space bar interacting with it doesn't make sense. Has anyone seen this issue before?


Animator.SetBool am I supposed to call it only when its value changes? I've searched around the web for a while, but didn't manage to find anything about it. Despite using Animator in several projects so far, I've never been in this exact situation, so I'm unsure what to do. Does calling Animator.SetBool have any performance issue, so that I'd better call it only when its value has changed, or when its value doesn't change it's so quick that I can call it every frame? Keep in mind that, due to the nature of this question, I don't care if it's slow when I change its value, I only care if it's slow when it's false and I call it to set it to false again (same thing for true ofc).


Sort Textures by name before looping through them im using a system to get textures from the device persistent data path and assign them to an array in order to show them in the game scene. So far everything works as expected, images are getting pulled into the array and are selected based on the level index. My issue is that on some android devices each time the image is loaded its either random or its a different image than it should be. public void LoadTextureArray(string dirname) var fileNames Directory.GetFiles(Application.persistentDataPath quot quot dirname quot quot , quot .jpg quot ) source new Texture2D fileNames.Length int index 0 foreach (var fileName in fileNames) source index LoadTextureFromPath(fileName) source index .name fileName index public Texture2D LoadTextureFromPath(string path) if (string.IsNullOrEmpty(path)) Debug.LogError( quot Texture path is null or empty quot ) return null if (!File.Exists(path)) Debug.LogError( quot File not found path quot ) return null byte bytes File.ReadAllBytes(path) Texture2D texture new Texture2D(2048, 2048, TextureFormat.RGB24, false) texture.LoadImage(bytes) Debug.Log( quot success quot ) return texture and i assign them based on another variable with this code here if (LevelSystemManager.Instance.CurrentLevel lt source.Length) selectedText source LevelSystemManager.Instance.CurrentLevel DifficultySet() Debug.Log( quot selected Texture Name is quot selectedText.name) The LoadTextureArray function is called on Awake and on Start i do the assignment based on that index. Now in both Unity editor and my phone everything works fine and no matter how many times i load the level its the same image. Whereas on my wifes it either skips a couple of images from the array (displaying the 5th for instance as index 1) or everytime i open the level i see a different one! Thank you! Edit it seems my problem is that i need to sort them out before assigning them to that array so any help would be appreciated!


How to implement a button when the player is in the trigger I have implemented this code and it works but i wanna make this work only if i enter the trigger and press the UI button. Right now it is changing scene automatically so, i want to press the button and then change scene. I know how to do this for PC game but not on Android game. I hope you can give me a hand. Script public class ButtonScript MonoBehaviour public Button btn private bool door false public bool hasCollided false public void Update () if(door true) SceneManager.LoadScene("InventoryScene") SceneManager.LoadScene ("Scene1AToBathW") Application.LoadLevel("Courtyard1F") gameObject.transform.position new Vector3(x,y,z) public void OnTriggerEnter(Collider other) if(other.tag "Player") btn.gameObject.Setactive(true) door true hasCollided true public void OnTriggerExit(Collider other) if(other.tag "Player") btn.gameObject.Setactive(true) door false hasCollided false


Shaderlab and Cg API reference I am looking for definitive information on Shaderlab's API and the Cg language. The documentation I have found so far has been by way of example programs rather than a definition of APIs. Also, searching for a specific API term such as Sampler2D didn't turn up anything definitive. What reference documentation is available or possibly documentation of precursors to Shaderlab and Cg?


Why does ForceMode.VelocityChange work but not Rigidbody.velocity ... in script? I have a FPS movement script that I created that has a jump function that looks like this public void Jump() if (jumpAble amp amp grounded) jumpAble false gameObject.GetComponent lt Rigidbody gt ().velocity (Vector3.up jumpForce Time.deltaTime) For some reason, this does not make the player jump. However, replacing the .velocity ... to gameObject.GetComponent lt Rigidbody gt ().AddForce(Vector3.up jumpForce Time.deltaTime, ForceMode.VelocityChange) makes the player jump. Why is this? I'm under the impression that the two are essentially the same thing, but is there a slight difference? Also, not sure if it affects the function, but this is the whole script public class Player Movement MonoBehaviour public Transform camera public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask public bool grounded public GameObject joystick public bool isWalking false public bool isRunning false public float walkForce 12f public float runForce 30f public float jumpForce public bool jumpAble true public GameObject playerRotationHandler public float cameraTouchSensitivity public Animator animator Update is called once per frame void Update() grounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if (grounded) jumpAble true Vector3 direction joystick.GetComponent lt Joystick gt ().inputDirection.x transform.right joystick.GetComponent lt Joystick gt ().inputDirection.y transform.forward if (isRunning) gameObject.GetComponent lt Rigidbody gt ().velocity (direction runForce Time.deltaTime) else if (isWalking) gameObject.GetComponent lt Rigidbody gt ().velocity (direction walkForce Time.deltaTime) else gameObject.GetComponent lt Rigidbody gt ().velocity Vector3.zero public void Jump() if (jumpAble amp amp grounded) jumpAble false gameObject.GetComponent lt Rigidbody gt ().velocity (Vector3.up jumpForce Time.deltaTime) gameObject.GetComponent lt Rigidbody gt ().AddForce (Vector3.up jumpForce Time.deltaTime, ForceMode.VelocityChange) public void Rotate(float xMoveValue, float yMoveValue) float xRotation Mathf.Atan2(yMoveValue, cameraTouchSensitivity) Mathf.Rad2Deg float yRotation Mathf.Atan2(xMoveValue, cameraTouchSensitivity) Mathf.Rad2Deg playerRotationHandler.transform.Rotate(xRotation, 0, 0) transform.Rotate(0, yRotation, 0, Space.World) if (playerRotationHandler.transform.localEulerAngles.x lt 300 amp amp playerRotationHandler.transform.localEulerAngles.x gt 60) if (xRotation lt 0) playerRotationHandler.transform.localEulerAngles new Vector3(300, playerRotationHandler.transform.localEulerAngles.y, 0) if (xRotation gt 0) playerRotationHandler.transform.localEulerAngles new Vector3(60, playerRotationHandler.transform.localEulerAngles.y, 0)


How to reset scene (stage1) when selecting it from Level stagemain menu Good day I have a problem when the player finish stage 1 the screen look like this Then going back to selecting level When I try to play the stage 1 again. I want to reset the stage 1 so i can play it again. I only use Scene.LoadScene("stage1") in main menu to go to stage1 and Scene.LoadScene("mainmenu") to back to main menu


Unity, Pixel Perfect and Scaling I am totally stuck on with pixel perfectness of the game. I have tried a few pixel perfect camera assets, but they have lots of issues considering scalability. is it normal that these cameras zoom in and out, instead of scaling the camera screen when using different resolutions for the game. Because this is a huge problem for me, cause i need to make a game for aspect ratio of 16 10, and every resolution that has the same aspect ratio is needed to scale it correctly keeping the pixel perfectness. The ortographic camera size is dependent of screen width (width PPU 2) So it always zooms in or out with different resolutions. Question is Is there a way to make it scale the game sprites instead of zooming the view?


How can I move number of objects between two points with random speed? In the Hierarchy I have a Cube and the script is attached to the cube. And I also have in the Hierarchy two spheres as waypoints. public class WP MonoBehaviour public Transform waypoints public float movingSpeed GameObject allLines GameObject duplicatedPrefabs private void Start() allLines GameObject.FindGameObjectsWithTag("FrameLine") DuplicatePrefabEffects(allLines.Length) duplicatedPrefabs GameObject.FindGameObjectsWithTag("Duplicated Prefab") private void DuplicatePrefabEffects(int duplicationNumber) for (int i 0 i lt duplicationNumber i ) var go Instantiate(prefabEffect) go.tag "Duplicated Prefab" go.name "Duplicated Prefab" private void MoveDuplicated() for (int i 0 i lt duplicatedPrefabs.Length i ) duplicatedPrefabs i .transform.position Vector3.Lerp(pointA.position, pointB.position, movingSpeed Time.deltaTime) void Update() MoveDuplicated() The duplicatedPrefabs are moving very very fast no matter what value I put for movingSpeed and then they are all stuck in the second waypoint and seems like moving on very specific small area on the second waypoint. What I want to do is to move them smooth slowly between the two waypoints and with random speed range from each object. For example one will move at speed 1 the other on speed 20 third on speed 2.


Clone gameobject on drag without having to click a second time I have a standard Cube gameObject (with a BoxCollider and my CubeController.cs script) in my scene and I want to be able to click and drag on it to instantiate a new cube prefab (with a BoxCollider and my DragController.cs script) which then follows the mouse. I have it nearly working but when the new cube prefab is instantiated at the same position as the clicked cube (but 10 bigger) you have to then click the new instantiated object again to begin dragging it. I have a debug line printing 'Prefab created' in DragController.cs so the prefab must be sensing that the mouse button is still down. How can I do it so you click the original cube then the new prefab is created and draggable without having to click again? CubeController.cs placed on original Cube gameobject using UnityEngine public class CubeController MonoBehaviour RaycastHit hitInfo Ray ray public GameObject CubePrefab private bool canCreate true Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hitInfo)) GameObject objectHit hitInfo.transform.gameObject if (objectHit.tag "Cube") createCubePrefab() void createCubePrefab() if (canCreate) canCreate false GameObject newCube Instantiate(CubePrefab, hitInfo.transform.position, Quaternion.identity) newCube.transform.localScale new Vector3(1.1f, 1.1f, 1.1f) DragController.cs placed on Cube prefab that is going to be instantiated using UnityEngine public class DragController MonoBehaviour private Vector3 screenPoint private Vector3 offset Start is called before the first frame update void Start() if (Input.GetMouseButtonDown(0)) Debug.Log("Prefab created") void OnMouseDown() screenPoint Camera.main.WorldToScreenPoint(gameObject.transform.position) offset gameObject.transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)) void OnMouseDrag() Vector3 cursorPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) Vector3 cursorPosition Camera.main.ScreenToWorldPoint(cursorPoint) offset transform.position cursorPosition


GUI.DrawTexture problem in Unity I'm having a problem with GUI.DrawTexture() and I'm looking an alternative function to draw 2D Texture Images. The problem I have is that my textures draw above all other objects and when my camera moves, the images move with the camera, keeping their relative position inline with the cameras position. using System.Collections.Generic using System.Drawing using System.Drawing.Imaging using UnityEngine public class AnimatedGifDrawer MonoBehaviour public string loadingGifPath public float speed 1 public Vector2 drawPosition List lt Texture2D gt gifFrames new List lt Texture2D gt () void Awake() var gifImage Image.FromFile(loadingGifPath) var dimension new FrameDimension(gifImage.FrameDimensionsList 0 ) int frameCount gifImage.GetFrameCount(dimension) for (int i 0 i lt frameCount i ) gifImage.SelectActiveFrame(dimension, i) var frame new Bitmap(gifImage.Width, gifImage.Height) System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty) var frameTexture new Texture2D(frame.Width, frame.Height) for (int x 0 x lt frame.Width x ) for (int y 0 y lt frame.Height y ) System.Drawing.Color sourceColor frame.GetPixel(x, y) frameTexture.SetPixel(frame.Width 1 x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)) for some reason, x is flipped frameTexture.Apply() frameTexture.LoadImage. gifFrames.Add(frameTexture) void OnGUI() GUI.DrawTexture(new Rect(drawPosition.x, drawPosition.y, gifFrames 0 .width, gifFrames 0 .height), gifFrames (int)(Time.frameCount speed) gifFrames.Count ) The code above is designed to draw animated GIFs using System.Drawing.dll in Unity


Why the canvas text is gray and not really white? This script change the text color to white using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DisplayInfo MonoBehaviour public string myString public Text myText public float fadeTime public bool displayInfo false Use this for initialization void Start() if (myText null) Debug.LogError(myText " Is null please add Text component !") if (myString "") Debug.LogWarning(myString " Is empty, No text will be display.") myText.color Color.clear Update is called once per frame void Update() FadeText() void FadeText() if (displayInfo) myText.text myString myText.color Color.Lerp(myText.color, Color.white, fadeTime Time.deltaTime) else myText.color Color.Lerp(myText.color, Color.clear, fadeTime Time.deltaTime) This is the script i'm using with the DisplayInfo using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public DisplayInfo displayInfo public Canvas canvas private RaycastHit whatObjectHit private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true displayInfo whatObjectHit.collider.gameObject.GetComponent lt DisplayInfo gt () displayInfo.displayInfo true else image.color Color.white if (displayInfo ! null) displayInfo.displayInfo false else image.color Color.white if (displayInfo ! null) displayInfo.displayInfo false When it's "Interactable" then i display the info about this object. The DetectInteractable is attached to the Player (FPSController) in the hierarchy And on each "Interactable" item i attach the script DisplayInfo For example the door And this is the editor screenshot before running the game Display Infomration is Canvas. The Text i set it's color to white in the inspector. But when running the game the text i see on objects is gray and i see that on the inspector the white is becoming gray On the game view window there is a text Security Door in fray it's hard to see it. It should be in white and bright enough to see it clear


Why does my Outlined Diffuse 3 shader seem "detached" at a distance? I'm using the Outlined Diffuse 3 shader from Unity and I'm having a problem with it the outline looks great when the camera is near the object, but at a distance, it looks detached. From nearby (looks good) From afar (looks bad see the shelf and books) How can I fix this graphical anomaly?


How can I make outline shader like "Life is Strange"? I want to make sketch shader like life strange. shader has two part 1.animated dashed line 2.noisy outline I like to know how can I make noisy outline? see outline of objects First I tried to make outline by copying of incoming vertex data and scaled according to normal direction then Cull Back.but I think it's something like Image effect because outline sometimes move inside of object. anyway I will appreciate if someone help me to Implement this shader ) What I tried I used edge detection and animate it by vertex shader but this isn't good like above gifs.


Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences? The first script the manager is attached to new empty gameobject I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager using System.Collections using System.Collections.Generic using UnityEngine public class DialogueManager MonoBehaviour public DialogueTrigger dialoguetrigger private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () dialoguetrigger.TriggerDialogue() DisplayNextSentence() public void StartDialogue(Dialogue dialogue) Debug.Log("Starting conversation with " dialogue.name) sentences.Clear() foreach(string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() Debug.Log(sentence) void EndDialogue() Debug.Log("End of conversation.") Next the DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue() FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Last the Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue public string name TextArea(3, 10) public string sentences In the editor I filled the all 3 TextAreas each one with a sentence. Hello world Hi everyone I have woke up When running the game it's showing only to the Hi everyone it's not showing the I have woke up. And it also not showing the "End of conversation." in the log.


Ignore UI elements when clicking to move I have a click to move character that uses a Nav Mesh Agent and I want to ignore clicks that are made on UI elements. For example, I don't want clicking around in my inventory to move my player to the target under the inventory. The relevant part of the move script is very simple. if (Input.GetMouseButton(0) amp amp !playerHealth.isDead) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) navMeshAgent.destination hit.point I would think that this is a common question raised among beginner developers or that it would be covered in beginner courses, but I can't seem to find the info I'm looking for when Googling around, so I'll ask it here. So how do I get my Nav Mesh Agent to ignore clicks made on a particular UI element? How about ignoring clicks made to any and all UI elements? Thanks.


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


How to transition between "rooms" virtual cameras on a button press? I'm trying to make a game that navigates like the example here I'd like it so that after combat, the player can push the button corresponding with an exit (left, right, up, down) and navigate like in this game. Also I eventually hope to randomize each run of the game so it would hopefully have some flexibility outside of being hard baked. I've seen examples of it being done with a player object and a collider, but the player won't actually be moving their character. I like this style of navigation because I think it still provides the joy of exploration for the player, but is more friendly of a navigation system for a novice like me. How would I implement something like this?


How do I load Player position as new gameobject? I want to make game like time travel, the player has the ability to go to the future by limited time, for that, I want to add some game mechanic like save the player position. Additional information ignore the red text. When pressing the button the player will create a new platform and immediately teleport to the original position. After the player teleported, the player will save the new platform as the new teleport position. after 2 seconds or pressing a button. the new platform will disappear and the player will return to the platform position. I have this playerController Script and I already implement the save position, but I don't know how to make it like what I explain. public Rigidbody2D theRB public float speedMovement public GameObject prefabGameObject Space(10) private BoxCollider2D boxCollider2D SerializeField private LayerMask GroundMask public float jumpVelocity Space(10) public float past public float future Space(10) public float hor Start is called before the first frame update void Start() theRB gameObject.GetComponent lt Rigidbody2D gt () boxCollider2D transform.GetComponent lt BoxCollider2D gt () Update is called once per frame void Update() PlayerPosSaveLoad() PlayerMovement() PlayerJump() public void PlayerMovement() hor Input.GetAxis( quot Horizontal quot ) if (hor gt 0 hor lt 0) theRB.velocity new Vector2(hor speedMovement Time.deltaTime, theRB.velocity.y) if (hor gt 0) transform.localScale new Vector2(1f, transform.localScale.y) Animation Debug.Log( quot ToTheright quot ) else transform.localScale new Vector2( 1f, transform.localScale.y) Animation Debug.Log( quot ToTheLeft quot ) public void PlayerJump() animation if (isGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) theRB.velocity Vector2.up jumpVelocity public bool isGrounded() float extraHeighText .1f RaycastHit2D raycast2d Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, boxCollider2D.bounds.extents.y extraHeighText, GroundMask) Color raycolor if (raycast2d.collider ! null) raycolor Color.green else raycolor Color.red Debug.DrawRay(boxCollider2D.bounds.center, Vector2.down (boxCollider2D.bounds.extents.y extraHeighText), raycolor) return raycast2d.collider ! null SerializeField private Vector2 saveThisPosition public void PlayerPosSaveLoad() if (Input.GetKeyDown(KeyCode.E)) saveThisPosition transform.position SpawnGameObject() if (Input.GetKeyDown(KeyCode.Q)) SwitchWithsavedPosition() Destroy(prefabGameObject) private void SwitchWithsavedPosition() Vector2 temp transform.position transform.position saveThisPosition prefabGameObject.transform.position temp public void SpawnGameObject() Instantiate(prefabGameObject, transform.position, transform.rotation) And this is the Camera Script because connected with the player. lang cs public Transform Player Start is called before the first frame update void Start() Update is called once per frame void Update() transform.position new Vector3(Mathf.Clamp(Player.position.x, 7.3f, 7.3f), Mathf.Clamp(Player.position.y, 1f, 2f), transform.position.z)


Unity adding objects through script to scrollview (SetParent) Objects overlap I need to add X objects to a scrollview. I do it like this GameObject statsObject Instantiate(instance.statsObjectPrefab) statsObject.transform.SetParent(statsParent.transform) statsParent is the content container if the scrollview. Scrollview Viewport Content This is statsParent In the pause I see that then objects are added successfully, but they all overlap and no scrollbar is visible. The content has a content size fitter and a vertical layout group, but I tried now all settings and the result is always the same. I use Unity 2019.2


How to set the force applied to RigidBody2D depending on the time user holds touch on screen? I trying to make an object jump from 1 point to another point. How far it jumps depends on how long the player holds the touch anywhere on the screen. It jumps when player releases his touch. At the code below,I able to detect the moment player release his finger. if (Input.touchCount gt 0) Touch touch Input.GetTouch(0) Handle finger movements based on touch phase. switch (touch.phase) Finger start touching the screen case TouchPhase.Began print("Start tapping") break Finger leaving the screen case TouchPhase.Ended when finger release, the object jump float rightForce Time.deltaTime 10000 2 float jumpForce Time.deltaTime 30000 2 box2D.AddForce(new Vector2(rightForce, jumpForce), ForceMode2D.Force) break As you can see I able to get the Time.deltaTime which is I assume is how long the player hold the screen. What I want to do is calculate the rightForce and jumpForce added to the object depending on the Time user hold the touch. float rightForce Time.deltaTime 10000 2 float jumpForce Time.deltaTime 30000 2 Because if I use the 2 line of code above, the result will be almost the same everytime. So what is the correct way to determine the rightForce and jumpForce depending the time user hold touch?


How to calculate the reachable space of the end effector in an IK chain? I have an array of points in a 2d worldspace and I want to calculate which points are reachable by the end effector of a limb controlled with a CCDIK chain (with rotation limits applied). It's a limb with 2 hinges (upper arm amp lower arm) The upper amp lower arm have a fixed length The 2 hinges have fixed rotation limits This needs to be recalculated every update (continuously) as the limb is attached to a moving body I work in Unity using C Crude Illustration of the problem My idea sofar is to create a polygon collider along the outer edges of the reachable space, and then look if the points are within the bounds of that collider. But I have no idea if this is the smartest solution, or if so, how to achieve this. How could I solve this issue?


How can I toggle between single shots when clicking the mouse left button and automatic none stop shooting when clicking the mouse right button? I'm talking in build not in editor ! using System using System.Collections using System.Collections.Generic using UnityEngine public class Shooting MonoBehaviour SerializeField private Transform firePoints SerializeField private Rigidbody projectilePrefab SerializeField private float launchForce 700f SerializeField private Animator anim SerializeField private bool automaticFire false SerializeField private bool slowDownEffect false private void Start() anim.SetBool("Shooting", true) public void Update() if (isAnimationStatePlaying(anim, 0, "AIMING") true) if (Input.GetButtonDown("Fire1") automaticFire false ) automaticFire false if (anim.GetBool("Shooting") true) anim.Play("SHOOTING") LaunchProjectile() else if ( automaticFire true amp amp Input.GetButtonDown("Fire2")) automaticFire true if(automaticFire true) anim.Play("SHOOTING") LaunchProjectile() private void LaunchProjectile() foreach (var firePoint in firePoints) Rigidbody projectileInstance Instantiate( projectilePrefab, firePoint.position, firePoint.rotation) projectileInstance.AddForce(new Vector3(0, 0, 1) launchForce) projectileInstance.gameObject.AddComponent lt BulletDestruction gt ().Init() bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName)) return true else return false I tried to do it in the Update using the automaticFire variable but it's not working fine. When clicking first the left mouse button it's shooting singles but then when clicking the mouse right button it's shooting automatic but then when clicking the left mouse button again it's not back to single shots again it's staying on automatic. The idea is right click mouse button automatic fire left button each time clicking the left mouse button the automatic should stop and then single shots with the left mouse button. And this way to toggle between the Fire1 and Fire2. Fire1 left mouse button click Fire2 right mouse button.


blender imported sphere with mesh collider not collided here is the scene i imported a sphere (the blue sphere) from blender (with a hole at back), i added a mesh collider on it but it has no effect, and there is an error message Cooking cookConvexMesh user provided hull must have less than 256 vertices!. any ideas? (update the collider work fine after i retry and retry, but the error message still stay)


Images disappear when camera zooms in there is no problem when the camera is away, but as I zoom in to the game, the images disappear and I can't see the game properly. What is the reason ?


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.


Find random point on a circle with a radius of x and the players position as center (unity) First of all please note that the game is in 3d and Not 2d The image below is seen from above. What I am trying to do is find a random point 2 3 meters around the player. However I am not quite sure how to achieve it I have tried the following Vector3 randomPointOnCircle Random.insideUnitSphere randomPointOnCircle.Normalize() randomPointOnCircle radius return randomPointOnCircle However I am not sure how to set the player as the center? Star Player Square the general ground Circle A visual representation of where the points should be around the player


Unity Raw Image ui not showing when small I have some Images online that I download using WWW class and the use as UI elements. So far all of them where working perfectly but now the one I added recently is acting up. First you should know that all of the images are being downloaded by the same script and handled by that so there should be no difference between their materials and stuff AFAIK (if I'm missing something please tell me). Second , the problem is that this particular image only shows up when it's taking more than one sixth of the screen, for example if I make it bigger by changing it's size in the inspector, or if I go to scene view and zoom in on it, it starts to fade in the larger it gets on the screen. Also, I changed the picture to something that was working properly to make sure it's not from the image. public IEnumerator AddTools(Tool Tool) Texture2D T new Texture2D(4, 4, TextureFormat.DXT1, true) SpriteTool ST new SpriteTool() ST.TheTool new UnityEngine.Texture() ST.ID Tool.ID ST.ToolName Tool.Name ST.Type Tool.Type WWW wWw new WWW(Tool.Url) while (!wWw.isDone) yield return wWw.progress wWw.LoadImageIntoTexture(T) ST.TheTool T ST.TheTool.name Tool.Name SpriteTool PA ObjectTools.SingleOrDefault(p p.ID ST.ID) The SpriteTool Type is a class I made for storing some of the information needed to build the UI element later. private GameObject CreateButton(SpriteTool item null, float angle 0) Texture2D T2D (Texture2D)item.TheTool T2D.SetPixels(T2D.GetPixels(0, 0, T2D.width, T2D.height)) T2D.Apply() GameObject Tool new GameObject() Tool.transform.SetParent(GUICanvas.transform) There was some code for positioning the element and resizing it that I did not include but I can see in the scene view that the size and the position are what they supposed to be so that's not the problem Tool.AddComponent() The type is RawImage Tool.GetComponent().texture T2D the type is RawImage


Weird texture applied So I applied the baked texture (on the right side of screen shot) but it shows in this manner. What is the problem? I made the model in Blender and also the baked image. The house consists of multiple separate objects.


How to iterate through the frames of an AnimationClip in editor mode I'm working on a 2D game, using spritesheets as the basis for four AnimationClips. (Every frame from the spritesheet is a keyframe in the animation.) I'm trying to step through the frames of these AnimationClips and programmatically create Collider2Ds which fit the dimensions of each frame. The problem is, I'm having an impossible time actually iterating through the frames. My character has an Animator component, with 4 different states. I've tried various inputs to my editor script, but the closest I've gotten has an AnimationClip as input private AnimationClip clip set in inspector private GameObject targetForColliders set in inspector void createColliders() Animation animation new Animation() AnimationUtility.SetAnimationClips(animation, new AnimationClip clip ) foreach (AnimationState state in animation) do useful things here Unfortunately, somehow the animation local variable is null, crazy as that sounds. I've confirmed that by both logging it and attempting to use it, which causes a NullReferenceException every time. I can't access the Sprite containing the spritesheet directly, because I've made manual adjustments within Unity to the keyframes (removing some, duplicating others) and I don't want to have to manually sync my colliders with the modified assets. Has anyone attempted to do something similar to this before? tl dr What's the easiest way to iterate through the frames of a 2D animation in an editor script?


Understanding Scriptable Objects I am trying to understand the logic and functionality behind Scriptable Objects. I 've watched the provided video 2 times and I keep getting lost. I tried to follow the code as well but with no luck. Can someone please explain to me what the Scriptable Objects are and how they work in a few lines? EDIT This Video as well as the following answers helped me understand Scriptable Objects and even better incorporate them in my own game.


Unity When attaching my custom camera script camera shakes when player starts to move fast Here is my player code. Rigidbody rb Vector3 currMovement public float jumpSpeed 10 public float moveSpeed 10 public float rotSpeed 180 float distToGround public float posSmoothTime 0.5f float currPos float targetPos float posVel public float rotSmoothTime 0.5f float currRot float targetRot float rotVel void Start() rb GetComponent lt Rigidbody gt () distToGround GetComponent lt Collider gt ().bounds.extents.y bool isGrounded() return Physics.Raycast(transform.position, Vector3.down, distToGround 0.1f) void Update() Move() void Move() Rotation smoothing. targetRot Input.GetAxisRaw("Horizontal") rotSpeed Time.smoothDeltaTime if (targetRot gt 360) targetRot 360 if (targetRot lt 0) targetRot 360 currRot Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, rotSmoothTime Time.smoothDeltaTime) transform.eulerAngles new Vector3(0, currRot, 0) Movement smoothing. targetPos Input.GetAxisRaw("Vertical") moveSpeed currPos Mathf.SmoothDamp(currPos, targetPos, ref posVel, posSmoothTime Time.smoothDeltaTime) currMovement new Vector3(0, 0, currPos) currMovement transform.rotation currMovement if (isGrounded()) if (Input.GetButtonDown("Jump")) rb.velocity Vector3.up jumpSpeed rb.position currMovement Time.smoothDeltaTime I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script. public Transform player Quaternion targetLook Vector3 targetMove public float smoothLook 0.5f public float smoothMove 0.5f public float distFromPlayer 5, heightFromPlayer 3 Vector3 moveVel void LateUpdate() CameraMove() void CameraMove() targetMove player.position (player.rotation new Vector3(0, heightFromPlayer, distFromPlayer)) transform.position Vector3.SmoothDamp(transform.position, targetMove, ref moveVel, smoothMove) targetLook Quaternion.LookRotation(player.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, targetLook, smoothLook) The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.


Overridden movement function doesn't work I moved from C to C so I am a novice in Object Oriented Programming. I wanted to implement OOP in my character movement, but it didn't work the way I expected. My character is instantiated when the scene starts, but it doesn't move (maybe because of bad parameter passing). I just want to control input from derived class which is giving my character the ability to sprint. characterB script is attached to character in Inspector that character is instantiated prefab and is instantiated when scene start inherited script which is overridden is giving ability to sprint to character photon is package for multiplayer games so you don't have to notice it whole source code is so big, so i put there one method for movement and sorry for my weak english skillz works like standard MonoBehaviour public abstract class characterMain MonoBehaviourPunCallbacks declaration of variables public virtual void Start() RB GetComponent lt Rigidbody gt () protected virtual void movement(float horXF, float vertYF, bool sprintB) Debug.Log( quot movement function base class quot horF) NOT responding groundDetect Physics.Raycast(...) if (standOnGround) direction new Vector3(horXF, 0, vertYF) Time.deltaTime speed direction.Normalize() adjustSpeed speed targetSpeed transform.TransformDirection(direction) adjustSpeed Time.deltaTime RB.velocity targetSpeed public class characterB characterMain Header( quot Movement quot ) protected float horXF protected float vertYF Header( quot sprint quot ) private bool sprintB public void FixedUpdate() if (!photonView.IsMine) return Photon MOVEMENT INPUT horXF Input.GetAxisRaw( quot Horizontal quot ) vertYF Input.GetAxisRaw( quot Vertical quot ) JUMP INPUT skokB Input.GetKey(KeyCode.Space) movement(horXF, vertYF, sprintB) Debug.Log( quot movement function quot horF) responding protected override void movement(float horXF,float vertYF,bool sprintB) Debug.Log( quot movement function quot horF) NOT responding if (sprintB amp amp ... ) sprint base.movement(horXF, vertYF, sprintB) sprintB bZrychlenieC amp amp groundDetect amp amp ... if (sprintB) direction new Vector3(0, 0, sprintSpeed) Time.deltaTime


Make Unity GUI for mobile phones only? I'm using Unity and I want to make a responsive GUI for portrait resolution only. Now I'd like to know if this is a good or bad idea when I force the user to play my game in portrait mode only. Shall I use autorotate? The problem is that when you use landscape mode my GUI looks really shitty. I have some background images and I'd like to know if I should save them for the highest resolution available in mobile devices (like tablets)? Or shall I ditch the tablets and develop the GUI with the background images for mobile phones only? TIA


Is it possible to prevent the collider 2D outline from hiding in Unity? Is it possible to prevent the collider 2D outline from hiding in Unity? I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation. In my case the collider outline is red I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow?


Line renderer in 3D sorting order I'm using a line renderer as a laser aim for my character. If the aim hits an object it ends at that object. If the aim doesn't hit an object it continues a predefined distance. If I aim at an object it works fine, if I stand behind the object it also works, but if I stand in front of it, the line is rendered behind the object creating the illussion that the character stands behind the object. If I change the sorting order for the line I can make it to be in front of the object, but this is a bit tedious because then it will be in front of this object when it is in fact behind it. In the screenshot below a line is drawn from the picked up C4 which is in front of the pillar, but the line is drawn behind the pillar. Is there any way to solve this issue with a line renderer? I've been thinking of just using a cube and stretch it instead. Thanks in advance! Update 1 I made a cube solution instead, but soon realized that the issue is with a shader that is set to fade transparent and that this is due to sorting order. How can I dynamically change the sorting order in code so that my moving transparent object always appear in the correct place? Update 2 I noticed that my own answer below isn't working 100 . It works for most scenarios but if I'm standing at origo and aiming behind a pillar the sight is rendered in front of the pillar. In the image below it is clearly visible from the top view that I'm aiming behind the pillar. (This is done with a deformed cube, the line renderer had even more issues).


Unity 5.5 and Parse 1.7.0 on iOS 64 bit We are using Unity 5.5 and Parse 1.7.0 (and Firebase for notifications) which doesn't have "Parse.Unity.dll" and while on Editor everything is working fine but when we build using "IL2CPP" on iOS while running on device the game produces an error of "MissingMethodException No constructor found for Parse.Common.Internal.FlexibleListWrapper 2". I think it's because of stripping, I've tried to include "Parse.Core" and "Parse.Common" in "link.xml" but still same error while I was looking for solutions I found that there's a file "Parse.Unity.dll" that should have been in the project from the start but when I try to include it in our project another error but this time in Unity Editor that says "System.Threading.Tasks.Task is defined multiple times" and that's because I think the new Parse.Unity.dll and Unity.Task.dll from Firebase, if I try to delete that firebase Dll another error appears.... Please any help is appreciated ( We have to build with il2cpp to upload on the App store, Android version works fine.