How do I use Unity's TargetRPC calls? Trying to send data from the server to a client I want to send a large amount of data to only one player, as it would be wasteful to do this for every player when only one player needs the data. After a bit of research, it appears that TargetRPC is the thing that I want to use. Unfortunately, TargetRPC was only introduced semi recently in Unity 5.4, and I have not been able to find a guide on how to use it properly. Here is a barebones version of my attempt so far using System.Collections using System.Collections.Generic using UnityEngine.Networking using UnityEngine public class TargetRpcTest NetworkBehaviour private List lt NetworkConnection gt finishedConnections new List lt NetworkConnection gt () void Start () We don't want to send data to ourselves. finishedConnections.AddRange(NetworkServer.connections) void Update () If we're not the server, we don't have any business in sending data to players. if (!isServer) return Do the code contained below for everyone we haven't done it for yet. foreach (NetworkConnection connection in NetworkServer.connections) if (!finishedConnections.Contains (connection)) TargetSendStuff (connection) finishedConnections.Add (connection) TargetRpc public void TargetSendStuff (NetworkConnection connection) print ("I've just received a target RPC call!") This code is all I could come up with, and it does compile properly. No errors are thrown on the server side, either. However, when a client connects to the server, Unity throws this error Could not find target object with netId 5 for RPC call ClientRpc InvokeRpcTargetSendStuff UnityEngine.Networking.NetworkIdentity UNetStaticUpdate() The 5 in netId 5 varies depending on which object I apply this script to. All objects I attach this script to are required to have NetworkIdentity component because of NetworkBehavior. I have tried applying this script to static scene objects as well as the players themselves, but for some reason UNet still can't seem to find the target objects. Also, I don't really need the TargetRPC call to apply to any particular object. The code within will do only operations to other objects, and even create new ones based on the sent data. All I need is some way that I can send data to specific clients.


Unity how to apply programmatical changes to the Terrain SplatPrototype? I have a script to which I add a Terrain object (I drag and drop the terrain in the public Terrain field). The Terrain is already setup in Unity to have 2 PaintTextures 1 is a Square (set up with a tile size so that it forms a checkered pattern) and the 2nd one is a grass image Also the Target Strength of the first PaintTexture is lowered so that the checkered pattern also reveals some of the grass underneath. Now I want, at run time, to change the Tile Size of the first PaintTexture, i.e. have more or less checkers depending on various run time conditions. I've looked through Unity's documentation and I've seen you have the Terrain.terrainData.SplatPrototype array which allows you to change this. Also there's a RefreshPrototypes() method on the terrainData object and a Flush() method on the Terrain object. So I made a script like this public class AStarTerrain MonoBehaviour public int aStarCellColumns, aStarCellRows public GameObject aStarCellHighlightPrefab public GameObject aStarPathMarkerPrefab public GameObject utilityRobotPrefab public Terrain aStarTerrain void Start () I've also tried NOT drag and dropping the Terrain on the public field and instead just using the commented line below, but I get the same results aStarTerrain this.GetComponents lt Terrain gt () 0 Debug.Log ("Got terrain " aStarTerrain.name) SplatPrototype splatPrototypes aStarTerrain.terrainData.splatPrototypes Debug.Log("Terrain has " splatPrototypes.Length " splat prototypes") SplatPrototype aStarCellSplat splatPrototypes 0 Debug.Log("Re tyling splat prototype " aStarCellSplat.texture.name) aStarCellSplat.tileSize new Vector2(2000,2000) Debug.Log("Tyling is now " aStarCellSplat.tileSize.x " " aStarCellSplat.tileSize.y) aStarTerrain.terrainData.RefreshPrototypes() aStarTerrain.Flush() ... Problem is, nothing gets changed, the checker map is not re tiled. The console outputs correctly tell me that I've got the Terrain object with the right name, that it has the right number of splat prototypes and that I'm modifying the tileSize on the SplatPrototype object corresponding to the right texture. It also tells me the value has changed. But nothing gets updated in the actual graphical view. So please, what am I missing?


Sound Management Help I just learned how to implement a Sound Manager and put sounds into it. The problem is, I'm making a platformer and I have a player, and two different types of enemies who all have footstep sounds. The main issue is that I'm playing all the sounds from the same sound manager and I made the footstep sounds of the player to play like this public void PlayMoveSound() if(audioSrc.isPlaying false) randomMoveSound Random.Range(0,5) audioSrc.PlayOneShot(moveSounds randomMoveSound ) I don't know how else to make it NOT sound like its playing 100 times per second so I did this. This gave birth to the issue that the looping audio which is the player's movement sound now blocks me from doing the same thing for the other characters' footstep sounds since it uses the same quot audioSrc quot AudioSource. Any hints on how different I can create a system for semi looping audio?


Lerp UI Color outside update method? I'm able to Lerp the color of a UI panel within the Update method. However I'd like to trigger behavior a single time when needed. If I put it in a method and call it it only changes for a brief time and doesn't fully complete. I could probably set a bool flag within the update method but that seems sloppy.


Unity2D Scaling and Locking Image to anchor points I have a script that uses Index to change an objects sprite using OnClick to move through the sprites, like a slideshow. I want the image to scale to the size of my anchor points, because I've notice that when I stretch the game or put the game on maximize play the image stays the same size and doesn't scale to the size of my anchor points. How would I do that? This is my script public Sprite Images Index starts at one because we are setting the first sprite in Start() method public int Index 1 void Start() Set the image to the first one this.gameObject.GetComponent lt SpriteRenderer gt ().sprite Images 0 public void onClick() Reset back to 0 so it can loop again if the last sprite has been shown if ( Index gt Images.Length) Index 0 Set the image to array at element index, then increment this.gameObject.GetComponent lt SpriteRenderer gt ().sprite Images Index Thank you. )


How to restrict movement of Leap Motion hand object I have a quot Hand quot GameObject controlled by a Leap Motion Controller. The Hand despite having RigidBody and Box Collider just seemingly moves with no regards to physics (transform translate movement I suppose). So it clips through other Rigidbody objects. I'm trying to pseudo introduce physics to it. I created a second GameObject quot HandClone quot (with Rigidbody and Box Collider) that copies the first Hand position but moves with actual physics. HandClone script private void FixedUpdate() rb.MovePosition(targetTransform.position) rb.MoveRotation(targetTransform.rotation) Now HandClone goes where Hand goes, and HandClone is successfully bumping into other objects. However, when HandClone gets stopped by something, Hand still keeps moving past HandClone and clips into the other objects, like before. Now I am thinking that the way to solve this is to constrict Hand's movements to the bounds of HandClone so that finally Hand will stop clipping through objects. But how can this be achieved, would that even work, and is there a better way? Will movement streamed from Leap Motion Controller even respond to scripts like that? Edit I've now decided to hide Hand and place HandClone where Hand was. But my script for HandClone to copy Hand's movements is making HandClone fly all over the place. Here's the script using System.Collections using System.Collections.Generic using UnityEngine public class clone1 MonoBehaviour private Rigidbody rb public GameObject target void Start() rb this.GetComponent lt Rigidbody gt () Update is called once per frame void Update() private void FixedUpdate() Vector3 newRotation new Vector3(target.transform.eulerAngles.x 8.5f, target.transform.eulerAngles.y 172.78f, target.transform.eulerAngles.z 94.02f) rb.MoveRotation(Quaternion.Euler(newRotation)) The reason why I am adding those float numbers is because when the game isn't playing, those numbers are what make HandClone sit in the correct position, so I thought it would help with alignment in playmode. But HandClone is just flying everywhere regardless. Any advice with making the HandClone stay attached to the avatar's wrist would help.


How to draw grass sprites without using gameobjects? I am making a rimworld like procedurally generated 2D game using Unity's tilemap system. Just like tiles, I also have to procedurally generate grass and trees. Each grass instance should have logic inside that keeps track of it's growth progress and update the grass size appropriately. The downside is, I have to have maps as big as 400x400. That could be THOUSANDS of grass instances and each of them having their own GameObject seems ridiculous and like the game would lag. How can instantiate those grass sprites without creating new gameobjects for each one while still being able to control the growth and similar things? (Come to think of it, the DOTS ECS system in Unity would be perfect for this, however it is nowhere near ready and many things I want to do are just not supported.)


Unity pixel art distorted sprites I have a problem rendering my pixel art sprites properly in Unity. So far I have one character in a sprite sheet I made, with frames of size 64x64. The actual sprite is roughly 32x32 but I left room for movement in animations. I import the sheet following pixel perfection procedures I found on the internet using these settings As for the orthographic camera I set its size using this formula orthoCameraSize screenHeight (2 32) If I zoom on the sprite in scene it looks fine but when in game it gets rendered quite poorly (in game in scene pics below) What could be the source of the problem? I applied every good practice advice I could find on the web... Thanks for your help!!!!


