Isometric coords to cartesian coords I'm new to the tilemap feature of Unity, and I'm having a hard time with all those coords. I created a new project, added an isometric tilemap and left all values to their default. In the Unity Editor (and in game at runtime as well), the coordinates of the cells are like this This is pretty disturbing to me and it will be to most players (not programmers) too I guess. I would like something like this However, I can't figure out how to do the transformation. I tried this Vector3 currentWorldPos Camera.main.ScreenToWorldPoint(Input.mousePosition) Vector3Int currentCellPos grid.WorldToCell(currentWorldPos) This gives the coordinates as in the Unity Editor except for z currentCellPos.z 0 Set z to 0 so the coordinates of the cell are exactly as in the Unity Editor Vector3 cartesianCellPos new Vector3((2 currentCellPos.y currentCellPos.x) 2, (2 currentCellPos.y currentCellPos.x) 2, 0) Try to transform the Unity coordinates into cartesian coordinates WRONG RESULT But this calculation gives weird results, not what I expect at all. Do you know how I could transform the Unity coordinates shown in the first screenshot into the coordinates shown in the second screenshot?


For creating a distant moon in a 3D game, is it better to use a model or texture? I'm working on my indie game and I want to create a moon (it's a 3D game) however I am unsure if I should create a model and put it far away, or if I should use a texture on a plane and have it constantly move so the face of the plane is facing the player. The problem I had last time I tried a model is the render view, as the model was really far away (as when I did it very small, you could sort of tell it was a tiny model rather then a far away moon) and with the texture I'm not sure if it comes across as tacky. I'd really like to hear the pros and cons of each, since I'm planning to use the 'render objects only when in view' method and basically want advice on which I should go with.


Changing alpha of Sprite I'm using OnGUI to draw a rect when I "box select" or "drag select". The texture that gets drawn is a PNG file made in Paint.Net with the opacity alpha channel set quite low. In Unity however, when I go to box select, the texture is completely opaque. How do I get Unity to honor the alpha set in Paint.Net? I also wouldn't mind using Unity itself to adjust the opacity, but I haven't found such an option in the import texture part of the inspector.


How Can I Fix Where The Tile Spawns? I am making a 3D game in Unity and C . I want to spawn another tile when the player is at the end of the current tile. But when I spawn the next tile it doesn't spawn at the right place(just after the current tile). How can I fix this? Thanks Old Code using System.Collections using System.Collections.Generic using UnityEngine public class Terrain MonoBehaviour public List lt GameObject gt objs new List lt GameObject gt () public GameObject terrain public GameObject player private float z 4130.875f private float safeZone 260.0f private float tileLength 260.0f private int animTilesCount 2 void Start() for (int i 0 i lt animTilesCount i ) spawnTile() void Update() if (player.transform.position.z safeZone gt (z objs.Count tileLength)) spawnTile() DeleteTile() public void spawnTile() GameObject go go Instantiate(terrain) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward z Debug.Log(z) Debug.Log(Vector3.forward z) Debug.Log(go.transform.position) go.transform.rotation terrain.transform.rotation objs.Add(go) z tileLength public void DeleteTile() Destroy(objs 0 ) objs.RemoveAt(0) That's the position of the current tile. The correct position for the next tiles would be (6.103516e 05, 3.051758e 05, z). They have to spawn after the current tile.


How to fix this unexpected movement? I am facing a problem below is the detail. There are two scripts(actually more than two but these have the problem) Cannon.cs and Launch.cs and three buttons(up, down, and launch) to move cannon and launch the bullet. Cannon have bullets and each bullet has Launch.cs attached also a RigidBody2D. When specific event occurs the Cannon.cs calls the Launch.cs's Launch(direction) method. Parameter "direction" Cannon.transform.right. Bullets are being instantiated dynamically and are stored in the list Cannon.cs take one bullet and fires it(firing includes calling the Launch(direction)) . Launch(direction) will always be called once no matter what also to double sure myself I destroy the launch script on launch. The problem is once the bullet is fired or launched in the direction specified by the direction of cannon(since direction cannon.right) and I click on the up or down button the launched bullet changes its direction which should never happen because Launch() method is called only once in the lifetime of the bullet and also I detach the Launch.cs script on launch. I am using rigidbody2D.velocity direction thrust what I think is that rigidbody2D.velocity once called will possess the direction just like a method called by reference. I am totally lost I hope I made my question clear please do help me if you can.


What causes this graphics quality difference between WebGL Build and Unity 5 Editor? The Editor version and WebGL version of my Minesweeper clone have some graphics quality differences. I chose 'Fast' option when building this deployment. Is this the difference between 'Fast' and 'Fastest' options of Optimization Level in Build Settings, meaning that if I choose the 'Fastest' option, the WebGL deployment will be the same as Editor version, unlike below? If not, why this happens?


Is there a way to convert a shader code to shader graph? I would like to ask if there is a way to convert a Coded shader into the new Shader graph, beacause i want to edit my shaders in more efficient way. Any help is appreciated.


Spawn system not working correctly I try to spawn one or two obstacle at the same time given the position rightpos, midpos, and leftpos but i keep getting the spawn position to only rightpos and midpos. void Start () rightpos new Vector2(2f,6f) midpos new Vector2 (0f,6f) leftpos new Vector2 ( 2f, 6f) Update is called once per frame void Update () if (spawn activate true) number of spawn Random.Range (1, 2) spawn activate false if (number of spawn gt 0) spawnposition Random.Range (0, 2) if (spawnposition 0) Instantiate(obstacle,rightpos,Quaternion.identity) if(spawnposition 1) Instantiate(obstacle,midpos,Quaternion.identity) if(spawnposition 2) Instantiate(obstacle,leftpos,Quaternion.identity) number of spawn 1


Unity 5.3.5 Blurry UI text after switching canvasses until text is refreshed by turning visibility off on or changing resolution I have multiple scenes in my project where the canvas are switched between, each canvas having UI text included on it. The project was originally created in version 5.0 and I have just updated to version 5.3.5 and I am now encountering the following issue The canvas that is active when the scene first loads displays all UI text just fine, but as soon as I switch to another canvas with the exact same text on, the text on the new canvas is blurred. As soon as I turn the text object off on (via a button click) it appears to refresh it and it all displays fine again. It is also rectified by changing the display resolution in the editor play window. It appears as though unless it has a 'refresh' through clicking something else, or is on screen when the scene first loads, it appears blurry. The font is 'Open Sans Bold' and I am switching canvasses via a raycast script. I have read issues of text blurriness in 5.3, but most instances appear to be down to the size of the text being in odd numbers which mine isn't. Screenshots attached. The settings shown are the same for all canvasses and text. Any help would be appreciated. Thanks in advance


In Unity Move a GameObject at Animator State I want to move one of my GameObject to a different vector 3 position, when animator transit to a new state. How do I do it? Also there shouldn't be any delay.


Blurry text in Unity UI at default scale I'm working on a VR (GoogleVR Cardboard) game, and need to include UI elements within it. Ever since I first learned how to use Unity's UI elements, I've been limping around what seems to be a major problem at the default (1,1,1) scale, literally everything involving fonts that I add to a world space Canvas ends up looking like scaled, blurry bitmaps. I can kludge around the problem by manually changing the scale of everything UI related to (0.1, 0.1, 0.1) and multiplying the dimensions of everything by 10... but I can't believe this is how Unity's UI editing is intended to work by design. Somewhere along the line, I must have overlooked something major. The question is... what? Is there an option somewhere to either make Unity render fonts at a higher resolution, or to at least change the default scale for new items from (1,1,1) to (0.1, 0.1, 0.1) amp multiply all the default dimensions for new UI items by 10?


In Unity, how do get access to animation clips in selected model from EditorWindow? I need to add some animation events or copy them from other models. So I decided to make a EditorWindow. Unfortunately there's not much information about this, and I'm stuck in here. void OnGUI() GUILayout.Label("Source Object contains Animation Clips", EditorStyles.boldLabel) sourceObject (GameObject) EditorGUILayout.ObjectField(sourceObject, typeof(Object), false) if(GUILayout.Button("Copy")) if(sourceObject null) throw new System.NullReferenceException("Source Object is missing.") Do Copy here What I need to do is Extract all animation clips from the selected model(fbx) it's the source object Select "AnimationClip" to want to copy. Note that AnimationClip in here is not inside of model, it's seperated AnimationClip that duplicated from original model because basically animation clip from imported model is read only, so I have to duplicate to update it. How do I get animation clips from selected fbx model with ObjectField? Any advice will very appreciate it.


How to use Unity3D Social for OSX? I can't seem to find any documentation using the Social APIs with OSX. I can successfully use the iOS Social Libraries, but when I translate it over to OSX, it doesn't do anything. Also please refrain from suggesting Prime31, as I know that option exists, but the functionality for OSX leaderboards game center is natively built into Social API in Unity 4.1 yet there is no documentation to be found!? I want to know how to use Social.ReportScore, and the ShowLeaderboard UI Methods for OSX games. I would also like to know how to report achievement progress. I've tried using the EXACT methods from the Unity.Social Library that works for my other iOS iPhone iPad games. I've attempted the code in both C and UnityScript (JScript) to no avail. Please help.


