why is GetComponent returning null? As you can see in the attached image below and the code, I have added a class that implements the interface ICameraControl attached to a GameObject. When I call var controller GetComponent lt ICameraControl gt () , I get nothing returned (null), as in this example public class KeyboardHandler MonoBehaviour private void Start() var controller GetComponent lt ICameraControl gt () if (null controller) print("no ICameraControl found!") And the output is like this in the unity console no ICameraControl found! UnityEngine.MonoBehaviour print(Object) Assets.Player.KeyboardHandler Start() (at Assets Player KeyboardHandler.cs 18) Here's the Camera Position Handler attached to my game object Here's the interface implementation public class CameraPositionHandler MonoBehaviour, ICameraControl private GameObject mainCamera private Quaternion homePosition private void Start() mainCamera GameObject.FindGameObjectWithTag("MainCamera") homePosition mainCamera.transform.rotation private void LateUpdate() Any ideas what I am doing wrong? Much appreciated ) Matt Edit The keyboard script is on my player object (at bottom of the picture of the player object). And the Camera Position Handler is on the Camera Arm object. The Player object and Camera Arm objects are at the same level.


The best way to pass data between clients in a room I am developing a backgammon game in Unity and tried to use Photon. But I could not find a step by step help for it and I also know that photon in real time and it syncs data over 10 times per second. but I need to sync data after each moves. Would you please show me the best way to do that.


Unity Unable to take screenshots in server build I am trying to take snapshots in the server build of my Unity application. But the output image is all grey. From this post, I read that in headless mode, calling camera.Render() is necessary for rendering. I changed my screenshot logic accordingly. Here is my script private IEnumerator TakeSnapshot() yield return new WaitForEndOfFrame() var tempTexture RenderTexture.GetTemporary(Screen.width, Screen.height) camOV.targetTexture tempTexture camOV.Render() var tex new Texture2D(tempTexture.width, tempTexture.height, TextureFormat.RGB24, false) Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, tempTexture.width, tempTexture.height), 0, 0) tex.Apply() RenderTexture.active tempTexture Encode texture into PNG var bytes tex.EncodeToPNG() snapshotBase64 Convert.ToBase64String(bytes) File.WriteAllBytes( quot Users varun Desktop quot Time.time quot .png quot , bytes) Destroy(tex) I initalize the camera in the Start() method camOV Camera.main This works fine inside the editor but once I create a server build for Mac and try to run it I get this error. ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame. 0 ??? 1 operator delete (void , std nothrow t const amp ) 2 operator delete (void , std nothrow t const amp ) 3 operator delete (void , std nothrow t const amp ) 4 operator delete (void , std nothrow t const amp ) 5 (Mono JIT Code) (wrapper managed to native) UnityEngine.Texture2D ReadPixelsImpl Injected (UnityEngine.Texture2D,UnityEngine.Rect amp ,int,int,bool) Can someone give any suggestions? Thanks!


In Unity, how can I check if an input was made x seconds frames ago? I'm using the Rewired input plugin, and it comes with an input buffer. I enabled the buffer for my directional keys and airdash button so that the player doesn't have to hit both keys on the same frame in order to dash. However, this means that if you press both keys and hold them down for more than a frame, the airdash code gets run again. I tried to stop this by comparing Time.time at the beginning of Update() to Time.time at the beginning of the coroutine, but this seems inconsistent and it doesn't feel like the right way to do it. How would you check for the player's input time and compare it to the time since some previous input? Here's a sample of the dash code within FixedUpdate() Dash if (grounded) dashCount 0 dashTime 0 if (dashCount lt 2) print(currentTime dashTime) if (currentTime dashTime lt 0.1 dashCount 0) Double Tap Dash if (player.GetButtonDoublePressDown("Left")) StartCoroutine(Dash("left")) Button Dash if (player.GetButtonDown("Dash") amp amp player.GetButtonDown("Left")) StartCoroutine(Dash("left")) print(dashCount) and here's a sample of the coroutine Dash IEnumerator Dash(string axis) dashCount dashTime Time.time if (axis "left") if (inDash true) anim.SetBool("dashUp", false) anim.SetBool("dashDown", false) anim.SetBool("Hover", false) canControl false inDash true anim.SetBool("dashHorizontal", true) anim.SetBool("inDash", true) rigidbody2D.velocity new Vector2(rigidbody2D.velocity.x, 0) rigidbody2D.AddForce( dashForceHorizontal, ForceMode2D.Impulse) rigidbody2D.velocity Vector2.ClampMagnitude(rigidbody2D.velocity, maxVelocity) rigidbody2D.gravityScale 0 yield return new WaitForSeconds(0.2f) rigidbody2D.gravityScale 2 rigidbody2D.drag 25f yield return new WaitForSeconds(0.2f) if (grounded true) yield return new WaitForSeconds(0.1f) rigidbody2D.drag 0f canControl true anim.SetBool("dashHorizontal", false) anim.SetBool("inDash", false) inDash false yield break


Clamping the camera isn't so smooth when moving the camera around. Is there a way to make the clamping smoother? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook playerCameraCloseLook public CinemachineFreeLook playerCameraGameplayLook public float timeBeforeSwitching public float clampMin public float clampMax public float pitch public float speed private float brainBlendTime Start is called before the first frame update void Start() brainBlendTime Camera.main.GetComponent lt CinemachineBrain gt ().m DefaultBlend.m Time StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void LateUpdate() if (playerCameraGameplayLook ! null) pitch speed Input.GetAxis( quot Mouse Y quot ) pitch Mathf.Clamp(pitch, clampMin, clampMax) playerCameraGameplayLook.GetRig(1).GetCinemachineComponent lt CinemachineComposer gt ().m TrackedObjectOffset.y pitch IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) playerCameraCloseLook.enabled false playerCameraGameplayLook.enabled true PlayerLockManager.PlayerLockState(false) StartCoroutine(BlendTime()) IEnumerator BlendTime() yield return new WaitForSeconds(brainBlendTime) PlayerLockManager.PlayerLockState(true) I can look around up down left right using Cinemachine CinemachineFreeLook but when using the clamping in this script and then when moving the camera around with the mouse it looks like the camera is a bit stuttering jittering. Without the clamping, in the LateUpdate the camera will work fine but then I can't move the camera up down left right only to the left and right. The reason I'm trying to do the clamping on my own is that in the FreeLookCamera in the Axis Control gt Y Axis if I set the speed to 100 or 300 when I move the camera up and down it will also zoom in out on the player and I don't want that zooming but there is no option to remove disable the zooming.


Unity3D different object with the same mesh imported from Blender I would like to instantiate different objects (i.e. poker chips with different values) that actually share the same mesh imported from blender. To this end I have copied the assets and changed the texture but all the assets automatically switch to the last texture I choose as they are actually the same entity. What am i doing wrong?


Can I post to Facebook with my own text from Unity on behalf of the user? I'm using Facebook SDK for Unity 6.0 with FB.Feed. I'm trying to post a link to the user's feed, text and link on his behalf. So far I've managed to publish only a link and its details, the part where the user can write the post is left empty for him to fill.


How do I switch between different Update behaviour states in Unity? I have a bird entity that needs different update rules when it's moving or dying (among potentially other states). I want to avoid making my Update method a clutter of if else branches like this void Update() if(state movingState) Do moving logic. else if(state dyingState) Do dying logic. else if... Instead, I thought I could make a base class for all my bird behaviours, then derive classes for each state with their own update functions, and use the appropriate derived version based on the current state. public class BirdBaseModel MonoBehaviour void Update() ... public class BirdMoving BirdBaseModel void Update() ... public class BirdDying BirdBaseModel void Update() ... My BirdBaseModel is attached to the bird game object. Based on game states, I want to dynamically reference it in the GameController class. BirdBaseModel b if(State 1) b new BirdMoving() else if(State 2) b new BirdDying() Based on the above logic, I want to call the Update function of that particular class. How do I invoke the Update of the subclass?


How can I create a musical sheet using sprites?(Ocarina of time ) I am looking to make a musical sheet similar to the image below I want to use sprites prefabs have each sprite correspond to a different line Move down notes are more are being played have tail end notes disappear or go outside of text view (like when you type past a search bar) I am unsure if there is a UI asset in Unity that can perform what I just mentioned. I was thinking could just instantiate the prefabs in the right positions, shift them down, then delete the tail end prefabs as more are being played. Outside of that, I'm lost.


Why can changing a camera's position prevent it from rotating? I am going through the official introductory series "Roll a Ball" by the Unity team, and am on part 3 (youtube link. There is a ball with mouse controls attached, and a Camera set as a descendant of the ball so that it follows it around. As the tutorial mentions, the Camera at this stage "rolls" along with the ball and is unusable. The fix, as shown in the video, is the following added to Camera public GameObject player added through GUI private Vector3 offset void Start () offset transform.position player.transform.position void Update () transform.position player.transform.position offset I understand in terms of C syntax what this does, but I don't understand why it stops the camera from rotating. Isn't position controlled separately from rotation?