Why does my collider behave strangely after a coroutine So I'm trying to create a simple script that is going to handle the logic for cutting down a tree I'm experiencing some strange behaviour with my script. I have a private field which holds the quot HP quot for the tree which starts at 100, and when I hit the tree it goes down by 25 every time, so I need to hit it four times in order for me to cut it down. Once the tree reaches lt 0 in terms of HP it should play an animation which simulates the tree being cut down, wait a couple of seconds and then play another animation of it appearing again. Most of this works fine, it's not until after the animation, where I start my CoRoutine to wait for a couple of seconds it starts messing up. ISSUE The first time I cut it down, it works fine.. However.. After it respawns I need to hit it like 4 5 times for it to go down to 50 health and then it works like normal. So I hit it once, it gets to 75, I hit it twice, still at 75, 3 times.. still at 75.. And eventually, it starts going to to 50, 25, 0 etc.. This only happens after I cut it down the first time, and the first time it works fine. Here is my Tree script NormalTree.cs public class NormalTree MonoBehaviour public static NormalTree instance private int health 100 public Animator animator private void Awake() if (instance null) instance this animator GetComponent lt Animator gt () private void Update() if (health lt 0) KillTree() private void KillTree() StartCoroutine(TreeSleep()) IEnumerator TreeSleep() animator.SetBool( quot treedead quot , true) gameObject.tag quot DeadTree quot yield return new WaitForSeconds(3f) animator.SetBool( quot treedead quot , false) gameObject.tag quot Tree quot health 100 public Item DamageTree(int damage) health damage Debug.Log( quot Tree health health quot ) if (health lt 0) return new Item Amount 1, ItemRarity Item.ItemRarityEnum.Gray, ItemType Item.ItemTypeEnum.Log else return null And in my PlayerController I have this, which essentially checks if my hitbox collides with an object that has the tag quot Tree quot private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Tree quot )) var wc Skills.FirstOrDefault(x gt x.Name quot Woodcutting quot ) var tree other.GetComponent lt NormalTree gt ().DamageTree(25) if (tree ! null) inventory.AddItem(tree) wc.AddExperience(25) Debug.Log(wc.Level)


checking if an array rank is not equal to an int C I'm creating an inventory system for a dungeon crawler, I've got world gen, and player controls down, and this is the only snag. public Transform items public bool usingitem public int usingitemnumber public void Update() if (Input.GetKeyDown("1")) usingitemnumber 1 if (Input.GetKeyDown("2")) usingitemnumber 2 if (Input.GetKeyDown("3")) usingitemnumber 3 if (Input.GetKeyDown("4")) usingitemnumber 4 usingitem usingitemnumber true if (usingitem.Rank ! usingitemnumber) usingitem ! usingitemnumber false i need to check if a rank on the transform usingitem array is not equal to the int usingitemnumber , and if it's not equal to it set it to false, and keep the on that is equal to it true


Tools or techniques for UV unwrapping texturing terrain with features such as roads? I'm trying to create a map similar to Outset island in Loz Wind Waker. Here is an example of what I'm trying to create As you can see, the roads more or less have dedicated tris. However, when I look at the UV data, it looks like a complete mess For reference, this is the texture without any overlays I have no idea how to go about creating a similar effect in my own game are there any tools I can use? What is this technique called?


What are Unity3D Substances? I recently was a tutorial use substances in Unity3D. I understood that a Substance is a material we can dynamically manipulate at run time, but I am still unclear about it. Could someone shed some light on this?


How can I find the minimum required radius to draw a visible circle? The problem is that if for example xradius and yradius are set to 5 and the object is too big the circle will be hide under the object and won't be visible. So I want to find the minimum radius require to draw a visible circle. So I'm trying to use a recurse and loop over all the childs including the root objects to find what is the biggest radius and then to draw a circle according to the biggest radius. I created a new method FindRadius. The problem is how to get from this method the biggest radius from the List and then how to draw the circle on this radius size ? What xradius and yardius will be after finding the biggest radius ? using UnityEngine using System.Collections using System.Collections.Generic RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 Range(0, 50) public float xradius 5 Range(0, 50) public float yradius 5 public bool minimumRequireRadius false LineRenderer line private List lt float gt radiusList new List lt float gt () void Start() FindRadius(transform) line gameObject.GetComponent lt LineRenderer gt () line.positionCount segments 1 line.useWorldSpace false CreatePoints() void Update() CreatePoints() void CreatePoints() float x float y float z float angle 20f for (int i 0 i lt (segments 1) i ) x Mathf.Sin(Mathf.Deg2Rad angle) xradius z Mathf.Cos(Mathf.Deg2Rad angle) yradius line.SetPosition(i, new Vector3(x, 0, z)) angle (360f segments 1) private float FindRadius(Transform root) foreach (Transform child in root) TraverseHierarchy(child) var rend child.GetComponent lt Renderer gt () if (rend ! null) float radius rend.bounds.extents.magnitude radiusList.Add(radius) return radiusList 0 This is for RTS games too when selecting a unit and there should be a circle around it mark that the unit have been selected. For example now there is a circle drawn on the MissilesTurret the problem is that the circle radius is xradius 5 and yradius 5 the circle is too short and hiding under the turret base part so it can't be seen only if I will make a lot of zoom in And this is after making zoom in to the base part Now if before running the game I'm changing the radius of the circle from 5 5 to for example xradius and yradius to 10 now you can see the circle My problem is how do I know what radius the circle should be drawn for each unit s ? Each unit have another radius size. I don't want to draw it with the mouse for selecting yet I want it to be drawn and selected automatic. So I thought to calculate the minimum required radius for drawing the circle to be see it.


How to import a texture to be used as occlusion map? The same way normal maps need to be imported as "Normal map" in the import settings, how should I setup an Ambient Occlusion texture to correctly work? I've been searching around in the manual and the web but still not sure if AO maps should be imported as Lightmaps.


Should recoil be an animation or script? Should recoil for a rapid fire gun be be done through an animation or a script? I want the recoil to increase as I continuously fire, like a lot of FPS games do. I was initially considering achieving this through a script in unity that rotates the gun slightly each time I fire, but I realized that since I plan to have most rapid fire guns be 2 handed weapons, at some point, the left hand won't be on the weapon. However, since I also want the recoil to increase as I fire, I'm not sure how I can achieve this in an animation. How is recoil typically done? Input on this would be very much appreciated.


If I want to create a top down 2D game should I rotate the camera? Do I have to rotate the camera to top down view if I want to crate a top down 2D game or just disable gravity?


How can I have a Mecanim animation with displacement and physics? I have 3D wolf models from my animator with displacement (i.e the wolf transforms with animation, not in place). I have added rigid bodies to the models. I am facing following issues while executing them in my project When I turn on IsKinematic on my rigid body (i.e disable physics) the animations work perfectly, with displacement. But I need to have physics enabled on my wolf because it doesn't detect collision when physics is disabled and gravity doesn't have any impact. When turn off IsKinematic (i.e enable physics), the animations don't work the wolf start wobbling and flying in the air. How can I resolve this?


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


How to create a spiral brightness gradient I am stuck on creating a brightness gradient that looks as below(the values are continuous from the inner circle). What formulae can create such brightness gradient? So that when Time is added to it, it will slowly brighten up from the inner circle in a spiral form? Tried a long time to modify from codes below but fail. Shader quot Unlit testDisplay quot Properties MainTex ( quot Texture quot , 2D) quot white quot SubShader Render with transparent objects, after the opaque pass. Tags quot RenderType quot quot Transparent quot quot Queue quot quot Transparent quot LOD 100 Don't write to the depth buffer. ZWrite Off Additive blending (add light glow). Blend One One Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) Shift our texture coordinates so 0 is in the center, and we go to 2 ... 2 at the edges. o.uv (v.uv 0.5f) 4.0f return o fixed4 frag (v2f i) SV Target Define boundary value for radius float radius length(i.uv) radius radius (radius 0.5) 0.5 convert to polar coordinates float angle atan2(i.uv.y,i.uv.x) float angle1 frac(angle (2 3.142f)) float result 4 radius angle1 13 frac( Time.x) return result ENDCG


How to search for all uGui scripts in scene in the Unity editor? I have many game objects whose properties I need to edit because of a bug error. However, this is very time consuming, because I need to check each game object one by one. Is there any way to search for all game objects that (for example) contain uGui Scripts in a scene?


Unity Additive particle effect blends with background I created a fire particle effect with the Particles Additive (Soft) shader in Unity 5.2.2, and it looks fine against a dark background, like the editor background However, when I move it in front of a lighter background, it looks like this I think the additive property is blending with the background, is there a workaround to make the effect look like how it looks on a dark background, without using a different shader? I've looked at this question How can I achieve a good fire effect with alpha blending and particles? but I'm not sure how I would execute that in Unity.


How can I create lit up areas during night time in a top down 2D game? I am trying to implement a super simple day night cycle. It works fine, at 9pm it gets dark, and at 6am it gets bright. However, I am "creating" darkness by simply setting the alpha of a black Image that covers the entire screen, ie if(NightTime) Color tempColor dayNightImg.color tempColor.a 0.5f dayNightImg.color tempColor isDark true So, in order to create the Illusion of light, I would have to be able to ignore part of this Dark Image, i.e "Light it up", for example in a circle around my character. Is there some way I can do this? Or Is my approach too simple for this effect? Here is an example of what I want


Unity Is type casting every frame too expensive? I have a state machine that controls my enemy AI. Each AI has a target which may be a Player, an obstacle, a shell, or even a Vector2 position. I'm trying to abstract my "target" member, and my first thought was to use GameObject, then downcast to whichever type I need for different enemies. Examples below class StateController MonoBehavior GameObject target FireAction action Update() action.Fire(this) class FireAction ScriptableObject public abstract void Fire(StateController c) Examples of different fire scripts class FireAtPlayer FireAction public override void Fire(StateController c) Player p c.target as Player use properties of Player object class FireAtPoint FireAction public override void Fire(StateController c) GameObject t c.target as Player use properties of GameObject object As you can see, my Fire methods would cast the target object at every call to Update. Will this negatively affect my game's performance? Note that I know for a fact what type of object the target is, so I'm not guessing when I'm casting. Thank you in advance of your help!