Wrapping each script with classes causes errors The goal here is to change variables from another script. Thing is that they must be in classes, so for example I wrapped this code (which is from PadControl.js) pragma strict public var ball GameObject public var moveSpeed float 10 public var rotationSpeed float 10 function Update () var padMove float Input.GetAxis("Horizontal") var padRotate float Input.GetAxis("Vertical") this.transform.position.x padMove moveSpeed Time.deltaTime this.transform.rotation.y padRotate rotationSpeed Time.deltaTime function OnCollisionEnter(col Collision) if(col.gameObject.name "Ball") Debug.Log("SAY SOMETHING") like so pragma strict public class PadControl public var ball GameObject public var moveSpeed float 10 public var rotationSpeed float 10 function Update () var padMove float Input.GetAxis("Horizontal") var padRotate float Input.GetAxis("Vertical") this.transform.position.x padMove moveSpeed Time.deltaTime this.transform.rotation.y padRotate rotationSpeed Time.deltaTime function OnCollisionEnter(col Collision) if(col.gameObject.name "Ball") Debug.Log("SAY SOMETHING") As stated in this tutorial coming from Unity's website (https unity3d.com learn tutorials modules intermediate scripting statics) But when I do it, this is the error Assets PadControl.js(12,22) BCE0019 'transform' is not a member of 'PadControl'. Assets PadControl.js(13,22) BCE0019 'transform' is not a member of 'PadControl'. And I really don't know what's actually going on and what should I do. Any suggestions?


Can I add non trees to terrain.terrainData.treeInstances on Unity 3D? I need to create a brush in which there will be stones, poles, bushes and other elements of the environment. I bought a Prefab Brush. Whether it is possible to add the objects that I draw on the Prefab Brush scene to terrainData.treeInstances, as regular trees add? Is it possible to use a not prefab tree as an object for the TreeInstance class?


get access to Transform of a Clone in Unity In my game when you lose, A panel with a button on it appears and if you don't have enough coins, You may be directed to shop by hitting shop button. when buying is completed you can return to the scene from where you left it and resume the game. I'm using PlayerPrefs to save properties like slider.value my player position timescale etc, But I can't access to Transform of an Instantiated GameObject (Clone). it acts like obstacle and is Instantiated continuously. Here is my script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using CodeStage.AntiCheat.ObscuredTypes using CodeStage.AntiCheat.Detectors public class Spawner5 MonoBehaviour public float maxTime 1 public float Timer 0 public GameObject pipe public float height Use this for initialization void Start () pipe GameObject.FindGameObjectWithTag ( quot Gear quot ) Update is called once per frame void Update () if (Timer gt maxTime) GameObject newpipe Instantiate (pipe) newpipe.transform.position transform.position new Vector3(4, Random.Range ( height, height) ,0) Destroy (newpipe, 15) Timer 0 Timer Time.deltaTime


Glow effect shader for mesh generated at runtime I'm using the leap motion paint module and i would like the ribbons that are generated at runtime to have a glow effect, I tried editing the existing shader by adding a glow property but the colors did not change. I'm not experienced with shaders so any help would be much appreciated. EDIT I tried adding post processing effects for bloom amp glows, all the objects have a glow effect except the ones i'm generating at runtime.. Shader "LeapMotion TubeShader" Properties Color("Tint", Color) (1,1,1,1) Glossiness("Smoothness", Range(0,1)) 0.5 Metallic("Metallic", Range(0,1)) 0.0 Glow("Intensity", Range(0, 3)) 1 SubShader Tags "RenderType" "Opaque" "Glowable" "True" LOD 200 CGPROGRAM pragma surface surf Standard fullforwardshadows pragma target 3.0 struct Input float4 color COLOR half Glossiness half Metallic fixed4 Color half Glow void surf(Input IN, inout SurfaceOutputStandard o) o.Albedo ( Color Glow IN.color).rgb o.Metallic Metallic o.Smoothness Glossiness ENDCG FallBack "Diffuse"


Strange artifacts in Unity Lightmaps I experienced this weird lightmapping bug in my game that causes some models to have glowing artifacts on their surface. These artifacts "move" around, when I edit the UVs of the model in Blender, so I assume that it has something to do with them. I took a few screenshots to hopefully clarify the issue. Engine used Unity 2019.1.4f1 3D Software Blender 2.79b If you need any other screenshots or something, let me know. Thank you in advance! Lightmap Bug (lights off) Lightmap Bug (lights on) Models without Lightmaps baked Unity Lightmapper Settings Tree model in Blender with UVs Model Configuration in Hierarchy Model Asset Configuration


Flatten transform hierarchy at build time Nested hierarchies cause a performance overhead when they include moving objects. Every time a GameObject moves, altering its transform, we need to let every game system that might care about this know. Rendering, physics, and every parent and child of the GameObject needs to be informed of this movement in order to match. As the scope of a game increases, and the number of game objects skyrockets, just the overhead of sending out all these messages can become a performance problem. However, nested hierarchies are useful in organising a scene and keeping logical groups of gameobjects separate. What options exist to save performance whilst keeping the hierarchy? Is there any pre existing solution to flatten a hierarchy when building only?


How to handle back press in Unity? By back press on Android, I want to close all the open windows first then exit the game, I see everywhere it's suggested to check input key in Update void Update() if (Input.GetKey(KeyCode.Escape)) if (AreAllWindowsClosed()) Input.backButtonLeavesApp true But my issue with this is that it's calling the code in every frame and also may handle a single press multiple times! Isn't there a single BackPressed event in Unity for this simple task?


How can we view 3d objects from top down view in TD game I am making a tower defense game. I am working in x and y axis only. I have made a grid, snapped towers and made a pathfinding algo to run enemy. Initially I have worked with cubes and spheres in place of towers and enemies. Now I am going to place real towers (3D). Note that I haven't used z axis up till now. The user will analyze the game from top down view. I want the user to see towers placement with a little bit of 3d view but I have made my all code in 2d thing. Is there any solution to my problem that somewhat tower placement would view a 3D touch or you can say 2.5D ?? (like fieldrunners) or should I have to involve z axis and ignoring y axis ?


NavMeshAgent.CalculatePath produces a PathInvalid result Anyone know what can cause NavMeshAgent.CalculatePath to return false and give a path with PathInvalid status? I have two characters each character has a NavMeshAgent. Character x is a standard Humanoid, character Y is a vehicle with a custom agent type. Characters start out in scene A, which has two NavMeshes, one for each type, and both are able to navigate just fine. Characters get moved to DontDestroyOnLoad so that scene A can be unloaded and scene B can be loaded. Scene B has two NavMeshes, one for each type. Characters are placed on the ground, on a valid NavMesh location. NavMeshAgent is asked to path to another valid location on the NavMesh. Character Y (the weird one) paths just fine, but for character X, the call to CalculatePath fails and the NavMeshPath object's status is PathInvalid. I honestly have no idea what's going on here. If anything, I'd expect pathing to work for X and fail for Y, due to it being a nonstandard (and larger) agent. Not sure if the scene change is relevant or not including it just in case it is, and to show that the basic setup is working for 3 4 scenarios here. Anyone know how to go about debugging this?


Setting Camera's Viewing parameters manually I am working on Context aware camera in Unity. in this project i have to set parameters of the camera each frame manually depending on what camera sees on the screen. New View (v) direction is given and Up (u) and Right (r) vectors should be such that they minimize torsion with previous frame's u and r. I have deployed the following code to accomplish the given task Vector3 viewNew m Normal Vector3upNew Vector3.Cross(viewNew,m CameraPrevTransform.right).normalized Vector3 rightNew Vector3.Cross(viewNew, upNew).normalized ... transform.forward viewNew transform.up upNew transform.right rightNew The problem is it seems like Unity tries to automatically adjust parameters when one of the directions (up, forward, right ) are set. Is there a workaround ? is it possible to get more control of the camera?


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 can I edit multiple sprites in Sprite Editor at once? I have 100 sprites in one atlas. I want to edit some of them with same values. For example, I want to edit sprite's position no 1 30. Do I have to edit them one by one? Is there any function like Shift drag for selecting several sprites?


How can i put a skybox on a new layer with a new camera and then move the skybox? I want to create a moving start effect. For example the space station is moving around the star or moving to the star. But instead moving the space station i think it will be better to make effect of the skybox moving. I have in the Hierarchy a RigiBbodyFPSController and a child MainCamera. Now i added a new Camera to the Hierarchy. Now how do i make the rest ? Moving the new camera and the skybox to new layer and move the skybox ? Or it's more logic to say to move the new camera that the skybox is with in it in the new layer. Not sure if my idea is logic or if there are a better ways to do it. The general idea is to make movement effect like the space station is moving around the star or to the star. Star i mean the skybox. The skybox is on the right. I can't see the skybox in the scene view i see it only when running the game in the game view. This is a screenshot when the game is running then i can see the skybox in scene view and game view