2D diagonal movement using Rigidbody2D I have a problem with 2d player movement, as I am unable to move on the Y axis. Yet, the movement on the X axis is working as intended. Below, you can see my code public Sprite directionUp public Sprite directionDown public Sprite directionLeft public Sprite directionRight public float speed 0.1f public byte direction 0 0 up, 1 right, 2 down, 3 left private SpriteRenderer spriteRenderer private Rigidbody2D rb2D private Sprite directionArray Use this for initialization void Start () rb2D GetComponent lt Rigidbody2D gt () spriteRenderer GetComponent lt SpriteRenderer gt () directionArray new Sprite directionUp, directionDown, directionLeft, directionRight if(directionArray 0 ! null) spriteRenderer.sprite directionArray 0 Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Keypad7)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad9)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.Keypad1)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad3)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.W) Input.GetKeyDown(KeyCode.Keypad8)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 0 else if (Input.GetKeyDown(KeyCode.S) Input.GetKeyDown(KeyCode.Keypad2)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 1 else if (Input.GetKeyDown(KeyCode.A) Input.GetKeyDown(KeyCode.Keypad4)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.D) Input.GetKeyDown(KeyCode.Keypad6)) rb2D.MovePosition(rb2D.position new Vector2(1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 By the way, please keep in mind I am quite new to Unity. EDIT 1 I have attached the entire script, some of the variables are unused right now(was testing other methods of movement). I tried to both Keypad 1, 3, 6, 9, as well as the combinations which I didn't get to work yet (but this is off topic and I will look into it once I will get the Y axis to move). Thanks, Zryw


Leaderboard setup for Android I am totally new for this setup. I am trying to implement google Leaderboard. I followed the step by step process showed in "This Link". i opened windows Google play games setup Android setup. In Android setup i named the class name and copy and paste the xml code from play store account This Picture Shows this then i clicked setup button. i got two popup boxes, Shows below, in console i got messages Note All my software's are updated version only. first i used jdk 64bit. now i uninstalled 64bit and i installed jdk 32 bit. still i got the same problem Anybody Please help. Edit 2 using This video now i fixed the error JAVA HOME not set. then in unity i tried to do the same. Now it displays another message shown below


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


Why won't my integer go down when my function is called? I'm trying to implement a limited use slow mo power into my game using C , but I can use it infinitely. Why won't my integer go down when my function is called? using UnityEngine public class TimeManager MonoBehaviour public float slowdownFactor 0.05f public float slowdownLength 2f public int slowmos 5 private void Update() Time.timeScale (1f slowdownLength) Time.unscaledDeltaTime Time.timeScale Mathf.Clamp(Time.timeScale, 0f, 1f) public void SlowMo() if (slowmos ! 0) Time.timeScale slowdownFactor Time.fixedDeltaTime Time.timeScale .02f slowmos using System.Collections using System.Collections.Generic using UnityEngine public class charcterMovement MonoBehaviour public TimeManager timemanager public Rigidbody rb public float forwardForce 1000f public float rightForce 100f public float leftForce 100f Start is called before the first frame update void Start() rb.useGravity true Update is called once per frame void FixedUpdate() rb.AddForce(0, 0, forwardForce Time.deltaTime, ForceMode.VelocityChange) Set Speed To Cube if (Input.GetKey( quot d quot )) rb.AddForce(rightForce Time.deltaTime, 0, 0, ForceMode.VelocityChange) if (Input.GetKey( quot a quot )) rb.AddForce(leftForce Time.deltaTime, 0, 0, ForceMode.VelocityChange) if (Input.GetKey( quot space quot )) timemanager.SlowMo()


Textures go black when changing Quality Settings at runtime Whenever I change my Quality Settings at runtime in editor mode or in build, all of my textures turn black. I use the following line to change the quality settings QualitySettings.SetQualityLevel(value, true) I have tried to set the boolean at false and it does the same result. I am using HDRP and the shader "HDRenderPipeline Lit" on pretty much all of my materials. There is an interesting fact, in editor mode, I just hover my mouse on any material inspector window, it updates all of my textures back to normal and solves the problem. Here is a screen showing the textures (left is normal, and right is bugged) Any idea ? Thanks.


How to execute a code from many scripts I want to execute a function from many scripts attached on gameobjects which will be spawned. Since game objects are spawned, I can't assign the script in the inspector. What i want is that, there are three gameobjects, A,B,C. C is already in the scene. A and B are spawned with different scripts,the spawned gameobject's script should call the function on the gameobject C. I can make a delegate but there are different scripts that want to call the function. So should i have to create different delegates for each script on A and B and then assign them onto the gameobject C so that A and B can call their delegates and these delegates will trigger the function on C or there is something like a event that i can call from B. If it was possible, i can create a event on A and assign it on C. Now A can call the delegate and B can also call that event and trigger the function on C, but this is not possible as event can't be called from another script. I need something like a function that i can call from any script and it calls the function from C. Note that function should not be static. As i can call a static function from any script but it can call only static methods, which i don't want.


In Unity, Change which mouse button is used to scroll in ScrollRect I've created a new ScrollView in Unity. How do I change which mouse button is used to scroll in ScrollRect (through script or in the editor). By default it's the left mouse button. I'd like to be able to change this to another mouse button. I'd also like to be able to use a keyboard key and disable it altogether (via script without also disabling the scrollbars), but mainly I at least want to change it from the left mouse button.


Texturing edges of a procedurally generated polygon I'm generating a polygon from code to display unit ranges in my game. Here's how it looks so far I would love to be able to now use my texture and only apply it to the edges of this polygon (imagine a stroke with no fill). Could someone point me in the right direction with this issue?


Can I keep get out of Unity editor features if I'm using ECS Pattern? I'm learning about ECS Pattern to use it in my Unity game, as I saw until now, most of stuffs is created by code. As I know, each Unity GameObject is a Entity which contains many of Components and GameObjects are instantiated by code (created by my script, for example). My question is, when I use ECS Pattern, can I keep using the bunch of features offered by Unity editor (like Prefabs, ScriptObjects, Drag Dropg to position, etc) or I need to control all of them by code?


How to make Sprites scroll with the background image that are inside Scroll View? I'm new in Unity, so I hope you guys can help. I'm developing a 2D game for Android device, on the scene I have a huge background image inside Scroll View (UI Scroll View). Next, I created new empty Game Object "Players", attached to it "Players script" and added "Sprite Renderer" component. From the Sprites I created two prefabs housePrefab and dogPrefab. Inside "Players script" I have the following code SerializeField GameObject housePrefab SerializeField GameObject dogPrefab void Start() var houseXPos 1.41f var houseYPos 2.63f var dogXPos 0.41f var dogYPos 2.63f GameObject house Instantiate(housePrefab, transform.position new Vector2(houseXPos, houseYPos), Quaternion.identity) as GameObject GameObject dog Instantiate(dogPrefab, transform.position new Vector2(dogXPos, dogYPos), Quaternion.identity) as GameObject After I run game both Sprites appears on the screen (as I expected). The problem occurs when I Scroll background image, both sprites stay in the same position under scrolling. In other words sprites not scrolling with the background image. As far as I understand, the Sprites needs to be added to the background image, but I don t know how to do it. How to make Sprites scroll with the background image? Thanks to all in advance.


How can I resize my Blender models when importing to Unity? I made a 3D model in Blender, but when put it in my Unity project and add an FPS camera the camera is bigger then my model. I used the measurements of Blender (that one cube is 1 meter in Unity). How can I fix this?


How can I instantiate enemies in a 2D game at a set Viewport Position before my camera enters the room? (Or alternative solution!) I'm currently working on a 2D game where I'm trying to pre populate my level with encounters, I want the enemies already in the room when the player enters. Right now the encounter is triggered upon entering the room when the camera bumps into the collider and the enemies are instantiated at the Viewport position, however because it does it while the camera is moving into the room the position is incorrect. Using hard values isn't an option because the maps could of course change and also I may want them randomly generated at some point. So I guess ultimately the problem is the camera not being in the right position when they instantiate and not wanting enemies to quot pop quot in once it is. Is there a way I can I instantiate an enemy at the same point on the screen regardless of resolution in each specific room at the start of the level? Encounters will have up to 3 enemies and they will always hold the same formation (with spots randomized to add diversity) Here is my instantiating code SerializeField public List lt GameObject gt levelEnemies new List lt GameObject gt () GameObject levelEnemy Vector3 enemyPosition Vector3 viewportPosition new Vector3(0.8f, 0.5f, 10f) Place on the screen I decided I want single enemies to appear Camera cam void Start() Debug.Log( quot Enemy Triggered quot ) cam Camera.main enemyPosition cam.ViewportToWorldPoint(viewportPosition) levelEnemy Instantiate(levelEnemies 0 , enemyPosition, Quaternion.identity) instantiate test enemy at the converted position navigation.DisableNavigation() Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3) Here's what should be happening when the enemy is instantiated (triggered manually through the editor once camera has been moved fully) Here is what happens when the camera collider bumps into the encounter collider Any help in the right direction would be much appreciated or a workaround! Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)


Combining rotation (using Quaternion Quaternion) doesn't work as expected I have fragment of code that has to rotate the camera to the direction where my cursor is as below float yaw mouseSensitivity.x Input.GetAxis("Mouse X") float pitch mouseSensitivity.y Input.GetAxis("Mouse Y") Vector3 camRotDir new Vector3(pitch, yaw, 0) this works Vector3 camRot mPlayerCamera.transform.rotation.eulerAngles camRotDir mPlayerCamera.transform.rotation Quaternion.Euler(camRot) this doesn't work var rotation Quaternion.Euler(camRotDir) mPlayerCamera.transform.rotation mPlayerCamera.transform.rotation rotation WithmouseSensitivity being an arbitrary Vector2 value representing mouse's sensitivity respectively on axis X and Y. The problem is when I convert the current camera's rotation in Quaternion to Euler angle, add the camRotDir to it and then convert the result back to Quaternion, it works properly, the z component in camera's rotation remains unchanged during this process. But when I first convert the camRotDir to Quaternion and add it to camera's current rotation by multiplying them together, I get unexpected behaviour, the z component was somehow changed. I have no idea why this happens, should Quaterion of (euler a euler b) (Quaternion of euler a) (Quaternion of euler b) ? Code run in Unity 2018.3.12f1.


Nuget in Unity with Mac OS I have moved over to Mac for Unity development, and am aware you can still use Windows .dll files in your project. I use NuGet as a secure method of getting specific dlls, and have usually done this on Windows by manually downloading the .nukpg and extracting the .dlls using WinRAR, then putting the dlls in Unity. So far, I have thought of two ways to do this on Mac 1.) Doing the same thing, but with a WinRAR alternative that can open .nukpg 2.) Using Visual Studio for Mac that has a NuGet interface built in with Unity Has anyone done this, or found a solution for getting package from NuGet in Unity for Mac?