How to add constant force to player with sperical gravity planet.? I have a planet and character. My player move perfect around planet with pressing key like 'w','s','a and 'D'. I want to move my player on every frame with same force around sphere. I try plane surface constant force code like this this.rigidbody.AddForce ( 3f,3f,3f) , when start playing game this code work fine but after some movement it stop my player on specific position of planet. I want to use this code for 3D sphere. Any one can help me how can add constant force to my player on 3d sphere.? I want add constant force to player when game start. I don't want any kind of planet's orbits, because my player is moving on all over the planet. I try below link but it did not working for me. How can i accurately simulate orbits in unity.? Here is my Sctipts PlayerController.cs using UnityEngine using System.Collections public class PlayerController MonoBehaviour public float moveSpeed 10 public Vector3 moveDir Rigidbody rigidbody Update is called once per frame3 void Start() rigidbody GetComponent lt Rigidbody gt () void Update () moveDir new Vector3 (Input.GetAxisRaw("Horizontal") ,0,Input.GetAxisRaw("Vertical")) void FixedUpdate() rigidbody.MovePosition (rigidbody.position transform.TransformDirection(moveDir) moveSpeed Time.deltaTime) FauxGravityBody.cs using UnityEngine using System.Collections RequireComponent (typeof (Rigidbody)) public class FauxGravityBody MonoBehaviour public FauxGravityAttractor attractor public Transform myTransform Rigidbody rigidbody Use this for initialization void Awake() this.rigidbody GetComponent lt Rigidbody gt () void Start () myTransform transform rigidbody.useGravity false rigidbody.constraints RigidbodyConstraints.FreezeRotation Update is called once per frame void Update () attractor.Attract (myTransform) FauxGravityAttractor.cs using UnityEngine using System.Collections public class FauxGravityAttractor MonoBehaviour public float gravity 10 public void Attract(Transform body) Vector3 gravityUp (body.position transform.position).normalized Vector3 bodyUp body.up body.GetComponent lt Rigidbody gt ().AddForce (gravityUp gravity) Quaternion targetRotation Quaternion.FromToRotation (bodyUp, gravityUp) body.rotation body.rotation Quaternion.Slerp (body.rotation, targetRotation, 50 Time.deltaTime) I am working with this scripts, If any one help me? then please.


How to implement 3d maneuver gear physics in unity? I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here. How do I go about implementing 3d maneuver gear physics from attack on titan anime? What is it? In case you don't know, here's a brief link about 3d maneuver gear. A brief commentary about 3dMG It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about. My Approach so far I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific. The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry. So any general idea would be greatly appreciated.


Why does WorldToScreenPoint return "strange" results? I would like to show a menu to the right side and at the same y coordinate as a certain gameobject (shown as a green cube in the screenshot). Therefore I'm trying to get the screen coordinates of the object in my scene using WorldToScreenPoint. The code I'm using is this Vector3 nPos new Vector3(GlowCube.position.x GlowCube.localScale.x, GlowCube.position.y, GlowCube.position.z) Vector3 nOff Camera.main.WorldToScreenPoint(nPos) The resulting values however don't look right to me. I have created a red rectangle in order to demonstrate where the coordinates "nOff" would actually be in the screen At first I thought I get these strange results because the GlowCube is parented to the case, but since I use GlowCube's world coordinates (GlowCube.postion...) and not its local coordinates (GlowCube.localPosition...), I thought that this wouldn't matter. What am I forgetting here? Thank you!


Playing a simple camera animation with Animator I haven't worked with the animation system in Unity before and am getting overwhelmed trying to figure out how to start playback of a simple animation. Yes, this is a "stupid question", but I've spent more than an hour researching this and can't find an answer on how to do something this simple I've created an animation called CameraZoom for the scene's camera. The CameraZoom animation is supposed to play when a specific event occurs, so I want to trigger it from script. I've created the animation on the camera, it has the Animator component attached to it, and by default the animation plays as soon as the scene starts. I can stop the animation from code, but when I try to start it, nothing happens. Here's my code private Animator myAnimation void Start () myAnimation gameObject.GetComponent lt Animator gt () myAnimation.Stop() public void ZoomOut() Debug.Log("Zoom out!") myAnimation.Play("CameraZoom") This script successfully stops the animation when the scene starts, but when I call ZoomOut, the animation doesn't play. Here are the states It may be I'm not understanding how to utilize the state machine and I'm trying to play the animation incorrectly. Tutorials I can find on the Animator are either too vague or discuss other features such as triggers and parameters that I don't know how to apply to such a simple task. I know I could whip up a Coroutine to zoom the camera out in about 30 seconds, but I'm trying to learn how to utilize the Animator for basic keyframe animations.


Alternative to System.Drawing for breaking an image into separate tiles in Unity As far as I can tell, System.Drawing namespace is not available in unity. I there an alternative library to load and manipulate or generate images on the fly? Example Imagine you want to make a jigsaw puzzle game and want to load and chop random images to use as textures or such. EDIT specifically I want to crop images and draw patches from one image onto another image. Or overlay images with grids. Ultimately all the resulting images need to end up as textures on game objects. If need be, I can use texture.EncodeToPNG to save a copy for other purposes or for as a cached result. EDIT AGAIN Let's stick to a concrete example. Player selects a photo from their iPhone library. It is chopped into pieces and appears on 9 cubes. the player need to arrange the cubes in the correct way to recreate the original image.


Rotate Rigidbody to face away from camera with AddTorque I have a camera that rotates around an object with "Look At" . I want the object to rotate to face the direction the camera is pointing (Camera.main.transform.forward) using AddTorque, but I can't understand how. I tried to create a rotation in which the more the object's forward vector rotates towards the camera, the more it should slow down the rotation until it stops. But it only works in sections, when I use the rotation of the camera the object rotates and then stops, as if it detects only one part of the rotation, while the other is a blind spot. What equation can I use to rotate the object well? var currentR rb.rotation.y var targetR Camera.main.transform.rotation.y rb.AddTorque(transform.up 1000f (targetR currentR)) DMGregory I put your script as it is in a separate new script on a new object, equipped with a rigidbody. I post the script how I entered it. At "targetOrientation" I gave the value of "Quaternion.LookRotation (Camera.main.transform.forward) " because I want the object to follow the direction of that camera. The result is that all the axes of the rigidbody are influenced by the rotation (if I lift the camera the object turns towards the ground, etc.), and above all that the rotation works even if I block the axes with Freeze Rotation, and with this script the object is no longer affected by external forces. public class rotation MonoBehaviour private Rigidbody rb public Transform direction Start is called before the first frame update void Start() rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() Quaternion targetOrientation Quaternion.LookRotation(Camera.main.transform.forward) Quaternion rotationChange targetOrientation Quaternion.Inverse(rb.rotation) rotationChange.ToAngleAxis(out float angle, out Vector3 axis) if (angle gt 180f) angle 360f if (Mathf.Approximately(angle, 0)) rb.angularVelocity Vector3.zero return angle Mathf.Deg2Rad var targetAngularVelocity axis angle Time.deltaTime float catchUp 1.0f targetAngularVelocity catchUp rb.AddTorque(targetAngularVelocity rb.angularVelocity, ForceMode.VelocityChange) I set a command if (Input.GetKeyDown (KeyCode.T)) rb.AddTorque (transform.up 5500f, ForceMode.Impulse) to rotate the object with an impulse and this does not work when your rotation script is active. I also place a video where you see the object before activating the rotation script, and after it is active, to see how it does not react to the impulse with T, and how it rotates reacting on all rotation axes, while I want only that the rigidbody only rotates its Y axis of rotation, in the direction of the camera (as a person does when turning in one direction). In the video The axes of rotation X and Z are on freeze (otherwise without fixed the rotation the object falls moving). I also put a video of the desired effect taken from a game so as to explain me better. My video desired rotation


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