Control Camera with gyroscope and place a gameobject always in front of it Actually I have came here after searching from past 5 6 hours. Actually I am making a small game in which I have a camera and a gameobject. The Game Object is place in the center of the scene at 0,0,0 . My scene doesn't include anything but a skybox. I wanted to move my camera with gyro input, I got that working. My problem is that I want my object which is at 0,0,0 is to face camera always. The camera is controlled by gyro so the object should always remain infront of the camera. I have taken a script from wiki.unity3d and it seems to be somewhat working. Actually I want an offset for the transform.lookAt or if it's not possible I'll require some solution for it. public class CameraFacing MonoBehaviour public Camera m Camera void Update() transform.LookAt((transform.position) m Camera.transform.rotation Vector3.forward, m Camera.transform.rotation Vector3.up) Actually I have tried 3rd person and FPS shooter camera and Camera Follow script as well besides knowing it doesn't fit my need. As In most cases we want the camera to follow object. But in this case my input is through gyro of mobile device and I want the center object to always remain in front of camera. Here is the code for gyroscope. I have made the object which I want to always stay infront of camera as suggested by comment but the camera rotate with gyro but not the object that is child of it, which is pretty strange. private float initialYAngle 0f private float appliedGyroYAngle 0f private float calibrationYAngle 0f void Start() Input.gyro.enabled true Application.targetFrameRate 60 initialYAngle transform.eulerAngles.y void Update() ApplyGyroRotation() ApplyCalibration() public void CalibrateYAngle() calibrationYAngle appliedGyroYAngle initialYAngle Offsets the y angle in case it wasn't 0 at edit time. void ApplyGyroRotation() transform.rotation Input.gyro.attitude transform.Rotate(0f, 0f, 180f, Space.Self) Swap "handedness" of quaternion from gyro. transform.Rotate(90f, 180f, 0f, Space.World) Rotate to make sense as a camera pointing out the back of your device. appliedGyroYAngle transform.eulerAngles.y Save the angle around y axis for use in calibration. void ApplyCalibration() transform.Rotate(0f, calibrationYAngle, 0f, Space.World) Rotates y angle back however much it deviated when calibrationYAngle was saved.


submeshes and dynamic batching doesnt work as expected I'm duplicating one object with submeshes frequently, and assigning a random material from five materials to each submesh. There is batching happening, but it's not quite as efficient as I would have expected (details here). Note objects are all less 900 vertices no light maps and ... All are dynamic batching ready So if dynamic batching works there must be only 5 draw calls right but there isn't there is really much more than 5


When and where and how to turn on back the Player first person when loading a scene on button click ? In the Build Settings I have two scenes at index 0 and index 1 Then in the Hierarchy I have the two scenes The active scene is the MainMenu In the StartGameButton I added to it a script component. In the script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class LoadSceneOnClick MonoBehaviour public void LoadByIndex(int sceneIndex) SceneManager.LoadScene(sceneIndex) And this is the StartGameButton Inspector I dragged the script on the OnClick I selected the function LoadSceneOnClick And set the index to 1 When the game start and I click on the button it stay on the Main Menu scene and not loading anything. The problem I guess is that I'm getting error in the game No cameras rendering The problem is that when I'm running the game and it start from the main menu scene in the space station scene I'm enable false the Player and the Player is a first person character with a camera You can see in the Inspector that the Player is unchecked the Player is not enabled. If I will enable the Player and even if the main menu scene is the active one it will show me the player and the player camera and not the main menu. So I had to turn off the Player. The question now is where by script do I enable back the Player when it's loading the scene ? Inside the LoadSceneOnClick script ?


Why my raycast sometimes not working? As you see in picture, i cast rays to (vector3.right direction) from center of boxCollider's bounds. It can detect the wall mostly, but sometimes it can't detect the wall and pass through it. the layer of wall is 'obstacle' and ray only detect that layerMask. why this happend? moveAmount.x input.x speed moveAmount.z input.z speed directionX Mathf.Sign(moveAmount.x) rayLength Mathf.Abs(moveAmount.x) .015f if (Physics.Raycast(rayOrigin, Vector3.right directionX, out raycastHit, rayLength, collisionMask)) Debug.Log("Hit")


With gravity enabled, how do you move a RigidBody forwards at a specific speed? I have a perfectly smooth cube on top of a perfectly smooth plane. I am applying a forward force of 1 unit per second, using rigidBody.AddForce(new Vector3(0, 0, 1), ForceMode.VelocityChange). I apply this force every FixedFrame(), taking into account Time.fixedDeltaTime, of course. When the "Use Gravity" checkbox on the RigidBody is not checked, the object behaves as expected after exactly 3 seconds, it has a speed of exactly 3 units per second. However, when I enable the "Use Gravity" checkbox, the object barely moves. Both the object and the surface are using Physic Materials with zero friction, and the moving object's RigidBody has zero drag and zero angular drag. Why does this happen? And more importantly, how would I apply a force to this object so that it moves forward at, say, exactly 3 units per second, with gravity enabled? Thank you.


Loading .PNG file and using it for UnityEngine.UI.Image Have an Unity UI Image. I want to load a .PNG file that is in my persistent data path and use it as the sprite source for the UI Image. Code byte bytes File.ReadAllBytes(Application.persistentDataPath " sprite.png") Texture2D texture new Texture2D(width, height) texture.filterMode FilterMode.Trilinear texture.LoadImage(bytes) Sprite sprite Sprite.Create(texture, new Rect(0,0,width, height), new Vector2(0.5f,0.0f), 1.0f) myObject.GetComponent lt UnityEngine.UI.Image gt ().sprite sprite This almost works. Only a portion of the image is displayed. The initial guess would be that I didn't load the image properly. However, if you use a SpriteRenderer instead of UnityEngine.UI.Image like myObject.GetComponent lt SpriteRenderer gt ().sprite sprite The image is displayed in full. So this seems to be a problem with UnityEngine.UI.Image specifically... ... However, if you drag an image from the editor into the Sprite Source property of UnityEngine.UI.Image, then such image is displayed in full then suggesting that there is something wrong with the way I load my image bytes. What should I do? Edit If you set the image type to Tiled, you can see that it tiles with the full image... So apparently the UI Image component DOES have all the image data but for some reason it won't render all of it.


Unity prefab object limitations TLDR What are limitations on how many objects a single prefab can handle safely? keeping in mind that I could potentially have almost a 100 of these I am busy creating a system to essentially load the game world in chunks as the player moves. This means that every single object in the world will be streamed into the game through script when needed(still designed in the editor, impossible otherwise) The problem I am having is with methods to store and load objects. I have looked at everything I could think of or get information on. After researching all the methods I found, I started thinking that prefabs is the best solution since it can live anywhere in the project(unlike streaming assets folder, which is also not recommended for many assets, let alone every single asset). Creating Game Objects at runtime is not as easy once GO's get complex with components and settings, also I assume the performance hit from creating GO's this way is worse than using an existing prefab. So my question is if prefabs can handle massive amounts of objects(lets say 1000) safely? testing this is hard because i would have a prefab(or a few) for each tile that gets loaded.


How to move rigidbodies Have i understood this correct If i want to use a rigidbody for physics then i should not move an object through its transform.position. I should never move it by riigidbody.velocity since i then affect the physics. So what is left is moving it using addForce. I guess its like mimicking how in the real world everything that moves has something that drives it.


Match 3 should pieces store their location in the matrix? I'm making a match 3 game. I have a TileManager script which stores all the tiles in a matrix, it's a singleton and it handles tile swapping and basicly everything regarding the management of tiles. I have a variable called selectedTile. I have a method called SwapSelected which swaps the currently selected tile with the one you just clicked on. As pieces don't know their location in the matrix I can only loop through the whole thing to find them but it feels extremly stupid I just feel like there's gotta be a better way. If pieces stored their location and I kept that updated all the time that'd feel stupid too. What could I do to make this method work nicer and more optimalized? Is there a way or there is no problem with how I do it? public void SwapSelected(Tile tileToSwap) Vector3 tempPos selectedTile.transform.position selectedTile.transform.position tileToSwap.transform.position tileToSwap.transform.position tempPos Vector2Int tileToSwapPosition new Vector2Int( 1, 1) Vector2Int selectedTilePosition new Vector2Int( 1, 1) OPTIMALIZE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for (int x 0 x lt tileMap.GetLength(0) x ) for (int y 0 y lt tileMap.GetLength(1) y ) if ( tileMap x, y tileToSwap) tileToSwapPosition new Vector2Int(x, y) if ( tileMap x, y selectedTile) selectedTilePosition new Vector2Int(x, y) tileMap selectedTilePosition.x, selectedTilePosition.y tileToSwap tileMap tileToSwapPosition.x, tileToSwapPosition.y selectedTile UpdateTileName(tileToSwap) UpdateTileName(selectedTile)


StateMachineBehaviour.OnStateExit is called before StateMachineBehaviour.OnStateEntered is called When I start my game I get null references in my OnStateExit of objects that are initialized in the OnStateEntered. After this it goes smooth, so it only occurs at startup before any conditions for statechanges are met. How come? My understanding is that OnStateExit is always preceded by OnStateEntered. My StateBehaviour public class DuckStateBehaviour BaseStateBehaviour override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) base.OnStateEnter(animator, stateInfo, layerIndex) mMovement.BeginDuck() public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) if (mMovement ! null) mMovement.EndDuck() base.OnStateExit(animator, stateInfo, layerIndex) public class BaseStateBehaviour StateMachineBehaviour protected Transform mTransform null protected Rigidbody2D mRigidBody null protected IMovement mMovement null public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) mTransform animator.gameObject.GetComponent lt Transform gt () mRigidBody animator.gameObject.GetComponent lt Rigidbody2D gt () mMovement animator.gameObject.GetComponent lt IMovement gt () Debug.Assert(mTransform ! null) Debug.Assert(mRigidBody ! null) Debug.Assert(mMovement ! null)


Reused Avatar moves mesh I have a humanoid avatar and it's animation controller. I also have two different human meshes, they're quite similar. When I use the generic avatar and it's controller in the animator the meshes shot out into the sky and perform their animation correctly. The animations run normal they just move in weird directions and don't stay in their original locations. How to fix it so the mesh doesn't move far away and retain original position?