Make one object rotate to face another object in 2D In my 2D project, I have an object that is sometimes above or below another object. Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object. (Here, following Unity's default setup, the z axis is the axis pointing into the screen)


With Unity and Mecanim, how do I trigger an effect animation? We have a Mecanim animation. We'd like to play a particle effect on it at a certain frame in the animation. Do we need to use an AnimationEvent and have it call a function that triggers the effect? Or is there some editor only way to do it without script? We're using Unity 5.3.5.


Use references to UIManager script or direct for children OBJs So I've got a canvas with UIManager script attached to it, the canvas has a lot of buttons and texts as children OBJs and they somehow need to communicate to each other. Should this be done through the UIManager or through direct scripts? EDIT Fixed, the point was to set other buttons and other UI elements active or de active, I ended up using different methods in the UImanager script to do so, without having like 20 scripts.


How can I add intermittent voice chat to a Unity multiplayer game? I'm looking to make a multiplayer horror game with one of the main mechanics being the game's internal voice chat. Currently I plan on making it cut in and out so that the players (being on opposite ends of the map from each other) will lose verbal contact with each other. I planned on using Unity. Do you know how I could go about making this work?


How can I make huge terrains in Unity? How can I make extremely huge terrains in Unity? It seems like I can set width and length to large values. But the Heightmap resolution only goes up to 4097 and the Detail resolution only goes up to 4048. Any ideas?


reuse texture between quad objects This question is specific to unity I want to spawn multiple blocks, each representing a letter. There will be more than one copy of an alphabet. I have a big texture which contains all the letters in it. I use a prefab to Instance all the Blocks(quads) during Awake(). At runtime, I'd like to assign a texture to these quads (identifying the letter). My code looks like this void Update () if there is no active block, spawn it if (activeBlock null) this.getNextBlock (ref this.activeBlock) protected Block getNextBlock(ref Block block) block this.deQueueBlock () char letter LetterMgr.Instance.getNextLetter() based on the letter, index into texture and assign the texture indices to this block ? How can I reuse this one big texture and index into each letter amidst all these blocks (quads) ? I will be rendering this on a mobile, so will need to squeeze all the performance I can. Details 256 x 256 per letter 8 columns x 4 rows Total Texture Size 2048 x 2048 Total number of blocks 100 PS Each of the letters will be moving and will eventually come to rest. So I will have some (around 6 7) actively moving blocks and others will be stationary.


Help understanding IEnumerator Move routine I have this code and I know what it does (it will move an object up and down) But I don't know how its elements work. Could someone please explain it to me? IEnumerator Move (Vector3 Target) What this IEnumerator do? while (Mathf.Abs ((Target transform.localPosition).y) gt 0.1f) Vector3 Direction Target.y Top.y ? Vector3.up Vector3.down Is this an if else? and if yes why if target.y top.y its first choice is vector3.up? transform.localPosition Direction 5 Time.deltaTime yield return null yield return new WaitForSeconds(1f) Vector3 newTarget Target.y Top.y ? Bottom Top Same line but result order is different ?.? StartCoroutine(Move(newTarget))


Buttons only trigger right left movement once, not continually I have a Unity mobile project where I am trying to use right left movement using two UI buttons situated accordingly. The issue is that it only moves the player to the right to the left one time, not continually when the player is holding the button down. I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released. I've tried making the void into a Coroutine, but nothing working works. Here is my code. (rightCallable and leftCallable are attached to the buttons). using System.Collections using System.Collections.Generic using UnityEngine public class playerController MonoBehaviour public GameObject player public float speed 1000f public GameObject left this is so the player may also use the A and D keys if they want, and it works fine. public void Update() var movement Input.GetAxis( quot Horizontal quot ) transform.position new Vector3(movement, 0, 0) Time.deltaTime speed Below is what isn't working public void rightCallable () StartCoroutine( quot moveRight quot ) public void leftCallable () StartCoroutine( quot moveLeft quot ) IEnumerator moveRight() var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null IEnumerator moveLeft () var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null


Animation conversion failed transform for bone not found? I'm trying to animate my first humanoid, and the animations in the Standard Assets pack (HumanoidIdle etc) work really well right out of the box. However, when I try to use other fbx files, like those in Unity's "Raw MoCap Data" pack, I get errors. I import the animations, select one, go to "Edit " and go to "Rig", select "Humanoid", copy the avatar definition from the character I'm trying to animate (e.g. Robot Kyle), and under "Animations" I will get an error like "Imported file RunBackward conversion failed Transform 'Left Thigh Joint 01' for human bone 'LeftUpperLeg' not found". When I compare the avatar of the character I'm trying to animate with the avatar that comes with the animations, they have the same bones defined, just with different names (which shouldn't matter, right?), so it's not that bones are missing. Using the animation with the default avatar also doesn't work, I get no error but my character goes into the first frame of the animation but then freezes. I've tried this with the standard models Ethan and Robot Kyle to the same effect. Does anyone know how to handle this import error?


Problem with Parameters for polymorphism class This is going to be a bit tricky but it is really bothering me so I hope you will have the patience to follow along ) Here is my very basic architecture So in the framework, I am creating I have Actions these currently have a list of Conditions or Considerations (same thing different name). While each Condition share some of the same functionality such as Returning a float score Using an evaluation formula They implement these in very different ways depending on the situation. Take a look at the following code CreateAssetMenu(fileName quot Consider my health vs max health quot , menuName quot AnAppGames AI Example Decisions Health Consideration quot ) public class MyHealth BaseConsideration private float health public float maxHealth public override float Consider lt T gt (BaseAiContext context, BaseAction action, T value) health value as float return EvaluateValues(health maxHealth) What you are looking at is my first attempt at making some sort of quot reusable quot Consideration. Now in the continuation of my development, I had to make the following Consideration public class DistanceFromMe BaseConsideration public float minRange public float maxRange private float ConsiderWithValues(Transform target, Transform caller) return EvaluateValues(new FloatData(Vector3.Distance(target.transform.position, caller.position), minRange, maxRange).GetNormalizedData()) public override float Consider lt T gt (BaseAiContext context, BaseAction action, T value) Transform target value as Transform if (target null) return 0 return ConsiderWithValues(target.transform, context.transform) public override float Consider(float x) return EvaluateValues(new FloatData(x, minRange, maxRange).GetNormalizedData()) And now the trouble begins I thought quot This is not a scaleable solution quot as soon as I need more than 1 generic parameter I am screwed and have to create additional overrides of this Consider function. So what I need is somehow to add different types of parameters to the Consideration however these parameters will vary a lot. Another problem I have with this is that when I loop through the list I won't be able to tell what parameters i needed and how to fulfill the needs of the Consideration. I thought of different ways of dealing with this inside the editor but I have come up empty ( Can anyone help me out with this architectural mess? ) It is worth mentioning that at the current point each of these are ScriptableObjects I am not 100 set in the fact that they should be but i am just not sure how to deal with this problem.


FSM Transitioning to another state I am using a Finite State Machine for my character who has the ability to change into various forms (Wolf, bird, ect). The character changing to each state is not instantaneous and has a transition period to the next state. Most FSM i've seen set the next state instantaneously. My question is what should I do for the transitioning state? For example the "HumanState" is transitioning to the "WolfState" should I make another state class for each transition (Example HumanState HumanToWolfState WolfState)? Or should I just have the state stay at the current state until the transition is done by using a coroutine and setting the state on completion?


Architecture for extremely modular game? I'm developing a modular game in Unity 5.6. Each module has very little overlap in assets with the others. I'm concerned about having a bloated repository after a few months of development, and since I'm using Bitbucket (a free account) I'm limited in my repo size, but not in my number of repos. So instead of having one huge folder for my game I'm considering having a launcher project and scene that loads builds from a folder in Assets. Each module would be its own project, and I would just drop its build into the launcher's folder. My question is, is this a reasonable approach to building a highly modular game? Hopefully I'll be continuing development for quite a while, and I want to make sure the project is as lightweight and extendable as possible. Or am I overthinking this, and should I just use one big repo?


How do I define a required component on a Unity game object? I have a script that expected the game object to have a Terrain component. Is there an attribute I can add (or some other way) which will prevent a designer from adding my script component MonoBehavior to a GameObject that does not have the Terrain component? The only alternative I have been able to find is to attach my script to something else, and then have a public Terrain field, which requires the user to attach the terrain object to it. (since the editor won't allow you to associate a different object type.) I just want the reverse. Any thoughts?


Unity Water Cube (to 2D game) I wonder if you can create a cube of water within the unity! I'm starting to use the Unity, and took a sought as to whether there was already something like this ... but have not found any tutorial The idea is to use the 3D feature of water and turn it into a 2D scenario As shown below For this result The idea would be to make the cube of the material is "water". Its possible?


Unity's 'Ambient' Occlusion occludes everything. How to do it better? I'm experimenting with custom AO solutions for Unity. While looking at the source for their built in SSAO effect, I noticed the shader is doing this half ao tex2D ( SSAO, i.uv 1 ).r ao pow (ao, Params.w) c.rgb ao So basically it's darkening the whole image as a post process where the AO term is lt 1, specular and diffuse components included. I'd like my version to only attenuate the ambient component while leaving the direct lighting untouched. So how to go about this? One option would be to go to the full on deferred renderer (not legacy light pre pass), compute the AO texture after the G buffer pass, and incorporate it into a custom shader to do the final lighting pass. But are there simpler options that would work with light pre pass or even forward rendering?


Unity aircraft physics I want to make a simple aircraft controller, what looks like little realistic in unity. I watch some video from airplane physics. and make a simple script in unity, but if I start, my plane cant move or if I change drag to zero, it cant lift. I tried to use real data and get it from wiki(F22 Raptor). To my game object, I gave the rigidbody component mass 19670 kg. Engine thrust 2 116000.0f Newton. private void calculateEnginePower() EnginePower engineThrust ThrottleInput private void calculateForces() angleOfAttack Vector3.Angle(Vector3.forward, rb.velocity) angleOfAttack Mathf.Clamp(angleOfAttack, 0, 90) coefficient Mathf.Pow(1225.04f rb.velocity.magnitude, 2) 1 M 2 2 where M is mach. if (coefficient gt 0.0f) coefficientLift (4 angleOfAttack) Mathf.Sqrt(coefficient) lift 1.2754f 0.5f Mathf.Pow(rb.velocity.magnitude, 2) coefficientLift 78.04f densy1.2754 kg m3, speed m s , (F22)Wing area 840 ft (78.04 m ) coefficientDrag 0.021f rb.drag coefficientDrag 0.5f Mathf.Pow(rb.velocity.magnitude,2) 1.2754f 78.04f rb.AddForce(transform.up lift) rb.AddForce(transform.forward EnginePower) roll, pitch... inputs from keyboard and mouse, EnginePower, RollInput... are simple properties and I call the Move function in a controller inside void Update. Move(float roll, float pitch, float yaw, float throttle) transfer input parameters into properties.s RollInput roll PitchInput pitch YawInput yaw ThrottleInput throttle AirBrakes false calculateEnginePower() calculateForces() calculateRotation() used these formulas for Lift force Lift formula for Lift coefficient Cl formula for Drag Drag formula and for Drag coefficient I used data from wiki too (0.021f).


How to code simple Goomba like AI for 3D Platformer? I'm making a 3D Platformer and have an enemy similar to a Goomba in terms of AI. How do I get the enemy to walk around and then follow the player when they're in range?


How to make camera smooth when following player When my character moves through my cameras 'FollowPlayer' script, the background just looks really glitchy and bad Is there anyway to fix this? This is my script using UnityEngine using System.Collections public class FollowPlayer MonoBehaviour Transform bar void Start() bar GameObject.Find("PlayerMovingBar").transform void Update() transform.position new Vector3( bar.position.x, transform.position.y, transform.position.z)


What game objects can have a "material"? In Unity, I created an empty GameObject called "Person". I created some child objects to it, such as "head" (a sphere), "body" (a capsule), "leg" (a box), etc. Then, I wanted to change the person's color, so I created a material. However, I could not drag amp drop it on the person I could only drag and drop it on each child object separately. My question is what game objects in Unity are allowed to have a "material" on them? And, is there a way I can put a material on a parent object, and let it affect all its child and descendant objects?


Why is this Mono Behavior in the animator? I'm looking through the 3D Game Kit from the asset store to accustom myself with the animator, and I'm just wondering what this is referring to. I was looking into controlling MonoBehaviors through the animation controller the other day and thought I had come to the conclusion that it couldn't be done directly, so what's this?


Unity Networked gaming 2019... What happened to NetworkBehaviour, OnServerStart() etc After a long break, I am now trying to learn some basics in networked gaming in Unity. I've installed the latest beta client (because I want to ultimately make a network multiplayer game but it will be many months of learning and building barebone prototypes to ensure I can get game objects spawning correctly and be controllable by the correct client etc etc I have some experience in Unet, by extending the NetworkBehaviour class. I don't remember exactly but there were things such as Client RPC and Command and also OnServerStart() methods etc. But I am aware Unet is being removed. And I tried to extend my class from NetworkBehaviour (I also tried NetworkBehavior lol) and it doesn't recognise it anymore. So what replaces OnServerStart() method and ClientRpc instruction? Ideally I want to use a Dedicated Server solution (which I will run on my own computer in order to play small tests online of my game). The game im trying to make to start off with is extremely simple. The 'player' is just a capsule which can shoot small cubes and give damage to other players. Also the player object 'you' are controlling will appear blue, but all the other players will be grey. Using Unet I was able to make the above small game idea work. But now I am unable to.


Seaming between procedurally generated terrain meshes in Unity I have been generating procedural terrain for an upcoming project however I am coming across a seaming effect between the tiles I have searched for solutions including this video. Here is the code (sorry for the lack of comments) chunkx and chunky are the x and y coordinates of the chunk that is being generated. seed is a randomly generated integer. float Gen Height(int x, int y, int seed) float height 0 float newx float newy for (float resolution 128 resolution gt 8 resolution 8) newx (seed 40f) resolution x resolution newy (seed 40f) resolution y resolution height (Mathf.PerlinNoise(newx, newy) 0.5f) resolution if (height lt 0) height 0 return height public List lt Vector3 gt Gen Vertices(int chunkx, int chunky, int seed) float height int x 101 List lt Vector3 gt vertices new List lt Vector3 gt () for (int i 0 i lt x i ) for (int j 0 j lt x j ) height Gen Height(i chunkx (int)x, j chunky (int)x, seed) heightmod vertices.Add(new Vector3(2 i, height,2 j)) if (height gt maxheight) maxheight height else if (height lt minheight) minheight height return vertices


How to hide objects behind an invisible plane? I am using Unity 2019.1.4f1 (personal) in regular 3D mode. I want to make a material for a plane that will cause everything behind that plane to be invisible. I want a character who steps through a doorway to appear to disappear into "hammerspace" when he passes the door frame. I will post pictures in a minute. Blender concept (note how space after the doorframe is successfully occluded) Unity WIP (note how path after doorway is not yet occluded)


3D model editor manipulators I'm trying to make my own 3D model editor to better learn 3D programming. I have my translate manipulators and I'm trying to calculate the Vector2 that the mouse would have to move in order to move an object down a specific axis. This will obviously change based on the position of the camera, position of the object and the axis. I have the majority of it working, I'm just not sure on how to finish it. If the camera is completely horizontal to the object then the values come out correct, but once I start to move the camera above or below the object the values start to get less accurate. I figure I need to incorporate the camera's up vector into it, but I'm not sure how. The code snippet is for the X axis. Vector3 meshCameraDistance meshPosition cameraPosition Vector3 angleAxis new Vector3(1, 0, 0) float meshCameraAngle Vector3.Angle(meshCameraDistance, angleAxis) Vector2 mouseDragDirection new Vector2(Mathf.Sin(Mathf.Deg2Rad meshCameraAngle), Mathf.Cos(Mathf.Deg2Rad meshCameraAngle)) if (meshCameraDistance.z lt 0) mouseDragDirection new Vector3( mouseDragDirection.x, mouseDragDirection.y) speed (manipulatorSpeed.x mouseDragDirection.x) (manipulatorSpeed.y mouseDragDirection.y)


(2D) Take player speed into account while shooting bullets In my top down 2D game, there is a plane as shown below The plane shoots bullets forward. For firing bullets, I use obj.GetComponent lt Rigidbody2D gt ().AddForce(transform.up 500) However, when player presses up arrow or A key, plane speed increases. At this point, bullets are slower than the plane and appear to move backwards when plane moves at maximum speed. How do I take into account player speed so that force applied takes into account player speed?


How to add Facebook Data Storage to Mobile Game? I was wondering how I would add the option for players to sign into their Facebook profiles on my mobile game and then have Facebook store their game save data, so they can recover it on any device when they sign into Facebook. Other Facebook features would include seeing their friends on the Facebook leaderboards, inviting their friends to the game and challenging their friends to beat their scores. I would hate for the Player's data to be lost, so the Facebook data save part is very important. A good reference to this feature is the Hungry Shark mobile game. I wasn't sure how this works. My programming friend and I are creating the game together, but he doesn't know how to do this and I don't know how to program. Once I figure out exactly what has to be done, I would like to hire a programmer who knows how to add this feature. Thank you!


Unity How do I fix the players model rotation in a NetworkManager to spawn properly? How do I fix the players model rotation in a NetworkManager to spawn properly? I created a game with the NetworkManager code. Player Model is a cone I made and imported. all works fine but when the NetworkManager spawns the player model it is sideways. I have tried turning it in 3ds but the player remains sideways when it is spawned by NetworkManager on run, Ohterwise the model is fine in unity, and no matter how I rotate it, in or out of unity , The NetworkManager Rotates it. All other objects attached to the main object remain with proper orientation all, All other objects including instantiated ones appear properly.


Efficient way to build a 360 rotation system with clockwise and counterclockwise direction I've been struggle with rotation for sometime now, maybe it isn't that hard for someone who dominates the mathematical side of things regarding rotation and angles but, I need to build a rotation system that rotates the player to either clockwise or counterclockwise direction according to the nearest direction to the target angle. I.E. If my player is rotated to 45 and the direction is changed to 135 , he must rotate 90 clockwise (from 45 to 135 ). If my player is rotated to the same 45 and the direction is changed to 315 , he must rotate 90 counterclockwise (from 45 to 315 ). This didn't seemed a big deal when I started, but it's been hard for me to build something that cover all the rotation possibilities, which tells me that I'm doing something wrong here. I mean, there's must be a couple of formulas that fit this problem and cover all the possible rotations or something. Right now, my rotation system is configured to a minimal of 5 degrees of rotation, wich means that the possible degrees goes from 0 to 355(it never get to 360, going back to 0 instead). I don't have a code to show cause everytime I try to build this, I reach to a point where there are so many possibilities that aren't covered by my tests that I end up deleting everything to try again, but I'm tired of this seemingly endless loop (for me anyway lol). Does anyone knows a way to build this? EDIT My project is 3D and the camera perspective is similar to sports games like NBA 2K or soccer games in general. The input is a Vector2 obtained with the new input system. I need to move my player around with root motion, which means that my goal with this system is to calculate the rotation data to be passed as an animation parameter (using a event), so the correct animation is played and the player finally rotate according to the animation. The main part of the code (calculation part) was built by a friend of mine, who has more knowledge than me. This is my current code if (movementVector ! Vector2.zero) targetRotationAngle Mathf.Atan2(movementVector.x, movementVector.y) Mathf.Rad2Deg cameraTransform.eulerAngles.y FUNCTIONAL CODE BUILT BY A FRIEND targetRotationAngle Mathf.CeilToInt(targetRotationAngle 5) 5 FUNCTIONAL CODE BUILT BY A FRIEND if (targetRotationAngle lt 0) targetRotationAngle 360 if (currentRotationAngle targetRotationAngle) return else if (currentRotationAngle lt targetRotationAngle) Debug.Log( quot Clockwise rotation in quot (targetRotationAngle currentRotationAngle) quot degrees quot ) if (currentRotationAngle gt targetRotationAngle) Debug.Log( quot Counterclockwise rotation in quot ((360 currentRotationAngle) targetRotationAngle) quot degrees quot ) currentRotationAngle targetRotationAngle This is a summarized version of my previous attempts (the ELSE part), I know my formula is wrong, cause it doesn't cover all the rotation scenarios, the more I tried to build, more of this IF's were nesting. That's why I've decided to ask...


Controlling Unity 3D cube with remote gyroscope This probably will go into conceptual things as well, but what I would like to do is take a Raspberry Pi (with a Sense Hat), transmit the gyro values to Unity, and effectively have a 1 1 realistic representation of orientation changes. I have no problem transmitting values from the Pi to Unity (though learning about hidden firewall rules was fun), however I am lacking some understanding of how to transform raw gyro values to something representative in Unity. I have not calibrated the Sense hat recently, but know that is something that should be done. For example, I am transmitting the pitch roll yaw values from the Pi (resting normally, these are about 100.30272132022793, 351.3885231076573 354.9306950697191). I have a cube gameobject that I've flattened out and set to the origin. My question is basically, what is the best way to translate raw values from some anonymous object to the Unity coordinate system, and have it rotate appropriately? I don't necessarily want its position to change, just rotation. Screenshot for reference. Raspberry Pi sending gyro data is on the left, Unity is on the right. Tabletop (flattened cube) is what I'd like to rotate to simulate a ball balancer.


How can I avoid instantiating multiple instances of a RigidBody? I could use a little help. I've a state machine for an NPC that does a melee attack. The problem I'm running into is that the current code instantiates multiple instances when I only need one per cycle. I could use some ideas. This is the chunk of code I'm working with public void ChaseToAttack() navMeshAgent.speed 3.5f slow down the navAgent float playerDistance Vector3.Distance(chaseTarget.position, transform.position) stop navMeshAgent to begin attack sequence if (playerDistance lt stopAtDistance) ensure enemy is always looking at player enemyToTarget ((chaseTarget.position offset) eyes.transform.position) if(Physics.Raycast(eyes.position, enemyToTarget, out hit, sightRange) amp amp hit.collider.CompareTag("Player")) navMeshAgent.Stop() currentState attackState StartCoroutine(FistTimer()) PunchCycle() ensure the enemy isn't hitting air amp will always look for the player else transform.Rotate(chaseTarget.position, searchTurnSpeed Time.deltaTime, 0) end look amp atttack player block void PunchCycle() StartCoroutine(AttackCycle()) void PunchClone() clone Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody clone.transform.Translate(0,1f,0) clone.velocity transform.TransformDirection(0.0f,0.0f,0.125f punchDistance) IEnumerator AttackCycle() move animation here AnimPunch() PunchClone() yield return new WaitForSeconds(4f) fistTimer BeAlert() Thanks in advance... EDIT Changed the code so it would only instantiate once but now, it will only instantiate only once even though it's still in the attack sequence. public void ChaseToAttack() navMeshAgent.speed 3.5f slow down the navAgent float playerDistance Vector3.Distance(chaseTarget.position, transform.position) stop navMeshAgent to begin attack sequence if (playerDistance lt stopAtDistance) ensure enemy is always looking at player enemyToTarget ((chaseTarget.position offset) eyes.transform.position) if(Physics.Raycast(eyes.position, enemyToTarget, out hit, sightRange) amp amp hit.collider.CompareTag("Player")) navMeshAgent.Stop() currentState attackState StartCoroutine(AttackCycle()) ensure the enemy isn't hitting air amp will always look for the player else transform.Rotate(chaseTarget.position, searchTurnSpeed Time.deltaTime, 0) end look amp atttack player block void PunchClone() if(!didClone) clone Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody clone.transform.Translate(0,1f,0) clone.velocity transform.TransformDirection(0.0f,0.0f,0.125f punchDistance) didClone true IEnumerator AttackCycle() move animation here AnimPunch() yield return new WaitForSeconds(0.75f) fistTimer PunchClone()


How can I move my player on exact x and y coordinates, like on a grid? I'd like to implement movement exactly like it is done in this game. (You can see it in action on YouTube.) I need my Player to always stay in the center of X and Y similar to grid movement, but with free movement line like. Only move on x and y lines. And I need smooth changes at intersections. var x Input.getAxis("Horizontal") var y Input.getAxis("Vertical") var deltaPos Vector2.zero if (Mathf.Abs(inputY) gt Mathf.Abs(inputX)) deltaPos.Y speed inputY Time.deltaTime else deltaPos.X speed inputX Time.deltaTime transform.position deltaPos


Unity Quaternion.LookRotation meaning I've gone through Unity's documentation for Quaternion.LookRotation, but I didn't get the full understanding of how it works. What is the meaning of Creates a rotation with the specified forward and upwards directions? And if I have to rotate my object in X axis I have to modify both X and Z axisVector3 lookAt new Vector3(relativePos.x, 0, relativePos.z) transform.rotation Quaternion.LookRotation(lookAt) , why can't I only just modify the X axis directly to rotate?


Best way to implement Finite State Machine for player character in Unity? I'd like to implement the player in my game as an FSM as described in this guide to programming patterns in games. What is the best way to accomplish this? Should I implement each state as a monobehaviour with a state interface that can be enabled disabled when the state transitions? Or would it better to the states as plain classes (with their own Update method) where the main player monobehaviour calls StateName.Update() from its own Update method (.e.g. void Update() currentState.Update() )


Creating an object in javascript with unity (unityscript) So I have a ton of experience with JavaScript (its what I do for a living) but I am new to unity. I have built a game engine in javascript but now want to move it over to unity. I have been trying to implement my player class but am running into this error. I have a getter function for my level up stats. and inside of my level up function I call that getter function and store it now I know this would work in normal javascript but its not in unity and I have having a heck of a time googling any information on objects in unityscript. Here is the relevant code function level getter() return base level exp float , lvl exp modifier float , current level int function level up() var level object new Object() level object level getter() level object.current level 1 level object.base level exp level object.base level exp level object.lvl exp modifier level setter(level object.base level exp, level object.lvl exp modifier, level object.current level) I guess my first question is, is it even valid to return an object like that in unityscript?(in the level getter() function). If its not valid what do people suggest I do instead. Set a getter function for each var? My second is how do I declare level object so that it can accept the return if it is valid, and so that I can access the members of the object. I have been looking around at tutorials and google for several hours now and have found nothing to clear up my confusion over objects in unityscript. So any help would be appreciated.


Rigidbody not working properly I have two objects a player and a wall. The player is passing through the long side of the wall but it collided with the short side of the wall. I want the player to collide with whole wall. Here is the code


Playing a video in AR using Vuforia and Unity 5 I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon.


Unity3d Delay between animation cycles trying to create simple 360 rotation animation on 2d object but can't understand delay between animation cycles, please check youtube video with issue https www.youtube.com watch?v JlLJLHvnkgo


How can I access a method via a string in Unity? I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this public string PlayerPrefsName public GameObject Button public string GadgetForSkin private void Start() GadgetChanged PlayerPrefs.GetInt(PlayerPrefsName) if (GadgetChanged 0) Button.SetActive(false) GadgetForSkin quot GadgetForSkin quot GadgetChanged public void GadgetChecker() GadgetForSkin() public void GadgetForSkin1() If it's not possible, how can I achieve something similar?


How can I push a button with VR hands? New programmer here. I am currently trying to create a sample game in Unity (2019.2.11f1) where I push a button using the VR hands of my Oculus Rift (the hands follow my controllers). I can't believe how difficult is to find documentation or tutorials for said task. I've tried to read documentation but I'm at a loss here. I have tried putting sphere colliders on the Hands, and tried to use raycast, with no success. I use the localAvatar with both grabbers as children, and the avatar is itself child of the OVR Player Controller prefab you get when you download the Oculus asset from the store. How can I achieve this?


Irregular Shaped Colliders For Unity Is it possible to create an irregular shaped collider? If so, how? Would I need to create a couple objects and group them up into one Game Object?


Overlap transparent particles without blending? (Unity) I'm trying to create a continuous output of light from an object (like the exhaust of a space ship), and I thought I'd use particles to achieve this. But I'm running into a problem with alpha blending. I'd like to decrease the particle system's alpha over time, but because there's such a high density of particles, they end up evaluating to a solid color for most of the system's duration. This blog post basically shows what I'm trying to achieve https mispy.me unity alpha blending overlap The idea is to use a stencil test to make sure pixels in a sprite particle aren't gone if they're overlapping another sprite particle. Pass Stencil Ref 2 Comp NotEqual Pass Replace Then the author adds an alpha cutoff to make sure transparent pixels on an underlying sprite don't prevent new pixels from being written. half4 frag (v2f i) COLOR half4 color tex2D( MainTex, i.uv) if (color.a lt 0.3) discard return color But this solution requires you to eliminate soft edges, so I'm thinking it wouldn't look good in a particle system. The author also hinted at an alternate solution involving ZTest, but I can't visualize what that would be.


Why do my objects with colliders go through each other, and how do I fix it? I am new to Unity and I am just experimenting with a player controller script (which I got off youtube) and another object which doesn't move. Both my player and the stand alone object have colliders and rigidbodies but when I move the player it goes straight through the other object. My player controller script is using System.Collections using System.Collections.Generic using UnityEngine public class PlayController MonoBehaviour public float speed private Rigidbody2D rb private Vector2 moveVelocity void Start() rb GetComponent lt Rigidbody2D gt () void Update() Vector2 moveInput new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) moveVelocity moveInput.normalized speed private void FixedUpdate() rb.MovePosition(rb.position moveVelocity Time.fixedDeltaTime) Nothing has been changed on the colliders (nothing ticked), and the rigidbody2D has been changed to kinematic.


trying to get an int grid of values from unity tilemap I'm trying to get a 2 dimensional grid of values from a tilemap and found this which seems to do the trick tileMap gameObject.GetComponent lt Tilemap gt () foreach (var position in tileMap.cellBounds.allPositionsWithin) Debug.Log(gameObject.name " " position) TileBase tile tileMap.GetTile(position) if(tile.name ! null) Debug.Log(tile.name) However, something strange happens as it produces two values, when I only have one tile on the tilemap and when I uncomment my .name log above it only works for the second value and errors for the first. Any help of the best way of finding values from tilemaps would be great.


How should I deal with different enemy types? I'm making simple space shooter game for Android in Unity. I want to have different types of enemies (different weapon, stats, movement schemes) and I'm not sure how to do it. I'm quite new to objective programming and I don't really know what classes should I create. I guess I could just make a prefab for every enemy since there won't be many types, but that is not what I'm looking for. I have some ideas First of all I'd write an BaseEnemy class and enemy type subclasses that inherit from it. My first idea is to create those without MonoBehaviour. Then I'd have to make an EnemyScript with MonoBehaviour that I'd add to enemy game object. It'd have a specific subclass object inside, which will set every variable. BaseEnemy would just have undeclared variables and in subclass I'd set particular values. But I'm not sure how to deal with different movement schemes then. I wouldn't be able to put move() function in subclass since it wouldn't have MonoBehaviour, so I'd have to find another way. I might put in EnemyScript every possible scheme and then use correct one depending on some type value, but it doesn't seem like a proper way, does it? The second idea is to just make a MonoBehaviour BaseEnemy class. Then while creating enemy game object I'd just add correct subclass script (aaand... I'm not sure how to do it ) Could you tell me which one is a better way? Maybe neither of those?


elements of list are changing their values I'm making an app that's similar to an alarm, the user enters time and days, for days I'm using toggles,and storing the values of toggles states in a list which is stored in a list that contain all the inputs of the type days, then the user could edit any of his inputs, his old input are supposed to be shown there , but the problem is even when I'm storing them, old values are changing when I add new elements,(that's when currentToggle is changing) so when he press edit values aren't the same as he entered them I think it has something to do with nested lists but I can't figure out how, ( assigning hours and minutes is perfectly working and both are normal lists) the confirm method is for when the user confirm his choice, and there's edit button that open a panel ,its values are the same as the user entered them before the index gives the number of the selected group of input, dayholder is the gameobject that contains all the toggles , and that's the part of the code that's related to what I've said Toggle toggles List lt bool gt currentToggle new List lt bool gt () List lt List lt bool gt gt daysAll new List lt List lt bool gt gt () void Start () toggles dayHolder.GetComponentsInChildren lt Toggle gt () public void confirm() checkON() daysAll.Add(currentToggle) public void editBut() GameObject panelC EventSystem.current.currentSelectedGameObject.gameObject.transform.parent.gameObject int index panelC.transform.parent.gameObject.transform.GetSiblingIndex() assignDays(index) void assignDays(int index) for (int i 0 i lt daysAll index .Count i ) if (daysAll index i true) toggles i .isOn true public void checkON() currentToggle.RemoveAll(item gt item ! null) for (int i 0 i lt toggles.Length i ) if (toggles i .isOn) currentToggle.Add(true) else currentToggle.Add(false)


How can I shoot an arrow if I know the shot power and target? I am trying to shoot an arrow at a target with a 100 success rate. Given the initial force applied to the arrow, the gravity, the location of the archer, and the location of the target, how can I do this in Unity? I have read How can I find a projectile 39 s launch angle?, and it contains the equation I am using However, this is only accurate when I am at the maximum distance from the object given its power. (Above the maximum distance means that the arrow cannot reach the target.) The closer I move to the target, the less accurate the arrow shot becomes, as it travels past the target. The angle is increased resulting in the arrow traveling a shorter distance as I'd expect, but it is not increased by enough. The script spawns an arrow (a simple sphere) and launches it towards a target. It fires once per second, but the closer to the target the archer is, the more inaccurate the arrow is. The case of the archer being too far from the arrow is not handled, but that is not my concern right now. using UnityEngine using System.Collections public class Archer MonoBehaviour public GameObject arrow Simple 3D Sphere public GameObject target Simple 3D Cube public float power 25.0f public Vector3 aim private void Start() StartCoroutine(ShootArrows()) private IEnumerator ShootArrows() while (true) yield return new WaitForSeconds(1.0f) Vector3 spawnPosition new Vector3(transform.position.x, transform.position.y, transform.position.z) GameObject arrowInstance Instantiate(arrow, spawnPosition, Quaternion.identity) as GameObject arrowInstance.GetComponent lt Rigidbody gt ().AddForce(Aim() power, ForceMode.VelocityChange) private Vector3 Aim() float xAim target.transform.position.x transform.position.x float yAim Mathf.Rad2Deg Mathf.Atan(((Mathf.Pow(power, 2) Mathf.Sqrt((Mathf.Pow(power, 4) ( Physics.gravity.y) ( Physics.gravity.y Mathf.Pow(HorizontalDistance(), 2) 2 VerticalDistance() Mathf.Pow(power, 2))))) Physics.gravity.y HorizontalDistance())) float zAim target.transform.position.z transform.position.z Vector3 aim new Vector3(xAim, yAim, zAim).normalized return aim private float HorizontalDistance() float xDistance target.transform.position.x transform.position.x float zDistance target.transform.position.z transform.position.z float distance Mathf.Sqrt(Mathf.Pow(xDistance, 2) Mathf.Pow(zDistance, 2)) return distance private float VerticalDistance() return Mathf.Abs(target.transform.position.y transform.position.y) My best guess is that I am using the equation correctly, but I am plugging the angle into Unity wrong. Why is my script giving me inaccurate results?


Why is Camera turning with different speed than Player with same code in different scripts? (with unity) I want to integrate a running character in my game, so I downloaded an animation via Mixamo. The player is running and if I attach the camera directly to the Player, it's shaking the camera and the game is not playable. Therefor I made a different script for the camera. In there, the camera is always following the player but turns (like the player) via float h PlayerMovement.horizontalSpeed Input.GetAxis( quot Mouse X quot ) transform.Rotate(0, h Time.deltaTime 60, 0) (for the camera) and float h horizontalSpeed Input.GetAxis( quot Mouse X quot ) transform.Rotate(0, h Time.deltaTime 60, 0) for the player. (horizontalSpeed is a constant) But after a few seconds I'm running in a completely different way then I look. Why is that and how can I solve this? I tried different animations nothing worked. Update If there is no rigidbody and no collider attached to it it works fine. But I need them.


Why doesn't anything run after the yield return new line I am trying to make a fade to another scene in unity when I came across a problem. For some reason when the coroutine begins the Ienumerator it only runs half of the Ienumerator Method which is only the anim.SetForBlue line. Heres my code. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class Loseforcube1 MonoBehaviour public GameObject blueWinPanel public Animator animForBlue Use this for initialization void Start() blueWinPanel GameObject.Find("Blue win panel") animForBlue blueWinPanel.GetComponent lt Animator gt () public IEnumerator WaitTillNextScene() animForBlue.SetTrigger("FadeBlueWin") yield return new WaitForSeconds(3.9f) SceneManager.LoadScene(2) void OnTriggerExit() if (GameObject.Find("Cube Player 2")) StartCoroutine(WaitTillNextScene())


Maintain UI position with Aspect Ratio Fitter and anchor preset is set to stretch So i have a text UI using Aspect Ratio Fitter with Aspect Mode Height Control Width and i set anchor preset to stretch upward . To make it easier to understand , i want my text to stretch upward only when screen height is increased , and at the same time , using Aspect Ratio Fitter , i want my text to keep width and height aspect ratio by stretching width when height is increased . And don't worry about screen height size become bigger than screen width size because i have separate UI for portrait . When i apply both anchor preset stretch upward and Aspect Ratio Fitter , UI cannot maintain it position anymore if screen height is increased . So my question here is straightforward , how do i keep my UI inside my camera view while using Aspect Ratio Fitter and anchor preset is set to stretch ? , if possible , can it be done using unity built in feature ? (without me writing the script) Here are screenshot below to show my problem (ps ignore the error it doesn't have any correlation with this problem) Before screen height change After screen height change


How to slow down this rotation My goal here is simple. I am making a top down shooter kind of game, and I want the player to simply rotate in one axis, towards where the mouse is on the screen. I got it working, but it rotates so fast that everything is out of control. The following method is called in Update() on my player's game object void RotatePlayer() var targetPosition new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100) targetPosition Camera.main.ScreenToWorldPoint(targetPosition) targetPosition.y transform.position.y Time.deltaTime transform.LookAt(targetPosition) That rotates in the direction of the mouse, but like I said it rotates so fast that you cannot control it. As you can see I tried to multiply by delta time, but that did not seem to do anything. Also, changing that last parameter of "100" to a lower number also does not do anything. Any help is greatly appreciated.


Unity Animator default values overwriten I have created a project to reproduce the problem I'm currently facing. I'm running a simple unity animation that moves a game object and expect to be able to reset the gameobject position. This can be done by adding an empty animation, that (since it does not change anything) simply writes the default values, thus returning our gameobject to its original position. But here is where things get complicated if the animator gameobject is set inactive while the animation is running, new incorrect defaults values will be saved when gameobject is activated, and I am unable to reset my gameobject position. To reproduce this issue, run the attached project (Download from here) Change the stop method to "PlayEmpty" Hit Start Animation and watch the left "Hello world" text travel. While it is traveling, click Disable Text GO. The left text disappears. Click Enable Text GO and see the text comes back at its last location. Click Start Animation and watch the left "Hello world" text travel. Click Stop Animation the text is returned to the position where it was when enabling the gameobject, rather than its original position. Any help is welcome, suggestions on how to change the code to make the above scenario work. Thanks, Yaniv


Verlet rope between two moving points connected with a spring joint? I'm connecting two moving rigidbodies using a spring joint in Unity. Between them, a rope will be rendered using a line renderer and I want it to move realistically as the joints move, without physics. I've read about verlet integration, but only found examples where one point moves, and the other one is calculated, for example a guy with a grappling gun, swinging back and forth. Here's the current implementation with spring joints. The second image shows a nice and smooth verlet rope with a line renderer. It's a little too lenient, but looks good. As this doesn't use physics, it doesn't let me move the object or affect the ship, for example if it was stuck on something. How do I make an elastic rope like the second image, between the spring joints, without the physics engine?


How to Load PDF file in runtime using PDF Renderer Asset in unity? Hello Guys I am working in Unity PDF Renderer. I will purchased that Asset but i need to Know, How to load PDF file one by one in run time in File path mode but old PDF File will remove and Load new PDF file in run time. can any one help


rigidbody cube falls off the ground Inspite my ground and cube contains colliders as i apply rigidbody it falls down....use gravity


Flexible and extendable system of level objectives (victory failure conditions) in Unity I'm trying to come up with a flexible system of level objectives for a Unity game. What I'd like to achieve is to have a system that on each level (scene) can accept a different set of (configurable) success failure conditions. Conditions can be repeated between levels but on every level a given type of condition should accept different parameters. For example on one level success conditions would consist of destroying all enemy units and on the other level success conditions would require destroying a specific enemy unit and escorting a friendly unit to a specific place on map. Failure conditions would for example be player death (on all levels) or not reaching a specific destination within a given time. First I've tried to approach this problem by using ScriptableObjects but abandoned this idea as it's not possible to save scene object references in a ScriptableObject. So I've come up with a kind of polymorphic system like this (pseudocode) public interface Condition bool IsFulfilled() public abstract class VictoryCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class AllUnitsKilledCondition VictoryCondition public List lt Unit gt units public bool IsFulfilled() foreach (Unit unit units) if (unit.IsAlive) return false return true public abstract class FailureCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class TimeOutCondition FailureCondition public float timeLeft void Update() timeLeft Time.deltaTime public bool IsFulfilled() return timeLeft lt 0 The idea here is to have a level manager that is given a set of victory failure conditions in the editor and have it continuously monitor all those conditions. In a simplest scenario a level is won if all victory conditions are fulfilled and lost if any failure condition is fulfilled. Unfortunately, I'm not sure how to create a LevelManager component that would expose those lists letting me add various conditions and configure them (for example letting me add a list of units from scene to AllUnitsDestroyedCondition). I think it would be doable with a set of custom property drawers for each type of condition but I'm wary of digging into this until I'm sure there is no other, easier way. I've come up with a way of adding various conditions by adding multiple condition components to a GameObject and then dragging those components to victory failure conditions lists in LevelManager. But this solution seems awkward and inflexible because it's not possible to dynamically add and configure new conditions in runtime and creating more complex conditions (for example some condition activating only after some other condition is fulfilled) seems like a sure way to create a huge pile of unmaintainable condition component mess. Please, let me know if I'm approaching this problem correctly and if not, what are other, simpler, more flexible solutions.


Helicopter controller, spherical world with faux gravity I followed this tutorial to create a planet with faux gravity that attracts objects. Further I'm trying to create a helicopter like controller that could move vertically and horizontally and that when the player presses control buttons this would compensate the faux gravity applied with AddForce to Rigidbody and the helicopter could fly. I implemented that in a way that when player presses buttons faux gravity with AddForce is not applied, but still the control feels very awkward. What would be the best way to compensate the faux gravity to move the helicopter? Edit I only need it to move in XY plane (so only up down left right). The camera looks on helicopter from its right side. The attractor script works in 3 axis and this is ok for now. Player controller (assigned to the helicopter) public class PlayerController MonoBehaviour public float moveSpeed 15 private Rigidbody rb private Vector3 moveDir private float h private float v void Awake() rb GetComponent lt Rigidbody gt () if(!rb) throw new Exception("Game Object must have Rigidbody!") void Update () GetControls() moveDir new Vector3(h, v, 0).normalized void GetControls() h Input.GetAxis("Horizontal") v Input.GetAxis("Vertical") void FixedUpdate() rb.MovePosition(rb.position transform.TransformDirection(moveDir) moveSpeed Time.deltaTime) Faux Gravity Attractor (assigned to the planet) public class FauxGravityAttractor MonoBehaviour public float gravity 10 public void Attract(Transform body) Vector3 gravityUp (body.position transform.position).normalized Vector3 bodyUp body.up Rigidbody bodyRb body.GetComponent lt Rigidbody gt () bodyRb.AddForce(gravityUp gravity) Quaternion targetRotation Quaternion.FromToRotation(bodyUp, gravityUp) body.rotation body.rotation Quaternion.Slerp(body.rotation, targetRotation, 50 Time.deltaTime) Faux Gravity Body (assigned to the helicopter) public class FauxGravityBody MonoBehaviour SerializeField float gravity 10 public FauxGravityAttractor attractor private Transform myTransform void Start () Rigidbody rb GetComponent lt Rigidbody gt () rb.constraints RigidbodyConstraints.FreezeRotation rb.useGravity false myTransform transform void Update () attractor.Attract(myTransform)


Unity, Does camera ALWAYS render to RenderTexture? I have a camera that renders a simple model to a RenderTexture. I then use that RenderTexture as a texture for my UI with a RawImage component. However, sometimes I disable my UI and therefore you can not see the RenderTexture. My question is Does the camera continue to render to the texture in the background even when the texture is not visible? If I understand how this works I believe it should. If so, simply disabling the camera should prevent it from rendering in the background? Thanks.


Joint based destructible physics (like Armadillo Run) I've implemented a destructible terrain system like Worms before (where weapons create holes in the terrain), but for the game I'm designing I want something more like Armadillo Run https www.youtube.com watch?v 4JoPlcyxxb4 where everything is made from individual parts connected by physics joints. I've figured out how to make a chain of planks using Unity's joints that can fall, swing off each other, bend if unsupported, and break at the joints. But I can't think of how to make planks break instead of the joints. There's an example of what I want at 2 25 in the video, where the plank on the right breaks (not the joints, but the actual plank itself). Obviously I'd just have to destroy the plank object, but how do I decide when to do that? I'm using the Unity engine (2D physics), but I'd be perfectly happy to implement something myself if someone can direct me to some research on the subject or anything else to help me get started.


How to customize player script with different abilities in each scene? I'm making a game with Unity. I wanted the player script to not have some features in some scenes but couldn't remove them from the script because I needed them for other scenes. So far, I just unpacked those player prefabs, created new scripts for each of them and removed the lines that I didn't want to have. I know this was not the best idea but I don't know any other way. One of its problems is that it makes managing the scripts hard and confusing. Is there a way that I can change them without creating new ones? Since I'm going to switch to the new Input system, I want to avoid the possible problems and headaches around these scripts. I also did this (creating a new script) for pause menu script as well. I provided two examples below to make the situation more clear. Example A) The player can use a shotgun in one of the scenes and I chose to not let him to use the knife in there. So I created a new script for that player and copied and pasted the original script (which had the melee attack ability) and then removed those lines from the new script. Example B) Pause menu can disable the health bar game object whenever the escape button is pressed. But for one of the levels, I don't want to use the health bar, so I pasted the code in a new pause menu script and removed the line that disables the bar.


Finding when shapes overlap and lines intersect but exclude points edges I've been looking for a c algorithm to help determine if shapes and lines intersect but want to exclude boundary overlaps. Here's an example My true problem is finding if polygons intersect but exclude boundary overlaps. I broke down the problem to look at the individual lines of that polygon and check each line segment from the shape1 against each line segment from shape2. A Is this an efficient correct way to do the checking? B How do I ignore when they are on the boundary as illustrated above? Here's some code I found here I've been testing for line segments but it fails on fig 2, when the end point of the 2nd line segment finishes on the end point of the 1st segment. private bool DoesLineIntersect(Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2) float denom ((end1.x start1.x) (end2.y start2.y)) ((end1.y start1.y) (end2.x start2.x)) AB amp CD are parallel if (denom 0) return false float numer ((start1.y start2.y) (end2.x start2.x)) ((start1.x start2.x) (end2.y start2.y)) float r numer denom float numer2 ((start1.y start2.y) (end1.x start1.x)) ((start1.x start2.x) (end1.y start1.y)) float s numer2 denom if ((r lt 0 r gt 1) (s lt 0 s gt 1)) return false return true


How To calculate camera boundaries Is it possible to calculate the exact camera bounds? By this I mean the white lines that represent the camera area e.g the lines in the picture I'm using Camera.main.screenToWolrdCoordinates to convert screen coordinates to world coordinates because I want to position the player exactly on that white line that the camera represents But when I calculate the boundaries using Camera.main.screenToWolrdCoordinates I get this The players legs are outside of that lower camera bound on y axis, it will also happen on x axis when I strict the players movement by using the value that I got from Camera.main.screenToWolrdCoordinates , I also have bouncing balls in my game that I want to strict by the same boundaries. So my question is how can I calculate camera bounds exactly by this I mean again these white lines that represent the camera view, I hope that my question is clear enought. Just to make it more clear, when I calculate the bounds using Camera.main.screenToWolrdCoordinates I just assign the Y value that I got from that calculation to the Y position of the player.


Having trouble making game time pause and unpause I've been trying to make it where when the player does a certain task, the game's time will pause. When the player does another action, the game's time would unpause and continue. I had my code like so using UnityEngine using System.Collections using UnityEngine.UI public class timeScript MonoBehaviour uGUI Items public Text date public Text playerCash Times public static int week public static int month public static int year 1980 amount of cash public static int myCash 10000 public AlertBox alert public Text timeText bool timeActive true int time int day void Start() InvokeRepeating("Timer", 0, 1) public static void Timer() timeText.GetComponent lt Text gt ().text "W" week.ToString() "" year.ToString() playerCash.GetComponent lt Text gt ().text " " myCash.ToString() region YEAR Check if month equals 13 (allows for 12th month to be counted) if (month 13) year month 0 endregion region MONTH Check if week equals 5 (allows for 5th week to be counted) if (month 5) month week 0 endregion region WEEK Check if day equals 8 (allows for 7th day to be counted) if (day 8) week day 0 endregion region DAY Check if Time equals 5 (allows for 4 seconds) if (time 2) day time 0 else time endregion I tried using CancelInvoke(timeScript.Timer()) in another c file but all it did was give me an error that stated I couldn't convert from string to void.


Unity WebGL Responsive content I was trying to develop a simple drag and drop items for Web. What I was trying to do is to make the UI elements from web view to mobile view when the aspect ratio is changes. I need this web view change to mobile view as below when the screen changes. Changing Canvas settings does not seems to be work. Could someone please help with this issue?


Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls)


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