How do I simplify this code with an Array and counting int up in Unity? I want to simplify my code. I had the idea of making an Array of waypoints and and int i to count up each time I arrive a new point of waypoint but it should be the same way my code is but instead of waypoint1.position... waypoint3.position I thought it should be like waypoint i .position and it counts up everytime I reach another waypoint this would simplify a lot and would make the code much shorter. The code is for moving an Object from A to B from B to C and so on.. I commented some lines how it would look like but ignore the MOVE ROTATE comments Code public float speed public float turnSpeed Starting with these somehow public Transform waypoints private int i 0 public Transform player public Transform waypoint public Transform waypoint1 public Transform waypoint2 public Transform waypoint3 public bool b0 true public bool b1 false public bool b2 false public bool b3 false public bool b4 false void FixedUpdate () if(b0) MOVE player.position Vector3.MoveTowards(player.position, waypoint.position, speed Time.deltaTime) ROTATE var rotation Quaternion.LookRotation(waypoint.position player.position) player.rotation Quaternion.Slerp(player.rotation, rotation, turnSpeed Time.deltaTime) float distance Vector3.Distance(player.position, waypoint.position) Debug.Log (Mathf.Round(distance)) if(distance lt 1) i b1 true b0 false if(b1) MOVE player.position Vector3.MoveTowards(player.position, waypoint1.position, speed Time.deltaTime) ROTATE var rotation1 Quaternion.LookRotation(waypoint1.position player.position) player.rotation Quaternion.Slerp(player.rotation, rotation1, turnSpeed Time.deltaTime) float distance1 Vector3.Distance(player.position, waypoint1.position) Debug.Log (Mathf.Round(distance1)) if(distance1 lt 1) b1 false b2 true if(b2) MOVE player.position Vector3.MoveTowards(player.position, waypoint2.position, speed Time.deltaTime) ROTATE var rotation2 Quaternion.LookRotation(waypoint2.position player.position) player.rotation Quaternion.Slerp(player.rotation, rotation2, turnSpeed Time.deltaTime) float distance2 Vector3.Distance(player.position, waypoint2.position) Debug.Log (Mathf.Round(distance1)) if(distance2 lt 1) b2 false b3 true if(b3) MOVE player.position Vector3.MoveTowards(player.position, waypoint3.position, speed Time.deltaTime) ROTATE var rotation3 Quaternion.LookRotation(waypoint3.position player.position) player.rotation Quaternion.Slerp(player.rotation, rotation3, turnSpeed Time.deltaTime) float distance3 Vector3.Distance(player.position, waypoint3.position) Debug.Log (Mathf.Round(distance1)) if(distance3 lt 1) b3 false b4 true


How to block the player from moving left and right from two empty game objects? I made the game space shooter in that game my spaceship move left and right but its not stop in right and left corner. When its move to left its go out of the screen. how i stop block in the left and right screen edges. using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float speedMove 3 public float bonusTime private Rigidbody rb private float limit 3 1 for right and 1 for left. private float direction 1 You can call it as speed private float speed 0.01f private bool toLeft false private bool toRight false public GameObject shield public GUIText bonustimeText private bool counting true private float counter private Weapon addWeapons public Sprite strongShip public Sprite normalSprite public Sprite shieldSprite private SpriteRenderer sRender private Weapon weaponScript void Start () counter bonusTime rb GetComponent lt Rigidbody gt () sRender GetComponent lt SpriteRenderer gt () addWeapons GetComponentsInChildren lt Weapon gt () foreach (Weapon addWeapon in addWeapons) addWeapon.enabled false weaponScript GetComponent lt Weapon gt () weaponScript.enabled true Update is called once per frame void Update () transform.position Vector3.MoveTowards (transform.position,new Vector3 (transform.position.x direction, transform.position.y, transform.position.z), speed) if (Input.GetMouseButtonDown (0)) direction 1 void OnCollisionEnter2D(Collision2D coll) if (coll.gameObject.tag "StrongMode") Destroy (coll.gameObject) counting true StrongMode() Invoke ("Downgrade", bonusTime) if (coll.gameObject.tag "ShieldMode") Destroy (coll.gameObject) counting true ShieldMode() Invoke("Downgrade", bonusTime) if (coll.gameObject.tag "Life") GUIHealth gui GameObject.Find ("GUI").GetComponent lt GUIHealth gt () gui.AddHealth() SendMessage("AddHp") SoundHelper.instanceSound.PickUpSound() Destroy(coll.gameObject) if (coll.gameObject.tag "Enemy") SendMessage("Dead") void Downgrade() SoundHelper.instanceSound.BonusDownSound () counting false bonustimeText.text "" counter bonusTime sRender.sprite normalSprite weaponScript.enabled true foreach (Weapon addWeapon in addWeapons) addWeapon.enabled false weaponScript.enabled true shield.SetActive (false) void StrongMode() SoundHelper.instanceSound.BonusUpSound () sRender.sprite strongShip foreach (Weapon addWeapon in addWeapons) addWeapon.enabled true weaponScript.enabled false void ShieldMode() SoundHelper.instanceSound.BonusUpSound () sRender.sprite shieldSprite shield.SetActive (true) void OnDestroy() bonustimeText.text ""


Control Two agents separately with one script? I have two characters"agent" moving them on terrain by mouse. My script for both of them is... public Vector3 point public float mark public float mark public UI Button active character butoon select script void Update Ray mouseRay Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit mousePoint if (Input.GetMouseButtonUp(0)) if (Physics.Raycast(mouseRay, out mousePoint, 100) ) point mousePoint.point mAgent.SetDestination(mousePoint.point) mark Vector3.Distance(point , gameObject.transform.position) Here script for character buttons. Every character has it own button. public bool character1, character2 void Start() character1 true void Update() if (character1 true) character2 false if (character2 true) character1 false if (character1 fale amp amp character2 false) Later. free cam moving... public void avatar1 click() button character1 !character1 character2 false public void avatar2 click() button character2 !character2 character1 false It's possible to control both of them separately by one script by click on button to chose character ?


Why does my capsule collider fall without my object (Unity)? I've got a player with a rigidbody capsule collier (gravity enabled) and a plane with a box collider. When the player is on the plane, everything works as expected, the player can walk across the plane with no issue. However, when the player walks off the plane, I want the player to fall. However, what happens instead is that the capsule collider falls but the player just keeps walking in thin air. Why is this happening? Problem Colliders setup Code void Update () i 0.1f transform.position new Vector3(transform.position.x, transform.position.y, transform.position.z i) Sorry if I'm doing something stupid, I'm new to game development Unity, I usually program other things, not 3D games. Just expiermenting a bit to learn.


Unity UI following scene object lags or jumps I have a 3D plane with "enemies", each one has it's canvas with a health bar, that follows the enemy position. When the enemy rotates, the health bar position gets laggy and jittery (you see no fluently, like a jump) The code that I'm using is private Camera camera private RectTransform healthBarReact void Start camera GameObject.Find("Camera").GetComponent lt Camera gt () healthBarReact transform.FindChild("HealthBarImage").GetComponent lt RectTransform gt () void Update Vector3 screenPoint camera.WorldToScreenPoint(transform.parent.position) the parent is the enemy, I attached the script to the child canvas "HealthBar" healthBarReact.position screenPoint How can I fix that "lag" issue? apparently, the issue only occurs when the enemy is rotating... when it follows you in a straight line, the healthbar looks well.


Unity Mesh collider not working with capsule collider I have in my Unity3d Project a capsule that represents a character and has a Rigidbody and capsule collider as components, and in my project I also have a mesh that is my terrain imported as fbx from blender. I put a mesh collider to the terrain but the capsule goes trough the terrain as it had no colliders. Curiously, if I put a cube with a mesh or box collider, the cube does collide properly. Changing the Is Convex box in the mesh collider doesn't change anything Any ideas? EDIT This is how the editor window for both, the capsule and terrain looks like Terrain Capsule


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 to move character move on a circular surface in only one direction? Making a 2d game I want to move character on circular surface only in one direction? Script attached to child object is public GameObject ball float speed 2f Start is called before the first frame update void Start() GetComponent lt Rigidbody2D gt () Update is called once per frame void Update() Left() void Left() if(Input.GetKey(KeyCode.LeftArrow)) ball.GetComponent lt Rigidbody2D gt ().AddForce(Vector3.forward speed) transform.Rotate(Vector2.left) Note character will move on a circular surface in only one direction... Image reference