How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d? I have two character in my game enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way void FixedUpdate() if (CanMove) transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) public void StartMove(bool canMove) CanMove canMove TargetPlayer GameObject.FindGameObjectWithTag(Tag).transform rigidbody2D.gravityScale 0 This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good looking? Edit I need to make good looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the current player position. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air(( Edit 2 I was thinking about destroying that object anyway, but to my mind this will not look good the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself.


fade transparence for object by shader graph? I'm trying to make a simple fade transparence for my object using shader graph. I got a result with dither but I don't like it. I want something smooth without dots. How to get it?


Does Unity store temporary autosaves for scripts? If not, how do I avoid data corruption My PC lost power in the midst of a save(twice in a row) and I've lost my scene setup as well as a script(its contents actually). I would like to know if there are any fail safes for saving files. If not, how would I prevent future data loss corruption.


unity animation won't play unless input key is held The code is simple. If the player presses the right arrow key, one animation clip plays. If the left arrow key, another clip plays, etc. However, the clip doesnt play fully unless the input key is held continuously. The second you release it, the second the clip stops playing. I think it's something to do with update() and the input not being remembered over next frame. The code is simple using UnityEngine using System.Collections public class animatorcontroller Logic MonoBehaviour Animator anim enum MovementState Idle 0, run 1, walk 2, MovementState currentMovementState void Start () anim gameObject.GetComponent lt Animator gt () void Update () if(Input.GetButton("right")) currentMovementState MovementState.run else if(Input.GetButton("left")) currentMovementState MovementState.walk else currentMovementState MovementState.Idle set movement state to idle anim.SetInteger("MovementState", (int)currentMovementState)


Is white the best base color to start with when planning to shade sprites within Unity? I'm looking into prototyping a game in Unity which will consist of solid square sprites tiles. I figure I can represent different types of objects with different colors for each of the tiles in the game. I figure that I can import a single square sprite and shade it appropriately in Unity as opposed to imported squares of many different colors. My experience with adjusting the hue and saturation within Photoshop shows that white is not an easy color to change as things that are white often stay white. My testing in Unity shows that I can change the "color" of a sprite to anything other than white and the sprite is seemingly shaded appropriately, despite what I would have thought given my Photoshop experience. Since white objects do seem to take on the appropriate color shading when changed within Unity my gut tells me that this is the best base color to begin with, meaning that I can import a single white square sprite and simply adjust the color to represent different objects and object states. Is a white sprite actually the best color sprite to begin with and why does something like this work in Unity as opposed to adjusting the hue and saturation within Photoshop?


Networking and physics Context I have been implementing my own networking for a third person multiplayer game, but controls and physics will be ala old school FPSs. I'm using Unity's transport layer, which allows me to send and recieve raw data between server and client. I used this model as reference, in order to implement better client response http www.gabrielgambetta.com client server game architecture.html Implementing prediction, and interpolation was no problem, but I'm having a problem implementing reconciliation, even though I successfully implemented for normal ground movement. I do the following each tick Client The client sends the server the delta updates on the player position, and the server validates this movement and updates the player accordingly on the server. Server I send a snapshot to all clients with all players' positions. Each client interpolates the rest of the players, and reconciliates it's own position. Reconciliation Ground movement seems easy, because each frame the player input determines how the player moves Each FixedUpdate, the player moves a certain distance. This makes reconciliation really easy, since knowing which was the last input the server has received, your client just needs to consider the rest of the inputs yet to be processed. Reconciliating jumping But I don't know how to deal with jumping. Jumping is an input that has an impact on the player's position over several frames while it's airborne (and for a few frames, as the placer decelerates in case his air speed was high). This means I can't just rely on the input "jump" to recalculate my client's position, since depending on the moment I'm present, I could be ascending, or descending. Even more, if I jump and collide with the roof, killing all my vertical speed, the movement would be completelly different. This lead me to think I should be sending to the server each update on the player's position Instead of sending "hey, im jumping here", I could send "I'm moving up 1 unit"..."I'm moving up 0.9 units".... describing the players parabole. But I feel this method is not enterily secure, since the client could be sending "I'm moving up 1" ever single time, allowing the player to just fly away. So the server has to be the one handling the physics on the jump. Other scenerios This problem is also present in anything physics related When the player is pushed away by an external force set up by the server or the client itself. If the client recieves a message saying has been affected by an explosion, I could set the client's speed accordingly, but If I have any kind of air control (which I want to have), I need to tell the server the change on air speed If the server makes a correction on the physics made, I need to be able to predict and reconciliate the position AND speed. For example If I collide against a wall in the server, which for some reason, is not present in the client, I also need to kill the player speed or it will keep slamming into an invisible wall. Posible solutions There are several solutions I was thinking about, but I'm not really satisfied with any of them As said earlier, I could could let the client handle the air movement by sending the position update back to the server, but this feels insecure since th client could technically make himself fly around, and make himself immune to being pushed away. Besides sending the player positions, I could also send the players' speed, storing this information could make reconciliation easier and more reliable, but it will also increase the size of snapshots and network usage. Maybe I'm missing a clever alternative, but I don't really see any other option. Any ideas?


Vector3 Array serialization ReorderableList I've been working on a ReorderableList, but it's given me quite the headache. I've come to the point where I want to define a "drawElementCallback" callback, which looks like this list.drawElementCallback (rect, index, active, focused) gt EditorGUI.PropertyField(rect, list.serializedProperty.GetArrayElementAtIndex(index), GUIContent.none) What it's supposed to draw is one Vector3 object from an array of Vector3 objects. I get this property like this ("property" is a SerializedProperty that contains the property that I need) SerializedProperty locationsProperty property.FindPropertyRelative("locations") The array is declared as follows public Vector3 locations Inside a container class that is marked as "Serializable". The problem I kept getting with different code is that the ReorderableList shows all the Vectors correctly but it doesn't allow me to reorder any of the items, nor delete them (I can add new Vector3 objects and change them as expected). With this code, I wanted to fix that issue. However, now I keep getting the following error "InvalidOperationException The operation is not possible when moved past all properties (Next returned false)" I wanted to make a reorderable list because it seemed easy, but I can't figure out the problem and I honestly wish I hadn't started working on it. It's taken up most of the past 3 days. If anyone knows how to fix this, I would be very grateful. To clarify, this code shows the array properly list.drawElementCallback (rect, index, active, focused) gt SerializedProperty item locationsProperty.GetArrayElementAtIndex(index) EditorGUI.BeginChangeCheck() item.vector3Value EditorGUI.Vector3Field(rect, string.Empty, item.vector3Value) But doesn't allow me to remove or reorder items. I thought I should show the code to demonstrate that there are indeed array items.


2D Unity How to make a enemy jump from a navmesh platform to another? I'm currently working on a 2d platformer, however I came across an issue where the enemy moves within a certain range of the platform. In this case I use a navmesh to limit the enemy's movement however I want the enemies to be able to jump within platforms. I'm not sure how to achieve this effect, where the enemy moves in the platform a couple of times and the jumps into the next one until the player gets in range for it to attack the player. How can I acheive this effect? Should i keep on using navmeshes or try another way around?


How do you support different VR platforms? I created an Android app for Gear VR in Java (using the GearVR framework) that I now want to port to Unity, so it can also be used for Microsoft's semi new Mixed Reality headsets (for Windows not HoloLens, though). I've never worked with Unity (or C ) before, that's why I have a question How would you set up something like that? Can you simply create a single project and then put it on your (Android) phone compile it on your PC depending on where you want to test it, or do you need separate projects for different platforms?


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


How to use 3 cameras simultaneously in Unity I'm working on a project that requires 3 panels, each rendering a game object. There will be a search box and when the player enters a string, that key word will zoom to the tagged location on the each object in the 3 panels. How can I go about accomplishing this?


Do I need a server to connect two players in a mobile game? I would like to make a 2 players app game, where 2 players can compete with each other in real time. If I want the player to be able to compete with the public (anyone who registered with my game able to compete with one another), do I need a server? If I want the player to be only able to compete with his facebook friends, do I need a server? Do I need a server at all in the first place, for 2 players game?


How do I import multiple animations into the same file in Unity? I have hit a major stump in my development applying transitioning animations to the same model. I have learned how to do a single animation with keyframes, but have no clue on what to do with more than one. I tried importing different animations seperately and applying them to the same model, but it didn't work. How can I get past this stumbling block?


2d ParticleSystem batching problem I have multiple ParticleSystems with TextureSheetAnimation pointing to the same texture, using different offsets rows to choose different textures. They seem to batch with each other, but they're also being split by Unity into multiple batches in a strange manner. Here's a Frame Debugger view These 4 Draw Dynamic are on the same atlas, using Mobile ParticlesAdditive shader. The reason of breaking batching is Objects have different batching keys. This is usually caused by using different vertex streams on ParticleSystems or by mixing Lines and Trails, or by mixing lit and unlit geometry. All of the ParticleSystems have a simple setup, some Color Over Lifetime, some Velocity Over Lifetime etc. The strange thing is that Unity breaks batching like it makes one batch, puts half of the stars and half of the smokes into that, and then, makes another batch from these two. So they do batch, and the don't o.O I couldn't find and help on the web about this issue. I'd be glad for help.


How to improve textmesh quality? In my game I using textmesh, but textmesh has a pixel problem even adjusting scale, character size and font size. How to solve it?


Critical input from server arrives late... it must not! To preface, my understanding of networking is mostly from Source Multiplayer Networking and 1000 Archers on a 28.8. For various reasons I have decided to go with a client server model instead of peer to peer. My C Unity multiplayer game is ruled by an authoritarian server, which uses UDP. Each network instruction has a time index, and is inserted into PlayoutBuffer's data collection. The buffer executes stored commands at the correct local time index, based on a fixed update loop. The server is slightly ahead of time, and clients will pause if they have not received any regular update from the server, allowing them to catch up. Each client will simulate object movement and this movement is corrected by the server (ten times a second). I've got the basic system working, but when I'm testing it in two windows on the same machine sometimes input arrives late, and is dropped. Usually the late message is 1 time index too late. The fixed loop is 50 ticks per second. The server is 5 ahead of time, and commands are scheduled 5 ahead of time (assuming negligible lag, since ping hasn't been implemented yet and is on the same machine). This is a problem. Inputs from server are grouped into a few specific channels Ping, Serialise, Inputs, Criticals, Corrections. Ping has yet to be implemented. Serialise packs and unpacks mostly pregame multiplayer lobby stuff. Inputs are player commands select unit, issue move order, etc. Criticals are essential updates create unit, shoot unit's weapon, damage unit, etc. Corrections are mostly movement updates. All channels are unordered and with the exception of Corrections all channels are "Reliable" in Unity terms (see Unity documentation). Given that movement updates happen regularly, if a few are dropped or arrive late this is not a critical system failure. But if a critical is lost, this would effectively result in a desync. How can I prevent and handle critical data arriving late from the server? My first thought is to implement a custom ping. This is used to set the time index for the data relative to the time the last ping took to get back from the client, plus server time index. But I doubt that would be enough... and if it fails? Should the client pause or catch up based on the difference between local time index and the time index in the late critical? Does the PlayoutBuffer need to become an AdaptivePlayoutBuffer to resolve these issues to handle CPU and network lag? If so, how so? Any other ideas welcome! EDIT The reason inputs were arriving one time index too late sometimes was because the buffer's for loop which read inputs counted from 0 to list.count, and removed items as it iterated... when I changed it to reading from list.count to 0, it fixed the issue and no inputs arrived late. Whoops.


Why is my character jumping at different heights randomly? I have a character controller on my character's gameobject and I'm trying to make the character jump. This is working but sometimes he jumps way higher than other times. Does anyone know why this is happening? Here's the code using System.Collections using System.Collections.Generic using UnityEngine public class Movement MonoBehaviour CharacterController cc public float Speed float Forward float Sideways float vertical public float gravity public float Jump Start is called before the first frame update void Start() cc GetComponent lt CharacterController gt () Update is called once per frame void Update() Forward Input.GetAxis("Vertical") Speed Sideways Input.GetAxis("Horizontal") Speed if (!cc.isGrounded) vertical gravity Time.deltaTime else if (Input.GetKeyDown(KeyCode.Space)) vertical Jump Time.deltaTime vertical 8 Time.deltaTime Vector3 Delta transform.TransformDirection(Sideways, vertical, Forward) cc.Move(Delta Time.deltaTime)


How to fix lag in 64 bit Android devices My game's FPS drops to 30 8 FPS on any 64 bit Android device but is at 59 60 FPS on an even lesser 32 bit Android device. I've tried unchecking Development Build on Build settings and I've tried disabling debug calls on my game by using void Update () if UNITY EDITOR if(!Debug.unityLogger.logEnabled) Debug.unityLogger.logEnabled true else if(Debug.unityLogger.logEnabled) Debug.unityLogger.logEnabled false endif But there wasn't any change. And I tried setting all Stack Trace Log type to None(Edit gt Project Settings gt Player). Also no change. PS I used that update call because there are other imported assets that call the Debug class and I wouldn't want to mess around with their classes. EDIT As you can see in the screenshots below, the device that runs the game at less than 30 FPS(every 64 bit device) has Gfx.WaitForPresentOnGfxThread take 71.6 of the frames and RenderPipelineManager.DoRenderLoop Internal() takes up 51.1 . While the device that ran the game at 60FPS(every 32 bit device) has RenderPipelineManager.DoRenderLoop Internal() take up the most frames with 35.7 of the frame. How should I fix the frame rate drop on the 64 bit device? EDIT The 32 bit Android device is an Infinix Hot 4, 2GB RAM, 1.3GHz quad core MediaTek MT6580 CPU, OpenGLES2, Android 7.0, 1280x720. This reaches a maximum of 62FPS(Average 59FPS). The 64 bit Android devices are Cubot X19 4GB RAM, 8 core CPU 4x 2.3 GHz ARM Cortex A53, 4x 1.65 GHz ARM Cortex A53 , OpenGLES3, Vulkan supported, Android 9.0, 2160x1080. This reaches a maximum of 30 FPS(Average 25FPS). Qubo P19 3GB RAM, 1.5GHz Quad Core MT6739WA CPU, OpenGLES2, OpenGLES3 supported, Android 9.0, 1280x640. This reaches a maximum of 25FPS(Average 19FPS). I'm using Unity 2019.3.1f for my project.


Game objects all blue underneath I have an empty scene with a single object in it, a cube. The cube renders initially as pink, when it has no material attached. When I attach a material though. Any material. Odd things happen. I have created some extremely basic materials, which are just colours. Some metallic, some not. If I apply when of these the cube does not go the colour expected. The exception of this is the Green and Blue materials, although I suspect they're the wrong shade. Please see below Why could this be happening? My settings look pretty standard on the cube... If I create a brand new cube and set the materials up the exact same thing happens. I have downloaded some sample materials from the asset store, and they behave strangely too. A brown wood bark texture does the following And here is that texture, definitely no sign of blue. There are no lights set up, and the cube is the only item live on the scene, everything else is switched off. I have also added a camera and rendered the scene. Same thing. Is there some sort of ambient light setting or something I am missing quite obvious? Really not sure what to do here.


Animation is not starting even though collider is triggered? progress is steady but it is a bumpy road. I have removed the animation script from my character and reworked it into the controller script. I have also added new animations. Doing this required replacing the character FBX I was using earlier. Doing this has caused an unexpected problem Remember that super cool item box that I made, that the character can trigger when he jumps under it, causing it to play an animation where the lid pops off? Well, that's broken now. The box's idle animation still plays, but the GetItem animation does not. Before importing the new character, his animations and the box's animations were in the same animation controller. I separated them into their own controllers, and applied them each where they belong. I did not make any more changes ( you can see all its properties in the demos below). There are still no transitions or parameters for the ItemBox. Funny enough, I tested it and the ItemBox's trigger is being activated. What could be wrong? Video links (SHORT) Link to video of new character demo Link to Animators Panels Video How can I get the GetItem animation to play for my itemBox again? whoops, here is the relevant script ItemBox.cs using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour Start is called before the first frame update bool disabled false Animator anim void Start() anim GetComponentInChildren lt Animator gt () if (!disabled) anim.Play("ItemBox Idle") Update is called once per frame void Update() void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") print("itembox triggered") anim.Play("ItemBox GetItem") disabled true This is the heirarchy for the ItemBox prefab. Notice that animation frames can only be seen from first child ("Parent") of that prefab, downward UPDATE! GetItem animation is playing in the animation graph while I play the game, hitting the box from below, but the animation doesn't play in the game! The plot thickens! See (shorter) video shorter video


Use Unity Handles for interaction in the scene view I want to give an object with a specific script arrows to do special functions in the scene view. I have gotten Unity to render the arrows but I have no idea how to actually handle mouse events. The docs appear to say that I should be able to identify what receives a mouse down event by calling HandleUtility.nearestControl however when clicking on different arrows in the scene view I get the same ControlId (which i'm guessing is the gameobject itself). How are you supposed to know deal with mouse events properly? Code CustomEditor(typeof(Script)) class SceneGui UnityEditor.Editor void OnSceneGUI() if (Event.current.type EventType.Repaint) Transform transform ((Script)target).transform Vector3 pos transform.position Vector3.left 2 Handles.color Color.yellow Handles.ArrowHandleCap(3000, pos, Quaternion.LookRotation(Vector3.left), 2, EventType.Repaint) Vector3 pos transform.position Vector3.right 2 Handles.color Color.red Handles.ArrowHandleCap(3001, pos, Quaternion.LookRotation(Vector3.right), 2, EventType.Repaint) Vector3 pos transform.position Vector3.forward 2 Handles.color Color.blue Handles.ArrowHandleCap(3002, pos, Quaternion.LookRotation(Vector3.forward), 2, EventType.Repaint) Vector3 pos transform.position Vector3.back 2 Handles.color Color.cyan Handles.ArrowHandleCap(3003, pos, Quaternion.LookRotation(Vector3.back), 2, EventType.Repaint) else if (Event.current.type EventType.mouseDown) Debug.Log(HandleUtility.nearestControl)


A.I. dependencies based on components I'm working on a turn based game in Unity. I need to perform field grid analysis(2D grid) when i'm iterating trough each unit "entity". The A.I. should be able to plan ahead and therefor needs to consider the components each unit have. Not every unit will have the same ability. These abilities are defined as components. I want to make it flexible in the sense that I can plug in new abilities and my A.I. will take it into consideration. While user control is somewhat implemented, A.I. hasn't even been written. So I'm open to any suggestion. Q What is a way for the A.I. system to collect all abilities of one unit and make decisions depending on each component? edit I know there is the "null" checking method to see if the gameobject contains a component. But this is highly inflexible because you are hard coding a stack of if else. Something I want to prevent.


Unity 2D ROPE connected to moving platform Hey guys I have realy big problem with my rope. I use a hinge joints 2D to create my rope and distance joint to connect it with moving platform. On moving platform I have a distance joint that show on a first chain joint, so that allows move platform and rope should fallow that platform. Problem is that, when I will move platform then joints connection will brake and joints goes crazy. Is there any solutions for that ?? When I will move than green circle which is on image 3 then all joints go crazy


How do I stop clicks on a button from also triggering my gameplay scripts? My character jumps when I press the right side of screen. The pause button is alsp in the top right corner. So when I press that button, the right side script always triggers and I don't want that to happen. Here the script if (Input.GetMouseButtonDown(0)) float xPosition Input.mousePosition.x if (xPosition gt Screen.width 2 amp amp isGrounded amp amp !isJump) mouse is on the right part of the screen, shoot right rb2d.velocity new Vector3(0, jumpForce, 0) isJump true JumpSoundSfx() if (Input.GetMouseButton(0)) float xPosition Input.mousePosition.x if (xPosition lt Screen.width 2 amp amp !isJump) mouse is on the left part of the screen, so shoot to the left crouch.SetActive(true) stand.SetActive(false)


Set sprite for UI2DSprite from NGUI at runtime How can I set sprite for UI2DSprite from NGUI at runtime? This is what I tried gameObject.GetComponent lt UI2DSprite gt ().sprite2D Resources.Load lt Sprite gt ("Assets Content UI level notLife.png") I tried not to write .png in the end but it did not help as well. Here is my Project view so that to prove you that I am using the right path And the problem here is that instead of showing me the newly placed sprite my old one disappears and nothing else happens. So, how can I change sprite in UI2DSprite in NGUI from script?


maya root motion animation jumps back and forth in Unity I have a custom made model from Maya that is supposed to have root motion. But when I put the animation into the animator in Unity it keeps jumping back. I have configured the model in Unity as Root motion. So now I don't know whether it's a problem with the model in Maya or the setup in Unity. I have compared my Unity setup to a Jose Diaz Toon Dinosaur setup which seems to be the same so I am suspecting that there is a problem with the model export from Maya.


Prevent counterclockwise rotation So I have an object that has a handle attached to it, the player is supposed to rotate this handle. For that, I'm taking in the horizontal and vertical axis of a controllers analogue stick and transform these values into degrees, which I then use to rotate the object. The problem is that I can't seem to completely block out the possibility of rotating the handle counterclockwise, as the player is only supposed to rotate it clockwise. What happens is that every couple of frames while I try rotating counterclockwise it detects a clockwise rotation, executing my according code, even though I was rotating counterclockwise consistently. The principles I use to determine which direction the rotation is going is done by comparing the input angle of the last frame to the current input angle, like Variant 1 var inputAngle Mathf.Atan2(x, y) Mathf.Rad2Deg float angleDifference inputAngle previousAngle if (angleDifference gt 180f) angleDifference 360f if (angleDifference lt 180f) angleDifference 360f if (Mathf.Sign(angleDifference).Equals( 1)) Counterclockwise rotation else Clockwise rotation ... previousAngle inputAngle In another attempt, I tried to do this comparison by simply checking if my current angle is larger than my previous one while having the input transformed in a 0 to 360 range and also handling the overflow from going back to 0 from 360 , which did not work consistently either. So I tried to see what the values are giving in this faulty case, but what this told me was simply that the values are not as I expected them to be, as the current angle should be smaller than the previous one while rotating counterclockwise, in those cases and I can't figure out why or how to prevent it? So I guess in the end my question would be how can I consistently prevent a player from rotating counterclockwise by reading a controller's analogue stick input.


How to have 3d multiple planet gravity in unity c ? Im using unity and I want to make a game where you can walk around small planets and the further away you get, the weaker the gravity, so you can go to other planets. All the tutorials so far only work with one planet, how do I code this? Is there anything I can download that does it for me?


It lags when it collides. Help? ( I am trying (and believing) to make a game of pong. I have got a slightly decent working game. I haven't implemented the scoreboard or AI yet because I want the physics to work first. I am trying to reverse the direction of the ball when it hits either paddle just to make it work cleanly and am having the issue where it changes direction twice, it bounces off the paddle as expected and then goes in the opposite direction to when it hit the paddle . If anyone could help me, it would be much appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class BallController MonoBehaviour private float randomNumber private float range private float pointOfContact private float paddleTop private float paddleBottom private float limits private int speed private int caseNumber private Vector2 direction private Rigidbody2D ballRigidbody void Start () Getcomponent finds the rigidbody of the attached object. ballRigidbody GetComponent lt Rigidbody2D gt () speed 5 caseNumber Random.Range (0, 2) range PickARange (caseNumber) ballDirection (speed, range) void FixedUpdate() void OnCollisionEnter2D (Collision2D coll) if (coll.gameObject.tag "Player" coll.gameObject.tag "Computer") pointOfContact ballRigidbody.position.y print (pointOfContact) ballRigidbody.velocity new Vector2 (ballRigidbody.velocity.x, ballRigidbody.velocity.y 1) void ballDirection (int ballSpeed, float yDirection) randomNumber (Random.Range (0, 100)) if (randomNumber lt 49) direction new Vector2(Random.Range ( 1.0f, 0.5f), yDirection) ballRigidbody.velocity (direction ballSpeed) else direction new Vector2(Random.Range (0.5f, 1.0f), yDirection) ballRigidbody.velocity (direction ballSpeed) float PickARange (int number) switch (number) case(0) range Random.Range (0.5f, 1.0f) return range case(1) range Random.Range ( 1.0f, 0.5f) return range default range 1.0f return range I thought to multiply the whole velocity by 1 but that just caused a loop because of the lag. Even though that's the right way to reverse the direction. I think. Thanks Peeps!


Correcting imported animation to avoid hand going through the face of character I've imported an animation from Mixamo called standing draw bow. When I use it with my character in Unity the hand goes through the face of my character. Is there a way to move hand a little outside the face of the character using Blender or Unity? Or am I required to make up the animation myself? I tried modifying parameters Mixamo offers but doesn't resolve the problem. I actually tryed to solve the problem with IK by adding a Multi Parent constraint ( cause i didn't manage to have multi postion constraint to work ) and tried to move lowerarm r Bone a little bit off the face of the character but it only did force the bow to stay in the position and rotation of the quot Target quot while being buggy in certain keyframes. my aim is to force that bone to not rotate more than certain degree to not go through the face while executing the animation. I believe the problem is coming from the fact that animation is made for normal head character not big head ones.


Can Java be used for developing games for Android in Unity3D I only know Java Programming Language and no other. Can I develop games for Android in Unity3D using Java?


Why my stencil mask doesn't work? I've a very sipmle Unity scene. It has two objects in it, which is Sprites, and they both use sipmle black boxes as a textures. Here's two shaders, one should act as a mask, and second as a object, that should be rendered only in pixels, specified by that mask. Mask shader Shader "Unlit StencilUnlitShader" Properties MainTex ("Texture", 2D) "white" SubShader Tags "RenderType" "Opaque" "Queue" "Geometry" Pass AlphaTest Greater 0.5 Only render pixels whose alpha is greater than AlphaValue. Stencil Ref 2 Comp Never Never never pass the stencil test, Always always pass the stencil test Pass Replace write Ref value into the stencil buufer CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag (v2f i) SV Target sample the texture fixed4 col tex2D( MainTex, i.uv) if (col.a lt 0.9) discard discard a pixel if it's transparent and don't draw it into a buffer return col ENDCG Object shader Shader "Unlit GreenUnlitShader" Properties MainTex("Texture", 2D) "white" SubShader Tags "RenderType" "Opaque" "Queue" "Geometry 5" to draw after stencil object Pass AlphaTest Less 0.5 Stencil Ref 1 Comp Less Always, Less if ref value is greater then current value in the stencil buffer Pass Keep CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert(appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag(v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) fixed4(0,1,0.5,0.6) if (col.a lt 0.9) discard return col ENDCG The problem is, this doesn't seem to work, and object doesn't seems to be rendered at all (why it should in the places where mask have it's pixels)


How do I reference one game object in a script attached to another? This is all in Unity, with C . I have attached a script to my player that should destroy a TreeGroup (as in a forest) whenever I press 'Q' and instantiate one when I press 'E'. Here is the code using UnityEngine using System.Collections public class DisableTrees MonoBehaviour Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetKeyDown (KeyCode.A)) Disable Trees on A Keypress Debug.Log("Trees Disabled!") if (Input.GetKeyDown (KeyCode.E)) Enable Trees on E Keypress Debug.Log("Trees Enabled!") How do I access and find my 'TreeGroup' object group while script not being attached to 'TreeGroup' but my character instead and then Destroy on Q Keypress? And how do I Instantiate it?


How to join two cubes? If I want to make a character (in Blender) made of cubes, to export it to unity later, should I leave these cubes and all the other body parts as separate objects, or join them all into one mesh? And, If I should join them is it a good idea to leave the cubes elements inside of each other? Or I should remove them, add some loops and connect the vertexes? In the last case it will be difficult to keep the cubes surfaces flat, because of the vertex shifting during joining.


Making an 'anim in circular motion' get attracted by gravity of the center I am working on a project, where the main player anim is in circular motion with respect to a center point. This video shows what I have done to the anim till now. In that video, there are multiple apples are in circular motion. However, in my case, there is only one anim which is in circular motion. I have tried the following code for the circular motion. public Transform center public float degreesPerSecond 65.0f private Vector3 v void Start() v transform.position center.position void Update () v Quaternion.AngleAxis (degreesPerSecond Time.deltaTime, Vector3.forward) v transform.position center.position v The above code works perfect for the circular motion. At the center (0, 0), I placed a circle sprite with 'point effector 2d' component. (see below image). The reason why I 'added point effector 2d ' is to apply gravity effect to the player. But that didn't work. The player anim which is in circular motion around the circle sprite should get affected by gravity of that circle sprite and it should be pulled towards the center. Changing the 'Point effector 2d' parameters is good enough to create gravity? or do I require any change in code?


How would I access my list from Update function? The DFT function below works fine but I want to use the list, generated from that function, in the Update function. using System.Collections using System.Collections.Generic using UnityEngine public class FFT MonoBehaviour public ArrayList amp new ArrayList() public ArrayList freq new ArrayList() void DFT() float X 1, 2, 3 float Y 2, 3, 5 float N X.Length for(int k 0 k lt N k ) float re 0 float im 0 for(int n 0 n lt N n ) float phi (2 Mathf.PI k n) N re X n Mathf.Cos(phi) Y n Mathf.Sin(phi) im Y n Mathf.Cos(phi) X n Mathf.Sin(phi) var freqq k var ampp Mathf.Sqrt(re re im im) var phasse Mathf.Atan2(re, im) phase.Add(phasse) amp.Add(ampp) freq.Add(freqq) I want to use the lists elements in another function (for example in Update) void Update() for(var i 0 i lt 2 i) var x amp i Mathf.Cos(freq i ) var y amp i Mathf.Sin(freq i ) var pos new Vector3(x, y, 0) Debug.Log(pos) The problem is that amp i and freq i doesn't work in another function.


Unity How to create C classes with different properties like Objects in javascript and put them in an array? I just started my gamedev journey on unity this week and while I have a background with coding, I'm still somewhat of a beginner. Last year I made a text UI based game on the web browser with javascript and have been trying to make the same game on Unity. One of the main features of my game is that you press a button to "go hunting" and I had an array filled with enemies that were objects with different properties such as health, mana, attack, etc... Then I'd randomly pick one of those objects from the array to be chosen as my enemy that I'd fight. I've been trying to figure out the best way to do this with C and I might just be overthinking this. As a bonus, I'd also like to be able to see the individual enemy objects in the array in my inspector if possible so I could tweak the stats within unity. I've looked at scriptableObjects and different things but I am having a hard time putting it all together in an array from within unity. System.Serializable public class playerClass public string playerName public int lvl public int maxHealth public int health public int maxEnergy public int energy public int exp public class playerScript MonoBehaviour public playerClass player This is how I created an object for the player, I want to do something similar for the enemies but put them in an array so I could randomly pick from them. If there is a better way to do this I'd also welcome some advice ) thank you


Advice regarding Unity hosted content I'm currently trying to build a mobile application that, for the purposes of trying to keep small in size, I would like to have store much of its content Online and be downloaded to the users mobile when the application requires it. Ideally I'd like to do so not just as a means to reduce the applications original size, but also to allow new assets to be introduced over time (such as new objects and textures) without the user having to reinstall the application or download a new update. I am at the moment researching into the use of Unitys Addressible Assets for these purposes, and am currently trying to test and implement this idea on a small scale using assets stored using Google Cloud storage. If possible however I would like to to ask whether anyone here has any experience with storing and accessing assets on an external server, and if so, might they have any advice as to whether or not this could be a feasible solution for these purposes? Any help would be really appreciated, as this is an area that is completely new to me. Thanks in advance.


How can I create an "afterimage" effect like this one? How can I make an effect like this? With a particle system?


Does PBR mean only one, right technique to view 3D scenes? For example if I call Unity 5's render pipeline "PBR" (Physically Based Rendering) and also call Unreal Engine 4's render pipeline "PBR," does it mean that the same model with the same PB textures will be viewed identically in very similar or equal scene setups on both engines? I just wondering if someone says "PBR," does it mean only one, single, right way to do "PBR," or do implementations vary from one to the other?


Moving character controller on twisted track I am trying to move a ball using Unity's character controller component. I want to move the ball along the twisted track so that it can go upside down. Below is the video of the problem when moving using Unity's Character Controller https gfycat.com dismalaridjoey I want the ball to move upside down along the twisted track. I have the following questions What kind of modifications are required to achieve this using a character controller? Which other methods (physics or splines) can be used to implement such ball movement? I am flexible to switch the appraoch. I would appreciate any suggestions and thoughts on this topic. Thank you.


pause Menu only working in one scene and not in others Hi I'm working on a game for a school project but I'm still pretty new at game dev, I decided to add a pause menu to my game but for some reason, it only works in one of the scenes in unity, and I can't tell why it won't work on any of the other ones Here is a video showing the problem https youtu.be 28fD9UEtfpg and here is my script just in case using System.Collections using System.Collections.Generic using UnityEngine public class PauseMenu MonoBehaviour public static bool GameIsPaused false public GameObject PauseMenuUI Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (GameIsPaused) Resume() else Pause() public void Resume() PauseMenuUI.SetActive(false) Time.timeScale 1f GameIsPaused false Cursor.lockState CursorLockMode.Locked Cursor.visible false void Pause() PauseMenuUI.SetActive(true) Time.timeScale 0f GameIsPaused true Cursor.lockState CursorLockMode.None Cursor.visible true


Better way of handling the relation between Bullet and Enemy I was wondering how should I design this relation in terms of "better OOP"? Should I have a Singleton EnemyManager which contains a list of enemies (EnemyList) then Bullets can access the EnemyList to check for collision? Or should I just pass EnemyManager as a reference to each Bullet so Bullets can still access the EnemyList but not in a Singleton way? Or is there any other better ways of doing? Please advise.


Alternative solutions to applying an overly large and detailed texture to a mesh I have a very large spherical mesh in my Unity scene (the earth), to which one very large texture is applied (a map of the earth). Now it just so happens that Unity's max texture size (8192 pixels I believe) is not enough to capture the details I need on this huge mesh. What's the proper way to deal with this situation in Unity? That is, not only overriding the 8192 pixels limitations (although that would be nice as a temporary solution), but also making sure the overhead won't become unbearable... Is there a way to dynamically stream higher quality sections of textures as the camera gets closer to that specific part of the mesh? Additionally, I see the Granite add on (http graphinesoftware.com products granite for unity) seems to do just this (if I understood it well), but it's only for Windows, and I'm developing on a Mac. Is there any other adding out there?


Data structure for objects in a galaxy of star systems I'm having some difficulty coming up with the appropriate data structure to use for a game. I'm aiming for a galaxy view with tens of thousands of visitable star systems. Structure Hierarchically, each star system can contain one or more of the following Planets and their moons Asteroid Belts Megastructures and their moons sub structures All of the above can have quot points of interest quot POI eg a station in low orbit, a surface resource node, a docking bay. Usage I don't particularly care about physical location within a system beyond knowing its order in the hierarchy (I'll be showing a list of locations, rather than trying to render them in 3D space). So I can treat all objects within a system as located at the star for the pursposes of calculation. I do, however, need a way to specify routes from any Planet AsteroidBelt Moon Megastructure POI to any other. I also need to be able to search for other locations meeting certain criteria both to offer as destinations in the UI and to handle rendering . Each type of location will have some unique properties (Asteroid belts have resource distributions, for example whereas planets ave atmospheres) but they also have lots of common properties (inventory, owner, comms network node id, etc). Ideas so far Obviously, with the numbers I'm considering I need to take a sparse lazy generated approach. Currently the galaxy is built entirely in the GPU and stars are only presented to the CPU when the user first clicks on them. That lends itself nicely to a hierarchical data structure with a load on first access approach. Click on a star and it's added to the list, so the name is saved. Scan visit it and I'll generate the system contents. Unfortunately, I also need to be able to search across all generated locations efficiently (given an ID, find the star system coordinates, find planets with an atmosphere like X, find any location with X in its inventory) in a potentially huge search space. That doesn't align with recursively walking up down trees. I considered using a heirarchy and manually maintaining a number of separate indices to speed up searching. It's doable but a pain and error prone. It also feels like one of those solutions where I'm going to keep finding one more type of query I need to support and before long I'm trying to implement a minimal database. Speaking of which I also need to persist this data at some point. Currently I'm serializing to a densely packed binary blob. So... I took a step back and wondered whether I should actually use a database. I can see the benefits of using something like SQLite which I could bundle with the game and would handle persistence, indices, and the rest. Db? After spending a couple of days implementing the basics, I can see this is going to be quite a long and involved process. None of the friendly tooling works well in Unity, so I can't take advantage of entity framework w code first, nor nice Linq To Sqlite predicate handling. Even worse, most of the libraries to work with EF are tightly coupled to windows. EF Core seems like an option but I haven't been able to get it working in Unity (I need to do some assembly version mapping but as Unity overwrites the project file regularly and doesn't seem to support this itself, I think it's a losing battle). So I've headed down the route of implementing a data layer that generates SQL as needed. I can do that, but it opens up a huge can of worms in terms of manually maintaining the DB schema. I'm going to have to start tracking a DB version and bundling migration scripts with any update patch. It's a whole new maintenance burden. Question So... What am I missing? What's the elegant way to store a sparse hierarchy of data whilst still supporting flexible search across disparate object types that just happen to have a lot of common properties?


How to make an object covers a specific distance before moving in other direction for same distance? Suppose there is a small tile and I want an object to move on x axis on that tile back and forth. How can I make that object in that specific tile. My code is Rigidbody2D rb Start is called before the first frame update void Start() rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update() rb.velocity new Vector2( 3f, 0) As of now object moves left but I want it to start moving right and not go of the tile.


One side of every object is black I'm trying to make a driving game in Unity, but recently have been having lighting issues. When I was first building it, the lighting worked fine. However, recently, one side of everything (the indirect lighting side) has turned black. Here's an image of the issue. I've tried changing my lighting settings, but can't seem to fix it. Here are my lighting settings. What can I do to fix this? (I am using Unity 2017.2.0f3)


IndexOutOfRangeException on array of transform prefabs in Unity I have a public array of length 9 containing prefabs I'm using as position references for a moving object. The start function finds the transform.position of the appropriate transform in the array and makes it the target for a Vector3.MoveTowards() function that is called every update. I have an exception for the start function, but the object moves fine. If I print the length of the array on every update, It shows zero every other frame, and 9 otherwise. There's nothing in the script changing the array, how is this happening? I'm using the Linux build of Unity.


What determines the hit detection ordering for graphic elements in Unity (2d game)? I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated. Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered. How do you control the order in which buttons are registered by the mouse?


How do I account for the velocity difference between a ship and it's fired projectile? In my project, I have a ship that moves and increases it's movement speed with respect to time and how long the acceleration button is being pushed(just like the way a real life car works), now as expected, the ship fires projectiles when I press the fire button. The problem here, is that at a point in the game, the ship reaches it's highest speed terminal velocity, and now it's faster than the projectile it fired which is not what I want, so, how do I create a realistic projectile movement based on the ship's velocity? This is so that if the projectile is fired when the ship is moving slowly through the game scene, it doesn't move so fast that we can't see it travelling in the forward direction, and at the same time if it is fired when the ship is moving at top speeds, the ship is not seen to be faster than or as fast as the projectile's speed. I want to keep the code as optimized as possible, so I am using this line for the projectile's movement public float velocity 100f void Update() transform.position transform.forward Time.deltaTime velocity


Elastically Object movement in unity3d I want to move an object towards the destination elastically. Currently I am using Vector3.Lerp it working to move the object, start with high speed and reached at destination with low speed but missing elastic effects. float i 50, t 0 while (t lt 1) t Time.deltaTime i transform.position Vector3.Lerp(transform.position, newPostionAtDistance, t) transform.LookAt(targetFollow.transform) if (transform.position.ToString() newPostionAtDistance.ToString()) StartCoroutine(CamElasticMoveBackEffetcts()) Debug.LogWarning("Object reached to the point.") yield break smoothTime Time.deltaTime yield return 0 i


Reverse Movie in Unity 5 guys! Is it possible to reverse video or apply a rewind in Unity 5? I searched in the web but could not find the solution.


Raycasting from an object to the center of the screen (crosshair) without clipping through objects Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair. Using ViewportToWorldPoint I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below. The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be. Am not sure how to solve this. void Update() Vector3 ray Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f)) line.SetPosition(0, transform.position) RaycastHit hit if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)) if(hit.collider ! null) line.SetPosition(1, hit.point) else Vector3 pos line.GetPosition(0) line.SetPosition(1, ray (Camera.main.transform.forward raylength)) The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool


Roatating a Game Object downward In my game I have a rocket which is traveling horizontally across the screen. What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect. How do I do this?


How to approach debugging of java.lang.NullPointerException in android build of unity app? We are getting an obscure java.lang.NullPointerException when building a Unity app for android. There's not much information here that I can trace back to our code. Does anyone have advice about how to approach debug this? All I have to go on at the moment are logCat logs Uncaught exception thrown by finalizer java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference at java.lang.reflect.Proxy.getInvocationHandler(Proxy.java 891) at bitter.jnibridge.JNIBridge.disableInterfaceProxy(Unknown Source 0) at bitter.jnibridge.JNIBridge.delete(Native Method) at bitter.jnibridge.JNIBridge a.finalize(Unknown Source 15) at java.lang.Daemons FinalizerDaemon.doFinalize(Daemons.java 250) at java.lang.Daemons FinalizerDaemon.runInternal(Daemons.java 237) at java.lang.Daemons Daemon.run(Daemons.java 103) at java.lang.Thread.run(Thread.java 764) (Unity version 2018.1.0b10)


Box collider rigid body eventually moves through static collider I found this question, but I'm not sure if it applies to my problem. I'm hacking together a Pong style game, and my problem is with the walls (box collider, no rigid body) not completely stopping movement of the player paddle (box collider, yes rigid body.) Sufficiently fast mouse movement eventually moves the paddle through the wall. There is initial resistance, but I would expect Player Paddle to stop moving abruptly at the wall. How can I make this happen? I'm new to Unity colliders game dev. My player paddle simply moves up and down (Z axis) with up down mouse movement public class MouseMovement MonoBehaviour public float speed 10f Update is called once per frame void Update () var translation Input.GetAxis("Mouse Y") speed translation Time.deltaTime transform.Translate(0, 0, translation) I exported an asset package that reproduces the problem. My problem objects are Player Paddle, Upper, and Lower https www.dropbox.com s yx9svb51nywdvgg pong export.unitypackage?dl 0