How can I hide an object for one eye for the unity oculus rift DK2 platform? I am trying to build a game for my son for the Oculus Rift DK2 to help treat his lazy eye using Unity. I need objects that Appear only to his left eye Appear only to his right eye Appear for both eyes. (this helps force the brain to use both eyes together to form the complete scene) How can I pull this off? Thanks!


What is "Avatar" in the "Animation Controller" used for? I'm using animation layers for a model of type quot Generic quot . The quot Base quot layer contains an quot Idle quot animation. The quot Shooting Layer quot contains a pistol shooting animation. I want the shooting layer animation to only affect the upper body. To do that, I need to use an Avatar Mask, I think. In the avatar mask, I have to select if I want it to be of type quot Humanoid quot or of type quot Generic quot . I will not use a quot Humanoid quot avatar mask because my animations are perfectly tailored for my model, and I don't need any retargetting. Instead, I wanted to use the quot Transform quot avatar mask type. However, it seems to expect an avatar However, I haven't had the need to create one yet. Do I really need to create an avatar? I don't want any quot Humanoid quot , I want to have full control over my animations and over what's going on. I have tried quot Humanoid quot before, and for me, it's a total loss of control as I can no longer tell what is a bug mis use by me and what is automatic retargetting done by Unity, so I want to avoid it by any means. Why do I have to create an quot avatar quot ? What is it actually? Unity already has my generic model to work with, so it knows the transform. Why does it want an quot avatar quot ? Edit The strange thing is I can create an avatar the usual way gt quot Rig gt Create Avatar quot gt quot From this model quot . Then I have an avatar. In the avatar mask, I need to feed an avatar. I do this, then it shows my transform. Now I can delete the avatar, and it still remembers my transform. Strange... not sure why Unity can't simply use the transform.