Missing references in built bundles The following is a copy of our post in Unity Forum (https forum.unity.com threads missing references in built bundles.1103689 ) Hello, We have a bundle for our scenes and another one to store our prefabs (actually we have around 10 bundles but let's keep it simple). In every scene we have unpacked prefab instances. We have no problem in playmode using the AssetDatabase but once we use built addressables some unpacked prefab instances in our scenes are broken. Sprites and or scripts are missing in a inconsistent way in some scenes those objects are fine and sometime they are not. This comes along multiple warning messages quot The referenced script (Unknown) on this Behaviour is missing! quot . Note that the issue also happens when we fully deploy our player. Unity version 20193.3.13 Addressables version 1.16.1 Solution 1 We tried to remove addressable prefabs (A,B,C in the diagram) from their bundle since we don't really have to instantiate them at runtime for now and it worked. Solution 2 We also tried to put scenes and prefabs into the same bundle and it worked too. Solution 3 Switch to 1.18.2 and 1.15.1 version of addressable package and it didn't work. Solution 4 Finally we tried to use the Duplicate Bundles Dependencies analyzer multiple times in order to have no more issues of this type and it didn't work. Questions 1 As far as we understand, when addressable groups are built, Unity computes all dependencies and build them inside the bundle along the orignal assets (in my diagram quot Scenes quot bundles is packed with D'). What we don't understand is why having our prefabs in a separated bundle break references link in the scenes. Our guess is that Unity doesn't know which version of those dependencies to use (the one in the scene bundle or the one in the prefab bundle) and somehow fails to load them properly. Question 2 Is splitting our content is a good approach, we did it mostly for visibility but it appears to be more a problem in the long term, what are your guidelines regarding this matter ? Question 3 Why Duplicate Bundle Dependency rule has to be processed multiple times to properly fix every issue ? We think that running this rule creates duplication issues itself but we can't really tell.. Thanks.


Control convention for circular movement? I'm currently doing a kind of training project in Unity (still a beginner). It's supposed to be somewhat like Breakout, but instead of just going left and right I want the paddle to circle around the center point. This is all fine and dandy, but the problem I have is how do you control this with a keyboard or gamepad? For touch and mouse control I could work around the problem by letting the paddle follow the cursor finger, but with the other control methods I'm a bit stumped. With a keyboard for example, I could either make it so that the Left arrow always moves the paddle clockwise (it starts at the bottom of the circle), or I could link it to the actual direction meaning that if the paddle is at the bottom, it goes left and up along the circle or, if it's in the upper hemisphere, it moves left and down, both times toward the outer left point of the circle. Both feel kind of weird. With the first one, it can be counter intuitive to press Left to move the paddle right when it's in the upper area, while in the second method you'd need to constantly switch buttons to keep moving. So, long story short is there any kind of existing standard, convention or accepted example for this type of movement and the corresponding controls? I didn't really know what to google for (control conventions for circular movement was one of the searches I tried, but it didn't give me much), and I also didn't really find anything about this on here. If there is a Question that I simply didn't see, please excuse the duplicate.


Positions are the same but appear in different locations I have a procedurally generated tile that is a part of a turn based hex tile game. When I try to have the tile instantiate a prefab that is the placeholder for a unit, I used the tile's transform.position as the position part of GameObject.Instantiate(Object, Location, Rotation). Unfortunately, this is the result A similar thing happens no matter which tile I use. More information I tried placing a cube on where the hex is, supposedly. Its transform is very different. So what it appears to be is that the tile is being placed in the wrong place, not the cube. Further experimentation shows that the cube is appearing at exactly half the hex's apparent transform (I added a multiplier of 2 to the cube's position and it appeared in the right spot). I still have no idea why.


Unity how to position items into a Scroll View? I'm trying to add items (prefab) into a Scroll View but either if I simply add items without set positions and trying to setting position it not work. Case 1 without setting position Result All items overlapping Case 2 forcing positions (like commented row code below) Result Items not overlapped but X position take the same value (that not is 0) for (int i 0 i lt rows.Length i ) GameObject newObj Instantiate(MyRowPrefab) newObj.transform.SetParent(ScrollViewObject.transform, false) newObj.transform.localPosition new Vector3(0, ( 1 ((i rowHeight))), 0) If i decomment this line, X isn't set to zero... why ?


How to create a 3D grid in Unity3D? What is a easy way to generate a 3D "hollow" and square grid around a central point, more like a cube (that can vary in size), with each cell being evenly spaced (based on a value)? Note I know how to make a 2D grid but not a 3D one. Edit I'll try to explain it more I'm looking for a way to create a grid at every face of a cube (6 faces) at runtime, that lets suppose is 3x3x3m, and each cell being every 1 meter apart from each other. Something like that


Rearranging projects in Git and Unity I'm attempting to rearrange a Unity project that is under source control. Two problems In order to maintain the relationships between assets, I need to use Unity's API or interface. But when I move something that way, git loses track of them. In order to maintain git tracking, I need to use git commands. But when I move them that way, Unity loses track of how they're related. Is there an easy way for me to tell one what the other is doing?


Changing alpha of single pixel value? I'm trying to change the alpha values of a grayscale texture based on some conditions. Essentially if the color value is within some min and max threshold, set the alpha to 0.8, and if it is not within the thresholds, set it to 0 (unable to see) alpha. Here's my code so far Texture2D UpdateThresholdTexture(Texture2D tex) Texture2D texture new Texture2D(tex.width, tex.height) for (int y 0 y lt texture.height y ) for (int x 0 x lt texture.width x ) Color color tex.GetPixel(x, y) bool min color.grayscale gt minThresh bool max color.grayscale lt maxThresh if (min amp amp max) color.a 0.8f texture.SetPixel(x, y, color) else color.a 0f texture.SetPixel(x, y, color) texture.Apply() return texture At the moment it's just returning the original texture. Could someone point me in the right direction?


Initiated a animation in unity via use of an animator component I've written a coroutine that starts an animation. GameObject.FindWithTag(names number ).GetComponent lt Animator gt ().StartPlayback() This is the line of code that I wrote to start the animation. However, the animation does not start. I've even replaced the GameObject.FindWithTag(String) method with a reference to the actual object by declaring a GameObject in the script and setting it to a particular object in Unity's IDE. The animation still didn't start. Also, I must say the GameObject does have an animator component, you can see it in the inspector panel. No error messages can be seen in the console during play mode. What can I do to get the animation to play when I want it to play.


Is there a standard way to rig a humanoid? I am using some placeholder humanoid models for my game, which will be replaced later. I am concerned that when I replace them, they will not work with my animations, due to different rigging. Is there a standard rigging that artists use for humanoids? Such as, is there always a the same number of body parts attached in the same hierarchy, or does this vary based on the artist studio? If there is a standard, what is it? If there isn't how can I ensure that my animations and models play nice? I use Unity, if it's relevant. Disclaimer I am not an artist, and I have no idea what I am talking about. Please feel free to ask for clarification.


Implementing an enum from an abstract class Both my Player class and Enemy class should have an enum called State. (The values inside of that enum would be different in each class.) I'd like to have the Player class and Enemy class inherit from an abstract base class that would require those two classes to have that enum. Is this possible?


Can animation parameters only be changed in scripts? I have a very simple animation parameter in the Animator, a boolean that is "true" when a shooting animation is playing (to stop the game logic from allowing more shooting during a gun recoil animation). I assumed I'd be able to access this in animations, i.e. setting it to true when a shooting animation started, and false when it ended. But I just can't see how to access it in my animations. It's not available under "Add Curve". Am I missing something? I can do this in other ways, but this just seemed like the cleanest.


How do I do 2D z index parallax in Unity3d? I am new to unity3d and want to develop a simple game like crazy cabie. I have to implement a z index parallax for moving sprites towards the player and generating new sprite at the farthest z index. How can I do this?


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


How to reset the score to 0 when reloading the game? My scoring system uses DontDestroyOnLoad to persist between scenes public class ScoringSystem MonoBehaviour private int score 0 public void Correct(int number) If correct add score score score number void Start () score 0 void Awake() DontDestroyOnLoad(transform.gameObject) public int GetScore() return score Here is another script that I should include a description about public void iniTag() jawab true Time.timeScale 0 GameObject objek1 GameObject.FindGameObjectWithTag("Benar1") GameObject objek2 GameObject.FindGameObjectWithTag("Benar2") GameObject objek3 GameObject.FindGameObjectWithTag("Benar3") GameObject objek4 GameObject.FindGameObjectWithTag("Benar4") if (objek1.transform.parent.tag "Jawab4" amp amp objek2.transform.parent.tag "Jawab3" amp amp objek3.transform.parent.tag "Jawab2" amp amp objek4.transform.parent.tag "Jawab1") PanelBenar.SetActive(true) buttonNext.SetActive(true) GameObject.Find("QuizManager").SendMessage("Correct", playerScore) void Start () if (GameObject.Find ("QuizManager") ! null) ScoringSystem scoringSystem GameObject.Find ("QuizManager").GetComponent lt ScoringSystem gt () gameObject.GetComponent lt Text gt ().text scoringSystem.GetScore().ToString () else Debug.Log("No Scoring system found. To test scoring system start from the front page scene")


How can I make the objects to move at the same speed as the lines? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) Vector3 endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, counter 500f speed) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) The lines are LineRenderer. void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.tag "FrameLine" myLine.name "FrameLine" myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () myLine.GetComponent lt EndHolder gt ().EndVector end LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace false lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, start) So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed. Now I want to move the instancesToMove (GameObject ) with the same speed as the lines but the instancesToMove are moving much slower then the lines. I tried instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed) Then instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed Time.deltaTime) But it's never moving with the same lines speed.