Unity SceneView Positionning object with mouse position in Editor script I would like to create an editor tool who can change the position of an object in the scene view into other object in the world, based on mouse position, like in the picture bellow (the red pyramid is my object to positionnate rotate) I would like to do a raycast from the scene view camera to the mouse position (or something like that), to get the gameObject over the mouse, and then get the position of the verticle normal for position and rotation of my gameObject For now, I have tryed some code who didn't work, I have my object named "preview", and inside the methode OnSceneGUI() in a editor script i have managed to move my preview object, but now I have to know where to put it... Thanks ! EDIT here some of my try Transform previewPoint here my transform void OnSceneGUI() PointCreator() private void PointCreator() test 1 Camera sceneCam SceneView.GetAllSceneCameras() 0 Vector3 spawnPos sceneCam.ViewportToWorldPoint(Event.current.mousePosition) previewPoint.position spawnPos test 2 Vector3 mousePosition Event.current.mousePosition mousePosition.y SceneView.currentDrawingSceneView.camera.pixelHeight mousePosition.y mousePosition SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mousePosition) mousePosition.y mousePosition.y previewPoint.position mousePosition


How do game engines like Unity and Game Maker exports to other platforms? From what I understand, if you want to export a Unity or GameMaker game from the editor, the game needs to be compiled to create an executable. I thought that to produce a Windows executable, you needed to be on Windows. How does Unity and GameMaker compile to Mac and Linux, if the engine is running on Windows? Likewise, How do they export to Android and iOS? Do they use the NDK for Android? What about WebGL? How does the export actually work? Do they use a cross platform framework written in some programming language, and when you do things with the editor it generates code using that programming language and framework, so that when you export, that code gets compiled? For WebGL, since the UnityScript code doesn't get compiled, can we see the .js files with the code?