change one object into another, and then back again in Unity For example, I would like to change a cube into a sphere, then change that sphere into a capsule, by pressing the up arrow. I would also like to be able to change in the other direction. Change the capsule into a sphere, then change the sphere into a cube, by pressing the down arrow. It would be great if i could add extra objects in, say a pyramid etc. Ultimately i would want to do this with something like a seed, sapling, and tree. Each with there own properties.


Build and Run results in an empty window Out of nowhere my builds are broken. The .exe just always gives me this little blank window but it runs fine in the editor. Here are some things I have tried Deleted the previous build files Deleted the Library folder Upgraded to 2020.2.4f1 Uninstalled Reinstalled Unity Deleted AppData Files Deleted branch and pulled it back down (the branch works fine for other people) Here are my resolution and presentation settings


Unintended sliding blocks Unity (5) physics A game I'm working on right now relies on the Unity physics system for collisions, gravity etc. This all works well except for one strange thing. When an explosive is placed on a stone cube, it'll slide right off. A video displaying the sliding behavior https www.dropbox.com s lr6lhnn30x61tvf Unity 202015 02 19 2013 41 39 54.avi?dl 0 The stone gameobject settings http puu.sh g3BFn c15483b8ea.jpg The explosive has the same settings except for that the Mass is 1. What could cause this weird sliding and how can it be fixed?