Cannot click UI button in Unity I am working on Unity 5.4. I have an Event System, my UI has a parent canvas, Canvas has the graphic raycaster. I am not able to understand why this is not working. I have attached an image of the button script, Canvas, event system and my script. using UnityEngine using System.Collections using UnityEngine.UI public class Level01Controller MonoBehaviour private int highScore void Update () if (Input.GetKey (KeyCode.Escape)) Application.Quit () Debug.Log ("Clicked) public void StartGame() Application.LoadLevel ("Level01 Game")


How can I instantiate objects with gaps between all objects? When instantiate each a new object I want it to be with the same gaps from also the other instantiated objects. using System.Collections using System.Collections.Generic using UnityEngine public class GenerateStairsUnits MonoBehaviour Header("Stairs Units Prefab") public GameObject stairsUnitsPrefab Space(5) Header("Settings") Range(1, 20) public int numberOfUnits 1 public static GameObject Unit public int gap 10 private int oldNumberOfUnits 0 private List lt GameObject gt units new List lt GameObject gt () private GameObject unitsParent Use this for initialization void Start () oldNumberOfUnits numberOfUnits unitsParent GameObject.Find("Stairs Units") for (int i 0 i lt numberOfUnits i ) Unit Instantiate(stairsUnitsPrefab, unitsParent.transform) Unit.name "Stairs " i.ToString() Unit.transform.localPosition new Vector3(gap, 0, gap) units.Add(Unit) Unit.AddComponent lt MoveObjects gt () private void Update() if (numberOfUnits lt oldNumberOfUnits) Destroy(units units.Count 1 ) units.RemoveAt(units.Count 1) oldNumberOfUnits numberOfUnits else for (int i oldNumberOfUnits i lt numberOfUnits i ) Unit Instantiate(stairsUnitsPrefab, unitsParent.transform) Unit.name "Stairs " i.ToString() Unit.transform.localPosition new Vector3(gap, 0, gap) units.Add(Unit) Unit.AddComponent lt MoveObjects gt () oldNumberOfUnits numberOfUnits I tried in both places to add a localPosition with gap s Unit.transform.localPosition new Vector3(gap, 0, gap) But they are still all at same position.


How can I update my materials to work with LWRP? I'm using Unity 2019.1.6f1. When I open a new scene with the LWRP template project, I see errors from all materials in the scene. For example, the Jigsaw appears in my scene but in console window I see a message telling me Jigsaw Mat material was not upgraded. There's no upgrader to convert Lightweight Render Pipeline Lit shader to selected pipeline UnityEditor.Rendering.LWRP.LightweightRenderPipelineMaterialUpgrader UpgradeProjectMaterials() All materials show this message, and I don't know what to do to fix these materials. How can I resolve this error?


Unity getting Input from UI So I'm trying to get a script of mine to pass information to another static class being used for saving files as I've been told I wouldn't want that script to be instantiated. So I used a separate script to get input field text. However, I seem to be encountering a problem whenever I want to save the file. I keep getting the error "Object reference not set to an instance of the object", I have made done this though. (See code below) The class to get the name of the file public class SaveInputField MonoBehaviour public static string saveName public GameObject inputField public void getFileName(string saveName) saveName inputField.GetComponent lt Text gt ().text Debug.Log("Save file name " saveName) SaveFile.saveName saveName called whenever its been edited The static class public static class SaveFile public static string saveName public static void SaveData(Deck deck) BinaryFormatter formatter new BinaryFormatter() string path Application.persistentDataPath " " saveName ".dd" FileStream stream new FileStream(path, FileMode.Create) Debug.Log("Stream Opened") DeckData data new DeckData(deck) formatter.Serialize(stream, data) stream.Close() Debug.Log("Stream Closed")


How to unpack game data files encrypted with AES key? In game development pak files are secured by some encryption and one of these are AES key. I want to know that for security purpose is the AES key is stored in the game files itself? I know that computer cannot store the AES key in his mind so it need some clues or files to extract these Ppak files, so where does these AES keys gets stored in a game file itself?


How do you manage versioning across platforms in Unity? I'm just beginning to look into versioning games in Unity and noticed that Unity seems to offer different things depending on the platform you are building for. For instance, Android and iOS seem to have their own individual properties for versioning while Desktop has no versioning functionality at all out of the box. Since I'm working on a game that has builds for PC, Mac, Android, and iOS, I need to determine how we want to manage version numbers within our game without having to manually manage individual version for each platform. How do you solve this?


How do I create the terrain mentioned in GPU Gems 3 So, i want to create this style of terrain Nvidia GPU Gems 3 Chapter 1 However, as much as I scour the web trying to find ways to implement this inside Unity, I can't find it. My current understanding of 3d noise is that it is just an array of 2d noise that uses a range of 1 to 1 to determine density values (if there should be ground or air at a point in space (x,y,z), and 2d noise is just a heightmap of where you want the terrain to go. I currently have generated simplex noise in unity that I think works (it seems to go through 1 to 1 when i call the coherentNoise() function) I would love some review on it however pastebin.com SiX2C31t (currently, I haven't implemented the marching squares algorithm either, would love some tips on that as well). I've been looking at several forum questions and Unity answers, but never found anything. All I want to do is create fascinating ridges and overhangs for an underwater terrain, and I also preferably would like to know how to do it with a lower LOD, (I want it to be low poly). Thanks.


Unity5x GetComponent().Play("sequence".StopAll) not working I'm working with Unity3D 5x using C . I've attached collision detection to the character controller script that plays a "gothit" animation clip (using legacy animations). Here are the code snippets, the first is for the collision void OnTriggerEnter (Collider other) if(other.gameObject.CompareTag ("dmgEnvironment") other.gameObject.CompareTag ("dmgPlayerHit")) GetComponent lt Animation gt ().Play("gothit", PlayMode.StopAll) GetComponent lt Animation gt ().wrapMode WrapMode.Once print("hit damage") The attack animation call public void AnimatePunch() DidAttack () play animation if (canHit amp amp lastAttackTime lt lastAttackButtonTime attackTimeout) SendMessage("DidAttack", SendMessageOptions.DontRequireReceiver) GetComponent lt Animation gt ().Play("punch", PlayMode.StopAll) GetComponent lt Animation gt ().wrapMode WrapMode.Once The problem I'm running into is that the "gothit" sequence won't play on collision but will do so when wired to the AnimatePunch(). I'm not sure why this is happening. Any help is greatly appreciated.


How to play a sound for a Game Jam Menu Template button in Unity I'm using the "Game Jam Menu Template" plugin from the asset store in a project of mine and I'm having a bit of a problem with it. See, I'd like it so that a particular button in the menu plays a sound before transitioning to the next scene. I've tried a number of ways to accomplish this so far, but none seem to be working. I initially tried attaching the AudioSource.Play method to the On Click () events for my button, but that didn't work. It seems that the StartOptions.StartButtonClicked method is interfering with the AudioSource's ability to play for some reason (that method is used to transition to the next scene in this plugin). So, I tried patching that function itself, by both running this.gameObject.GetComponent lt AudioSource gt .Play() at the beginning of it, as well as finding the object I wanted by tag and then attempting to play its AudioSource. However, both of these attempts at forcing the sound to play were unsuccessful as well and I'm kind of at a loss as to what to do now. Is there a way for a button that transitions to the next scene via StartOptions.StartButtonClicked to play an AudioSource before doing so in this "Game Jam Menu Template" plugin?


Redistributing sprites in procedural generation according to player movement I am making space arcade with procedurally generated background consisted of nebulas and stars sprites, which spawn on Awake() in certain borders around player. Mobile phones have limited capacity so I want to redistribute sprites along the player's movement. E.G. if player reaches an empty area where is no sprites, I want sprites which farthest relatively to player to move in front of player. So player couldn't ever see an empty area. Notice that player can move in any direction in 2D space, not only up.


Unity editor PropertyDrawer custom button I has a PropertyDrawer, everything goes fine, except one feature I can't figure out how to add button and I use checkbox instead using UnityEngine using UnityEditor using System.Collections CustomPropertyDrawer (typeof (InteractiveObject)) class InteractiveObjectPropertyDrawer PropertyDrawer public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) EditorGUI.BeginProperty (position, label, property) position EditorGUI.PrefixLabel (position, GUIUtility.GetControlID (FocusType.Passive), label) var indent EditorGUI.indentLevel EditorGUI.indentLevel 0 Rect colorRect new Rect (position.x, position.y, 40, position.height) Rect unitRect new Rect (position.x 50, position.y, 90, position.height) Rect nameRect new Rect (position.x 150, position.y, position.width 150, position.height) EditorGUI.BeginChangeCheck() EditorGUI.PropertyField (colorRect, property.FindPropertyRelative ("show"), GUIContent.none) if (EditorGUI.EndChangeCheck() ) RenderSettings.skybox.SetColor(" highlight", property.FindPropertyRelative ("id").colorValue) EditorGUI.PropertyField (unitRect, property.FindPropertyRelative ("name"), GUIContent.none) EditorGUI.PropertyField (nameRect, property.FindPropertyRelative ("name"), GUIContent.none) EditorGUI.indentLevel indent EditorGUI.EndProperty () How I can add button there?


How are game menus logically structured? I've been struggling with making a game menu system in Unity for some time now. I spent time developing a way to help myself understand how game menus are connected together. Right now, I'm calling it the Screen Menu relationship. In this relationship, Screens (e.g. Main Menu, Game Over and Inventory screens) hold access to Menus (e.g. Options Menu, Level Select menu). These Menus are accessed via MenuButtons (e.g. Options menu button via the Pause Screen). Is this a valid way of thinking about how game menus are structured? How should I be thinking about it?


How do I wait until the player has reached the gameObject to perform the interaction? If the player clicks an object to move the player sprite to the object and interact with it, how do I wait until the player has reached the gameObject to perform the interaction? I have the interaction hooked up okay, but it is executing as soon as the click occurs. I would like the order instead to be (player clicks on object) (player walks to object) (once player is close enough to object the interaction occurs). But if the player moves away before reaching the object then the interaction is cancelled. I'm not sure if I should use the object's onTrigger? But my question is if I use onTriggerEnter for the gameObject, and then the player cancels the interaction before reaching it, how do I cancel the ontrigger? Is there a better way? Also, I cannot always use an onTriggerEnter because sometimes it is clicking on an empty tile and I want to wait until the player has reached the tile. Thanks!


Unity 5.3 with C Toggle Sound On Off I'm working with Unity 5.3 with C as code editor These are what I have I have 2 scenes in my project home and options. I have bg object on both scenes. Both bg objects have Audio Source component, which contains same background music that play on awake. I don't use any codes for these background musics, I only click the Add Component button from Unity and add Audio Source. This is what I want Options scene can toggle the background music on off for all scenes. Therefore, there are btnOn and btnOff in Options scene. This is my code in Audio Manager.cs using UnityEngine using UnityEngine.UI using System.Collections public class AudioManager MonoBehaviour public Button btnOn public Button btnOff Use this for initialization void Start () btnOn GetComponent lt Button gt () btnOff GetComponent lt Button gt () btnOn.onClick.AddListener(() gt PlayAudio()) btnOff.onClick.AddListener(() gt StopAudio()) void PlayAudio() AudioSource.volume 0.5f void StopAudio() AudioSource.volume 0f This is the problem I have this error An object reference is required to access non static member UnityEngine.AudioSource.volume. Maybe, this is because I don't write public AudioSource audioSource in my code. But, if I write this, I have to add another audio in Get Component box, and I will have double Audio Source in one scene. What should I do? Thanks