I need help with Admob in Unity this is my first Unity project and I'm getting desperate for answers. I've been trying to get Admob to work using the official plugin. It's been giving me a ton of problems as I can't get the banner to show, despite me using nearly verbatim code as tutorials. Here's my code using System.Collections using System.Collections.Generic using UnityEngine using GoogleMobileAds.Api public class AdMobTest MonoBehaviour BannerView banner InterstitialAd fullAdmob Use this for initialization void Start () RequestBanner() ShowBanner() void RequestBanner() string bannerID "Hiding my banner ID" banner new BannerView(bannerID,AdSize.SmartBanner,AdPosition.Bottom) AdRequest adRequest new AdRequest.Builder().Build() banner.LoadAd(adRequest) public void ShowBanner() banner.Show() public void RequestFull() string idFull "hiding my banner ID" fullAdmob new InterstitialAd(idFull) AdRequest adRequest new AdRequest.Builder().Build() fullAdmob.LoadAd(adRequest) public void ShowfullAds() if (fullAdmob.IsLoaded()) fullAdmob.Show() RequestFull() else RequestFull() Update is called once per frame void Update () I have a new 2D project setup with an empty scene and an "ad" game object, and a script added to that game object. I'm expecting something to show up on my phone's screen, but nothing is showing up. I know this may be a stupid question, but I've spent a ton of time on this, and I'm pretty new to this stuff. So please help me out!