Make Build and Run faster Is there a way to build an apk faster? (by disabling some shader compilation, for example Hidden Post FX Uber Shader takes most of the build time) p.s. Yes I know about Unity Remote and use it this time I need exactly Build and Run.


How can I places objects to specific facial landmarks ? like ears and hats I'm currently trying multiple AR plugins in unity and I'm stuck in how to place certain objects in specific landmark positions. I used the landmark positions to spawn certain objects but they are way off from the intended areas I wanted. Here is the code sample I'm using the get the facial landmarks of the ears, mouth, nose and eyes MatOfPoint2f imagePoints imagePoints new MatOfPoint2f () Mat rgbaMat webCamTextureToMatHelper.GetMat() Rect detectionResult faceLandmarkDetector.Detect() List lt Vector2 gt points if(detectionResult ! null amp amp detectionsResult gt 0) points faceLandmarkDetector.DetectLandmark(detectionResult 0 ) if(points ! null) imagePoints.fromArray( new Point((points 38 .x points 41 .x) 2, (points 38 .y points 41 .y) 2), Left Eye Facial LandMark Position new Point((points 43 .x points 46 .x) 2, (points 43 .y points 46 .y) 2), Right Eye new Point(points 30 .x, points 30 .y), Nose new Point(points 0 .x, points 0 .y),Left Ear new Point(points 16 .x, points 16 .y) Right Ear )