Unity 5 Closing Menu On Multiple GameObjects When A New Menu is Opened? I am trying to make a menu system for each GameObject, and when a GameObject is clicked it will close all other menus and open the one for that GameObject. I am using one script for this using UnityEngine using System.Collections public class BlockMenus MonoBehaviour Vector3 point public Transform block public GameObject activeBlock bool buttonActive false bool activeBlockActive false string hitObject "" void Update() point Camera.main.WorldToScreenPoint(block.position) void OnMouseDown() hitObject this.gameObject.transform.tag buttonActive !buttonActive activeBlockActive !activeBlockActive activeBlock.SetActive(activeBlockActive) void OnGUI() if(buttonActive) switch(hitObject) case "mine" GUI.Box(new Rect(((point.x) (1.08f)), ((Screen.height point.y) (0.1f)), (Screen.width (0.3f)), (Screen.height (0.5f))), "") GUI.Button(new Rect(((point.x) (1.08f)), ((Screen.height point.y) (0.87f)), (Screen.width (0.05f)), (Screen.height (0.06f))), "Build Mine") break


Strange javascript error when using Kongregates API In the hopes of finding a fellow unity3d developer also aiming for the Kongregate contest.. I've implemented the Kongregate API and can see that the game receives a call with my username and presents it ingame. I'm using Application.ExternalCall( quot kongregate.stats.submit quot ,type,amount) where type is a string quot Best Score quot and amount is an int (1000 or something). This is the error I'm getting You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround. callASFunction function(a,b) if(FABrid...tion, can be used as a workaround. quot ) I'm wondering, has anyone else had this error or am I somehow doing something stupid? Thanks!


Why does a UI button that is child to a canvas not appear in game view? I am trying to place a button onto a canvas background using C script. I want the button specific to the canvas (i.e., if I move the camera to look at another canvas, I do not want the button visible). My C script is below. I have attached it to an empty game object. When I run the game, the Heirarchy panel of Unity shows that the canvas and button are created OK, and that the button is a child of the canvas. The canvas appears in game view at the right size (200 x 200). But in game view, there is no button! The button is definitely present clicking on its name the Heirarchy panel shows me a location and size in the scene view that are exactly as specified in my C script. But nothing happens when I click the region in game view where the button is supposedly present. Unity's Inspector panel shows that a "Button (Script)" has been attached to my button object, with Rect Transform parameters as specified in my C code. I tried messing with the colors, but still no button. The "On Click()" window contains nothing except the message "List is Empty". How do I make the button appear in game view? How do I make the button work (i.e., generate the Console message "button pressed")? using UnityEngine using System.Collections.Generic using UnityEngine.UI using UnityEngine.EventSystems public class TestScript MonoBehaviour private GameObject myGO private Vector2 buttonSize private Vector3 buttonPosition void Start () setup a canvas myGO new GameObject () Canvas myCanvas myGO.GetComponent lt Canvas gt () myCanvas.renderMode RenderMode.WorldSpace RectTransform parentRectTransform myGO.GetComponent lt RectTransform gt () parentRectTransform.sizeDelta new Vector2 (200, 200) set size of parent rectangle create and place the button Vector2 buttonSize new Vector2 (10, 10) Vector3 buttonPosition new Vector3 (150, 70, 1) CreateButton (myGO.transform, buttonPosition, buttonSize) end Start() public void CreateButton(Transform panel ,Vector3 position, Vector2 size) GameObject button new GameObject() button.name "Button" button.transform.parent panel button.AddComponent lt RectTransform gt () button.AddComponent lt Button gt ().onClick.AddListener (handleButton) button.transform.position position void handleButton() Debug.Log("Button pressed!") end class TestScript


Unity Collaborate Error "It looks like you don't have any data yet" On the Unity Developer page, my partner has added me to his team. I can see his project. I clicked Go to Collaborate That brings me to the "Assets" tab, saying "It looks like you don't have any data yet." Clicking on the provided link just brings me back to the main page, where no detailed instructions can be found. Has anyone successfully used the new "Unity Collaborate" feature yet?


Move car at same speed I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that. Here is game play area on which I was moving car At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation. Here is my source code that I was using to move car void Start () direction new Vector2 (Random.Range ( 1f, 1f), Random.Range ( 1f, 1f)) void FixedUpdate () float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg float targetRot Mathf.LerpAngle (myRigidbody.rotation, (angle 90f), 0.1f) myRigidbody.MoveRotation (targetRot) myRigidbody.velocity direction speed myRigidbody.MovePosition (myRigidbody.position direction Time.deltaTime speed) Debug.Log("vel mag " myRigidbody.velocity.magnitude) void OnCollisionEnter2D (Collision2D other) ContactPoint2D contact contact other.contacts 0 direction 2 (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) Vector3.Normalize(contact.normal) direction Following formula v' 2 (v . n) n v direction 1 Dont know why I had to multiply by 1 but it's inversed otherwisae Vector2 reflectedVelocity Vector2.Reflect(direction, contact.normal) direction reflectedVelocity At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.


Unity3D Problems drawing on duplicated texture I'm trying to load texture from assets folder create a clone of said texture that will be manipulated during runtime set pixels on cloned texture I have successfully set pixels on the original texture (ie. discarding the code in the start function), but I cannot seem to be able to draw to the duplicated version. void Start () canvas gameObject.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer Sprite oldSprite canvas.sprite Texture2D oldTex oldSprite.texture Rect oldRect oldSprite.textureRect tex new Texture2D(oldTex.width, oldTex.height, TextureFormat.RGB24, false) tex.SetPixels32(oldTex.GetPixels32()) tex.Apply() Rect r new Rect(oldRect.x, oldRect.y, oldRect.width, oldRect.height) Vector2 pivot new Vector2(oldSprite.pivot.x, oldSprite.pivot.y) float pixelsPerUnit oldSprite.pixelsPerUnit Sprite sprite Sprite.Create(tex, r, pivot, pixelsPerUnit, 0, SpriteMeshType.FullRect) canvas.sprite sprite public void draw(Tool tool, Color32 color, List lt Vector2 gt locations) Color32 pixels tex.GetPixels32(0) for(int i 0 i lt pixels.Length i) pixels i color tex.SetPixels32(pixels) tex.Apply() Please ignore the unused vars, I'm just trying to set the whole texture's color for now. Anyways, any help is always appreciated thanks )


Why is the IntelliSense not working when I open a new script in Visual Studio? The strange thing is that opened scripts or newly opened ones are working fine. It's the new created C scripts that are not working. With not working, I mean the MonoBehaviour is not in light blue color it's in black color. In this screenshot I took, I marked it with a red circle. What have I tried so far? I have closed Visual Studio and started over again. Since it didn't solve it, I closed the unity editor and started it over again, to no avail. I pressed 'clean solution', I pressed 'rebuild solution', I pressed 'build solution'. What else can I do ? And why are the other scripts working fine? If I type gameo...it will auto complete it to GameObject but in this specific script it's just not working. This is a screenshot of the editor. I have in the Hierarchy a Ladder object. In the Assets I created a folder name Ladder and a script name Ladder. But this Ladder script is not working. This is the Ladder script and this script was working before but once I created another script inside the ladder folder name Raise empty script the Raise script didn't work and now the Ladder is not working either. But other scripts are working fine. using System.Collections using System.Collections.Generic using UnityEngine public class Ladder MonoBehaviour public Transform charcontroller private bool inside false private float heightFactor 3.2f private void OnTriggerEnter(Collider other) inside true private void OnTriggerExit(Collider other) inside false private void Update() if (inside true amp amp Input.GetKey("w")) charcontroller.transform.position Vector3.up heightFactor


Problem with draw distance in Unity editor 3D view The Unity editor scene renderer is not letting me get a close up view of anything. As the camera moves closer, the geometry closest to the camera just disappears. It's as if the draw distance has become far sighted. In the example above, the geometry of the green object (a car mesh) is being cut off as I pull the camera in. The floor is also disappearing, as shown by the grey cut off at the bottom. This is making is extremely difficult to line up colliders with render meshes, position smaller objects, and do other detailed tasks. I don't remember my Unity doing this before about a month ago, but I have no idea what changed. Is there a setting somewhere? Has anyone else seen this?


How do I use virtual joysticks in Unity2d ()top view? I want to use virtual joysticks for character movement, in a top down 2D game, that includes rotating the character. I tried an Easy Joystick Unity Package, but it doesn't work properly, so what do I do? Does anyone have a script (preferably in C ) that would use virtual joysticks to move a character?


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


OnTriggerExit2D called multiple times when two triggers touch I have two GameObjects tagged "Point", each with a Collider 2D set to Is Trigger. I have another GameObject, "pencil", which also has a Collider2D set to Is Trigger I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point. My problem is that when the pencil hits a point, it calls OnTriggerExit2D multiple times. How can I only detect first contact with the point? Pencil script private void OnTriggerExit2D(Collider2D collision) if (!collision.isTrigger) if (collision.gameObject.tag "Point") writing !writing