Is Godot's NavMesh viable for dynamic pathfinding (e.g. avoiding moving enemies)? I am a novice (read low budget) designer looking at moving from Pygame to a real engine, and between Unity and Godot it looks like the latter has a much better 2D engine 1, 2, 3 . I would be happy to support Godot's open source model except that, as far as I can tell, its built in navigation mesh is purely static i.e. it can't update its path to account for dynamic obstacles 4, 5 while Unity's pathfinding system can 6 . So my question is Am I "stuck" with Unity? Or is there functionality that I haven't yet been able to find? Or, alternatively, is GDScript significantly faster than Python such that basic algorithms like fixed grid A would do the job? Edit By "stuck" with Unity I don't mean that it's a bad option or that there aren't good options I mean, 'if I need good pathfinding, do I have to give up on Godot and use what would otherwise be a second choice engine?'


Load 3D model from external directory I am developing a desktop application that want to load the 3D model from desktop. Using file explorer user wants to choose the 3d model then it want to show in the application scene.I tried to find the object, the path is detecting but if i tried to Instantiate it on unity it showing this error. ArgumentException The Object you want to instantiate is null. here the code is used public class ReadData MonoBehaviour string path GameObject go public void OpenExplorer() path EditorUtility.OpenFilePanel("Overright with model", "", "dae") Debug.Log(path) GetObj() void GetObj() if(path! null) UpdateObject() void UpdateObject() WWW www new WWW("file " path) go GameObject.Find(path) Instantiate(go) Anybody please help me to do this. Thanks in Advance.


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.