www.texture and www.LoadImageIntoTexture both just show red question mark I'm trying to use this code I found in the Unity docs to display a remote image on a plane. However, no matter what URL I try, it only displays a red question mark. using UnityEngine using System.Collections public class KnowledgeWall WeatherMap MonoBehaviour The source image public string url "https radar.weather.gov Conus Loop northrockies loop.gif" public string url "http www.gstatic.com webp gallery 1.jpg" IEnumerator Start() Texture2D tex tex new Texture2D(4, 4, TextureFormat.DXT1, false) using (WWW www new WWW(url)) yield return www www.LoadImageIntoTexture(tex) GetComponent lt Renderer gt ().material.mainTexture tex I also tried the code here, which is slightly different. It gave the same result. Unfortunately this project is Unity 5.3.6. How can I fix this so Unity 5 displays the remote image?


FullSerializer Update serialized property name Currently we have some ScriptableObjects that are referenced by their name. This comes with some issues as names may change and also they don't have to be unique. We would like to switch to UUIDs. using FullSerializer System.Serializable fsObject(Converter typeof(CharacterDataConverter)) public class CharacterData public CharacterSO player public CharacterSO mentor The mentor field is currently serialized as mentorName. With the changes the serialized field name would be mentorUid. This is handled by the CharacterDataConverter, but this has to be updated all the time when CharacterData class changes and is often forgotten. Much simpler would be to use fsProperty using FullSerializer System.Serializable public class CharacterData fsProperty(Converter typeof(PlayerConverter) public CharacterSO player fsProperty(Converter typeof(CharacterSOConverter), Name quot mentorName quot ) public CharacterSO mentor But this can handle only either mentorName or mentorUid. Is there another solution? Maybe using versioning?