unity emission map bleeds (bug?) I have a material with a spritesheet texture (albedo) and an emission map. The spritesheet has 32x32 squares. The emission has a 32x32 square that is an emission for the magma looking square. It works well on the magma, however, the glow also spreads to the sand, grass, planks, and snow grass textures. You can clearly see it spread on the sand (bottom rightmost opaque texture) in the right because it isn't directly touching the magma. Here is another picture where it is attached You can still see the spreading of glow if you look closely. Now, you can definitely see it glow here How do you stop that from happening? That artifact is really weird and i really need it to go away. I've tried decreasing the size of the square in the emission map but it still was there. Please help. Thanks. EDIT 1 Here is how I apply uv public static Dictionary textureMap new Dictionary() public static void Initialize(string texturePath, Texture texture) Sprite sprites Resources.LoadAll lt Sprite gt (texturePath) foreach (Sprite s in sprites) Vector2 uvs new Vector2 4 uvs 0 new Vector2(s.rect.xMin texture.width, s.rect.yMin texture.height) uvs 1 new Vector2(s.rect.xMax texture.width, s.rect.yMin texture.height) uvs 2 new Vector2(s.rect.xMin texture.width, s.rect.yMax texture.height) uvs 3 new Vector2(s.rect.xMax texture.width, s.rect.yMax texture.height) Debug.Log(s.name) if (!textureMap.ContainsKey(s.name)) textureMap.Add(s.name, uvs) public static bool AddTextures (Block block, Direction direction, int index, Vector2 uvs) string key FastGetKey(block, direction) Vector2 text if (textureMap.TryGetValue(key, out text)) Debug.Log(key) uvs index text 0 uvs index 1 text 1 uvs index 2 text 2 uvs index 3 text 3 return true text textureMap "Default" uvs index text 0 uvs index 1 text 1 uvs index 2 text 2 uvs index 3 text 3 return false Where Direction is a direction (example north) and Block is a short. Index is the vertex index of the mesh. Texture is the sprite texture (.png)


Pointers in C Unity Hey I've just learned about pointers recently and am wondering how I can use them in c (I just learned about them in c ) in unity. I do have some questions though. Pointers use low level programming to find positions of different values on the computer so does that mean that you can just access a the value of a variable from any script? If so how do I just call upon a location of a variable with just its location code? Are there any discernible differences between pointers in C and C that I should know? How can I use pointers with the variable types in Unity (Vector3s, Transforms, GameObjects, etc...)? There are so many more questions I probably should and would like to ask so if you have any additional info or sources.


How can I create an outline shader for a plane? All these toon shaders I have been seeing render an duplicated mesh behind it and extrude the normals of the vectors to make it look like it has a border, but it feels a bit hacky to me. Basically I am trying to create an outline shader for a plane so these toon shaders do not really work. It's probably due to my lack of deep knowledge about shaders in particular but I am really confused and would like someone to explain. I'm also a bit worried that rendering an object twice would hit the performance. Edit Added picture for reference. (Thanks for the edit Alexandre!)


Why is my Unity camera chasing player script running slow? I have a camera class, that is suppose to chase my player, which works, but its really really slow. It only has this line of code, which makes sense to me, player moves, camera moves. Any idea of why my game runs slower. void Update() transform.position new Vector3(player.transform.position.x, player.transform.position.y, 10)


Objects with custom shaders cast grayscale shadows when lightmapped Unity 5 seems to be able to calculate colored shadows from objects mapped with standart shader and legacy shaders. What should I do to make my custom shader to cast colored shadows as well?


Reading XML working in my computer but not in my Android phone Following code works perfect in my computer but when I try to run it in my Android Phone, it does not work. string path "Assets Layout XML file" select.ToString() ".xml" XmlSerializer xmlSerializer new XmlSerializer(typeof(List lt Name gt )) StreamReader sr new StreamReader(path) List lt Name gt listnames (List lt Name gt )xmlSerializer.Deserialize(sr) How can I make the code work in my Android Phone? PS It is C , Unity.


How to implement the swipe up and down number select Unity3d I want to implement the UI like in the image. I want the users to select the number by swiping up and down. I found the tutorial on the YouTube which is similar to the what i wanted (https www.youtube.com watch?v mL FLsV3WRs) But it shows only the numbers from 0 to 9. I want to show from 1 to N (n can be any number). Any idea to help me to get this would be great.


Unity how to have a ghost 3d game object I want to have a 3d game object (player) who converts to ghost. That means that the user must not collide with other players, but must not pass walls, trees, and must take care about terrain height levels (I mean, I can't put it as kinematic and remove the collider because the Vector3.MoveTowards which moves the player will ignore the height dimension and will pass the mountains, etc) My was thinking about tagging the players and in some way try to skip the collider between them. Any idea? Thanks


Ienumerator is not working as expected So I'm trying to get my miner drone to mine from the resource by using an Ienumerator but the miner either leaves with more than the capacity or it leaves and it has taken more than the amount of resources available. So in short, the miner is to head to the resource, when its within the trigger, it needs to take the minerAmount over the miningSpeed amount of time. Please help. private void OnTriggerStay(Collider other) MinableResource mr if (other.CompareTag("Resource")) Debug.Log("Within Range of Resource") mr other.GetComponent lt MinableResource gt () if (minerCurrentCapacity lt minerMaxCapacity) StartCoroutine(MineResource(other)) else if (minerCurrentCapacity gt minerMaxCapacity) minerFull true Move(storagePos) IEnumerator MineResource(Collider other) if (minerFull) yield break yield return new WaitForSeconds(miningSpeed) Mining( other) private void Mining(Collider other) Debug.Log("Mining") MinableResource mr mr other.GetComponent lt MinableResource gt () minerCurrentCapacity miningAmount mr.resources miningAmount


How do I change a Unity 4.6 Sprite's textureRect at runtime? I'm using Unity 4.6, and I've made a sprite like this AtlasFrameData frame testAtlas.GetFrameByIndex(0) Rect spriteRect new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y) Sprite theSprite Sprite.Create( testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0)) The texture is an atlas, and I have a bunch of data read in from an XML file telling me where the frames are. I want to do this in Update() AtlasFrameData frame testAtlas.GetFrameByIndex( currentFrame) Rect spriteRect new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y) theSprite.textureRect spriteRect But I'm unable to do this since .textureRect is readonly. I could create a new Sprite each frame, but I suspect this is not going to perform well with tons of Sprites.


How can I programmatically add a Controller to an Animator during runtime? I am trying to set the Controller of an Animator during runtime using a script. When I click on the dot in the inspector manually, I can choose one called quot Standard Walk quot , but have not found a way to automate it.


Predicting the route a rigid body will take when force is applied I'm learning 3D game development with some kind of mini golf game. It is working well so far I have a sphere, and I am using AddForce on its RigidBody to launch it in the desired direction. One feature I'd like to add is to show a preview line that predicts the trajectory of the ball. Like telling the player that if he uses this direction and this force, the ball is going to follow this route, collide here, bounce, and end up there etc. I know how to use a line renderer alright, but I don't know how to calculate the array of points from which to draw the line. It has to be updated in realtime, and the player can quickly change the potential direction and force at any time it has to consider that there are various objects with different bounciness friction etc. That seems like a lot of work. The only thing that occurs to me is to use dummy invisible balls that will be constantly firing using the potential direction force and then recording their route, but I'd need to figure out some way to make them 'move faster' so I can get the array of points instantly. What would be my best approach for this?


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


Angle object only in the X axis I'm trying to code a turret to angle towards a target, where I have one part of the turret only rotating on the left right, and I want to animate another part to only angle up down. I've got the left right (RotateTowardsTarget) working, but I can't get the up down (AngleTowardsTarget) to work, it seems to also rotate the object as well as angle it. turretXRotation is a child of turretYRotation. These objects form the top of a gun turret, so the base will rotate, and the gun barrel will angle towards the target lt summary gt Orient the turret weapon towards the target. lt summary gt lt param name "lookPosition" gt lt param gt private void OrientWeaponsTowards(Vector3 lookPosition) RotateTowardsTarget(lookPosition) AngleTowardsTarget(lookPosition) lt summary gt Rotate towards the target. lt summary gt lt param name "lookPosition" gt lt param gt private void RotateTowardsTarget(Vector3 lookPosition) Determine which direction to rotate towards Vector3 targetDirection lookPosition transform.position The step size is equal to speed times frame time. float singleStep weaponRotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards( turretYRotation.transform.forward, targetDirection, singleStep, 0.0f ) Draw a ray pointing at our target in Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3) newDirection.y 0 Calculate a rotation a step closer to the target and applies rotation to this object turretYRotation.transform.rotation Quaternion.LookRotation(newDirection) lt summary gt Angle towards the target. lt summary gt lt param name "lookPosition" gt lt param gt private void AngleTowardsTarget(Vector3 lookPosition) Determine which direction to rotate towards Vector3 targetDirection lookPosition turretXRotation.transform.position The step size is equal to speed times frame time. float singleStep weaponRotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards( turretXRotation.transform.forward, targetDirection, singleStep, 0.0f ) Draw a ray pointing at our target in Debug.DrawRay(turretXRotation.transform.position, newDirection, Color.red, 3) Calculate a rotation a step closer to the target and applies rotation to this object turretXRotation.transform.rotation Quaternion.LookRotation(newDirection) Does anyone know how I can just make the turretXRotation only change it's X value to aim towards the target? I've tried similar stuff to the rotating, by zeroing out some of the x y z coords, but I can't seem to crack it.