How to make it possible to change the width of the stripes? I am making a shader to create stripes based on this tutorial, but I cannot set the width for each stripe and make a shader that accepts light. Shader quot Unlit Stripes 2 quot Properties IntRange NumColors( quot Number of colors quot , Range(2, 4)) 2 Color1( quot Color 1 quot , Color) (0,0,0,1) Ratio1( quot Width 1 quot , Float) 0.1 Width for first color. Color2( quot Color 2 quot , Color) (1,1,1,1) Ratio2( quot Width 2 quot , Float) 0.1 Color3( quot Color 3 quot , Color) (1,0,1,1) Ratio3( quot Width 3 quot , Float) 0.1 Color4( quot Color 4 quot , Color) (0,0,1,1) Ratio4( quot Width 4 quot , Float) 0.1 Tiling( quot Tiling quot , Range(1, 500)) 10 WidthShift( quot Width Shift quot , Range( 1, 1)) 0 Direction( quot Direction quot , Range(0, 1)) 0 WarpScale( quot Warp Scale quot , Range(0, 1)) 0 WarpTiling( quot Warp Tiling quot , Range(1, 10)) 1 SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot int NumColors fixed4 Color1 fixed4 Color2 fixed4 Color3 fixed4 Color4 int Tiling float WidthShift float Direction float WarpScale float WarpTiling struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert(appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o float2 rotatePoint(float2 pt, float2 center, float angle) float sinAngle sin(angle) float cosAngle cos(angle) pt center float2 r r.x pt.x cosAngle pt.y sinAngle r.y pt.x sinAngle pt.y cosAngle r center return r float random(float2 uv) return frac(sin(dot(uv, float2 (12.9898, 78.233))) 43758.5453123) fixed4 frag(v2f i) SV Target const float PI 3.14159 float2 pos rotatePoint(i.uv.xy, float2(0.5, 0.5), Direction 2 PI) pos.x sin(pos.y WarpTiling PI 2) WarpScale pos.x Tiling int value floor((frac(pos.x)) NumColors WidthShift) value clamp(value, 0, NumColors 1) switch (value) case 3 return Color4 case 2 return Color3 case 1 return Color2 default return Color1 ENDCG


Maximum number of controllers Unity3D can handle I've been trying to find out the maximum amount of xbox controller Unity3D can handle on one editor. I know through networking, Unity is capable of having as many people as your hardware can handle. But I want to avoid networking as much as possible. Thus, on a single computer, and in a single screen (think Bomberman and Super Smash Brothers) how many xbox controllers can Unity3D support? I have done work in XNA and remember that only being capable of support 4, but for the life of me, I can't find any information that tells me how many Unity can support.