how to make my camera follow script work for Photon Pun2 I m currently working on the Multiplayer part for a 2D top down game. I m using Photon Pun2, to do this. My problem is, that always just the last player, who joined the game get s my camera follow script attached. I ve tried setting an if (!myPV.IsMine) return on top of the function, but it doesn t seem to work. I give you the script here, so it would be nice, if you tell me, where I have to do what, to get 2 (and more) different views of the camera using System.Collections using System.Collections.Generic using UnityEngine public class CameraFollow MonoBehaviour public Transform followTransform Update is called once per frame void FixedUpdate() this.transform.position new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z)


Unity2D How to destroy my Instantiate particle system I'm having trouble trying to destroy my Instantiated particle system, I can only destroy my gameobject using UnityEngine using System.Collections public class meteor destruction MonoBehaviour public GameObject meteor d effect public GameObject meteor explo effect public GameObject meteor explo2 effect public int pointsIncrement 1 void OnCollisionEnter2D (Collision2D col) var effect explo Instantiate(meteor explo effect, col.gameObject.transform.position, col.transform.rotation) var effect explo2 Instantiate(meteor explo2 effect, col.gameObject.transform.position, col.transform.rotation) var effect d Instantiate(meteor d effect, col.gameObject.transform.position, col.transform.rotation) Destroy (gameObject) Destroy (effect explo,3) Destroy (effect explo2,3) Destroy (effect d,3) It's generated after the meteor collide, but those 3 particle effects keeps adding inside my Hierarchy panel.


Knockback when shooting I am currently working on a shooter and I could use some help with this. I want to make my character knock back when he shoots, but also the knock back should be different when the player uses a different weapon. How can I do this?


Will my Admob Unity Plugin be Obsolete? When I got back to Google Admob Console I received this announcement "Beginning on 23 Jan 2018, Google Mobile Ads SDK versions older than 7.0.0 for Android and 7.0.0 for iOS will no longer be supported. Publishers with these older versions will not be able to serve ads in their apps(s). Please ensure that you have upgraded to the latest version of the Google Mobile Ads SDK." I am concerned about whether the Unity game I released eight months ago will continue to serve Admob ads. I think this pertains to many Unity developers. It seems that the Google Mobile Ads for Unity uses a different versioning system. Its current version is version v3.10.0. So what is the latest version of Admob Unity Plugin that will be affected by this? Will we be affected at all?


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


Unity3d simple material color display correctly in windows built but yellow color turns to blue in android build? I have a simple roll a ball game as shown in unity 3d tutorials, and I have set the wall color as a shade of yellow using the standard shader and material. This runs flawlessly in windows application, however when running in android phone( Nexus 5 MM) the wall turns into a blue color. Can anyone tell me how to fix it?


unity and maya how to export import fbx animation with rootmotion and non rootmotion clips? I've started learning about and playing around with animations in Unity and I've installed the Basic Motions Pack by Kevin Iglesias. I wanted to know how they work and to see if I can modify them so I've looked at the animation files which are .fbx. The animation hierarchy in Unity looks like this where BasicMotions Walk01 is the in place animation and RootMotion is the root motion variant which has velocity. I've looked into what root motions are and I think I've grasped what they are, but here's where things have gotten interesting. I've imported the BasicMotions Walk01.fbx into Maya and it looks like this it has a root joint for root motion and the animation moves the rig in each keyframe. So far so good! I've modified the animation so that it plays in reverse, basically made a sketchy reverse walk animation. Exported it to .fbx with the following parameters And then opened that in Unity, however when I import the animation and rig it it only has one clip and it's the Root motion clip, and I can't get the non rootmotion clip. The Root Transform Position (XZ) Loop match is always red and if I don't bake it into pose the animation functions like the Kevin's RootMotion animations, but I don't know how to get the non RootMotion clip. What am I doing wrong here?


Can the GUI be used to create game objects? I want to be able to position 10 various game objects (sprites) within the area of the screen which will be dynamically sized accordingly to the screen size of the device. The area in which I want to position the items will be about 70 of the screen. The objects will be rectangles with irregular size (slightly irregular). The object should be positioned randomly (or in grid) within this area but they should not overlap. The objects will be a drop targets for other object which I will drag onto them. To summarize I need The area in which I can place objects. Random object position er. As I have been reading and watching various tutorials I have become very confused about how should I approach this. Should I use a Rect to draw the area on which I will then place the objects, or should I use GUI UI elements i.e. panel? Are the GUI UI elements suitable for achieving this or are they meant to be only used to create games menus not for actual game play?


How can I avoid a stack overflow when recursively checking adjacent game objects? I am building a simple game on Unity to learn the system. I am using C . The game is a basic "blocks" game, whereby when the player clicks on a block, the block and its neighbours of the same colour all disappear (get destroyed). My process is this To keep a track of which blocks are neighbours of the same colour, on each refresh each block checks their details on the event OnCollisionEnter and adds these collision neighbours to a List of valid neighbouring gameobjects. When a block is clicked, this list is checked and each neighbour has its own neighbours list checked, after list checking each block is distroyed. Somehow, this process is causing a StackOverflowException StackOverflowException UnityEngine.GameObject.GetComponent setupscript () (at C buildslave unity build artifacts generated common runtime GameObjectBindings.gen.cs 35) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 86) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) .... Here is my script, first my List establishment private List lt GameObject gt neighbours new List lt GameObject gt () Next, here is how the neighbours list is populated void OnCollisionEnter (Collision other) Rigidbody other rb other.rigidbody if(rb.velocity.magnitude lt 1f amp amp other rb.velocity.magnitude lt 1f amp amp other.gameObject.tag tagName amp amp !neighbours.Contains(other.gameObject)) Same tag so add to list of valid neighbours neighbours.Add(other.gameObject) Now, there are four conditions above to check when adding to the list Is the current block stationary. Is the "other" colliding block stationary (so they're at rest next to each other). do these blocks have the same tag (so they're the same type colour) does this block not already exist in this list. So once all four conditions are met, the block GameObject is added to the List. ( On conditions of OnCollisionExit blocks are removed from the List in a similar fashion. ) Now, my CheckNeighbours() script public void checkNeighbours() if (neighbours.Count gt 0) foreach (GameObject othercube in neighbours) setupscript otherCubeScript othercube.GetComponent lt setupscript gt () otherCubeScript.checkNeighbours() Destroy (gameObject) This should, as far as I understand it, run once through each List element and check that element for any neighbours who match. As I write this question out I think I'm realising that the issue is that we're in a loop as block 1 references neighbour block 2, which references neighbour block 3, which references neighbour block 1, etc. etc. But my StackOverflow exception occurs when there are only two blocks, so one refers to the other, refers to the first, etc. But as they should destroy after running the reference, this shouldn't (ideally) be an issue? Do I need to make the checkNeighbour() a Corountine to allow it to not hold up destroying the GameObject? If this repetition cycling is indeed what's going on, what would be the best way of getting each neighbour to be checked only once? Or checking that the GameObject referenced in the List still exists in the game itself? I have a quick edit here foreach (GameObject othercube in neighbours) if (othercube ! null) setupscript otherCubeScript othercube.GetComponent lt setupscript gt () otherCubeScript.checkNeighbours() But I'm not sure this will work as I feel this List will purely be a reference rather than the actual GameObject in the level?


Unity "Text Mesh Pro UGUI" component rewrites my text! Make it stop? I'm having this terribly annoying problem where my text is being overwritten by Unity. This Happens regardless of whether I am using tags or not. Here is what I want to appear (more or less, I don't think this example is using the tag) And here is what happens when I try to include a monospace tag Since you might not see it here, the text I inputed is lt mspace 64px gt A lt mspace gt This works FINE for regular TMP objects, which the other 3 are (and are using). I am trying to implement dropdown (and left, and up, and right) menus. You can see that Unity overwrites it as "Option A", like it has a clue what I'm doing. What can I do?


Why is Unity 2D Alpha Blurring my pixel sprite? So I have just brought in a place holder block for the ground in unity 2D, and it's 16 by 16 pixel image, and for some reason unity is automatically blurring the image. So I was wondering if there was any way to stop unity from automatically blurring the image. I would really appreciate if someone could tell me how to stop the image form being blurred. Also sorry if this is, just something that is incredibly simple to fix, I just started using unity 2D instead of 3D so it's different for me. Thanks, Nova


unity 5.x performance After I downloaded unity 5, it became very power consuming. For example, my pc becomes hotter and makes a lot of noise. Also building, compiling, baking of game takes a lot of time. I am making a multiplayer game and need to build the game almost on every change, but it takes hours or sometimes it doesn't even build the game. There are also bugs with directional light, it doesn't work. So yeah, any suggestions? My internal PC specs Intel core i3 3130M, 8gb of ram, video card Intel R4000 I installed unity 5 after Windows 10 came out, maybe it's something with the OS? Also yesterday, I updated Unity but with the same problems. Also here are some screens Directional light is turned off but everything except models is dark, i mean terrain is black. Also this baking process is more than one hour and stays on 5 11 clustering 41 jobs


Method Animator.SetBool sometimes is not working (or not triggering) in Unity2D I have trouble with Animator in Unity2d. I have a main character for my game. The character has his own animation clip for fighting. When the player touches the screen, i am starting animation. When the player touches the screen slowly (every second) everything is working fine, but when the player touches the screen fast, the animation clip is playing about 10 times, and then nothing happens (the clip isn't playing). I've checked the touch event is triggered normaly, may the problem is with animator. Does anyone have ideas how to fix this issue? public bool UseAxisInput false private Animator Anim Use this for initialization void Start () Anim GetComponent lt Animator gt () Update is called once per frame void Update () for (var i 0 i lt Input.touchCount i) if (Input.GetTouch(i).phase TouchPhase.Began) Anim.SetBool("IsFighting", true) May be this is because of that at the end of my animation i have an animation event which calls the method, that stops animation. This is my method, that is called, after the animation ends public void stopFighting() Anim.SetBool("IsFighting", false)


Why every character I drag to timeline is disabled in the timeline? I dragged 3 different characters to the timeline window and each one asked for track so I did animation track for all of them but on each track on the left side there is a yellow triangle say "The component is disabled" I created cinemachine virtual camera and it added the brain component to the main camera and created a timeline automatic for the virtual camera but when dragging a character to the timeline window I'm getting this yellow triangle with the message it's disabled. You can see in the screenshot on the left side in the timeline window the yellow triangles with the message.


Inventory View Screen Looking to create an inventory screen in Unity, and trying to think of the best way to do it. My current line of thinking is having a few rows of squares for inventory items that are drag and droppable onto a paperdoll, a la Diablo. When dragging and dropping on the items, it would update a 3D model of your current playable object with the items. The menu itself would be easy enough to do with a simple square and a hierarchy of game objects for the items, each responding to mouse hovering over. The problem I am trying to figure out is being able to render the 3D model on the side. Granted, this is a nice to have, and not necessarily a need, but browsing the documentation, the only way I can think of accomplishing this is using a render to texture which requires Unity Pro with a separate camera completely out of bounds of the current space. Anyone have suggestions on how to accomplish this?


How to fix this elbow issue when converting to humanoid Good day, how can I fix this? it looks fine in Blender and generic but not when I switch to humanoid. There is no error on rig tab but there are in animation tab under the import message that say quot is in between humanoid transforms and has rotation animation that will be discarded quot and I can't seem to fix it. Here are the things I've tried so far Put the right bones to the right slots. Enforce T pose. Translation DoF. Clicked Generate Retargeting and applied it.


Backround turning, follow the character In my Unity2d platformer, I need background to follow the character, so I just attach it. And when character turn left from right (or right to left), background turn too. How can I make my background constant?


How to change animation start end proprieties via script? Is there a way of changing the start end proprieties (Transform, Rect Transform, etc..) of an animation via script? Like, I have 5 objects that start at the same position but should end in different positions, so I would like to change the end positions of each one via script. As I haven't found a way to do this, I created 5 animations for this, but I'd like to just have one animation and change its proprieties in runtime.


How to add a bolt into my unity project In my game, one of the character you pick as a special ability called the dash. It allows the player to quickly move forward. Included below is the code. It just throws up a bunch of errors. This is a 3d scene using System.Collections using System.Collections.Generic using UnityEngine public class PlayerJump MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown("q")) transform.Translate(Vector3.KeyDirection 260 Time.deltaTime, Space.World)


Converting to JSON String with JsonUtility.ToJson I am working on converting and displaying the JSON String with unity. I have done coding for it using UnityEngine using System.Collections using LitJson using SimpleJSON using System.IO public class TestDelete MonoBehaviour JsonData json void Start() Data2 data new Data2() Payload2 data2 new Payload2() data.command "state" data.payload new Payload2() text "wwwwwww", image "hello" data2.option new Option () A1 "k", A2 "J" string dataValue data data2.ToString() string json JsonUtility.ToJson(data,true) P(json " t n") Use this for initialization void P(string aText) print (aText " n") System.Serializable public class Payload2 public string text public string image public Option option System.Serializable public class Data2 public string command public Payload2 payload System.Serializable public class Option public string A1 public string A2 This code of working fine.But with the output Iam having problem.The out is displayed as follow "command" "state", "payload" "text" "wwwwwww", "image" "hello", "option" "A1" "", not getting displayed "A2" "" not getting displayed the string value A1 and A2 is not getting displayed.What will be the issue with my code.Can anybody help me sorting out this issues


How to implement the graph for pathfinding using A The game I am working on is based on a maze where each level is procedurally generated. The pathfinding grid is a 2D array where each node holds its connections. Path requests are handled one at a time so there can't be two path calculations going on simultaneously. So far I have each node hold its data required for the A (H,F,G scores and its parent) and manipulate them directly in the algorithm. Since the nodes are the actual nodes and not copies of them, every time the algorithm runs the data changes permanently and I have to manually set them on default values before the next run. So my questions are 1) Is this a valid way of handling pathfinding in a game? 2) What other data manipulation techniques I could use in order to avoid that? If you need a copy of the code it's all on my github under Pathfinding and Managers PathfindingManager.


Can both High poly model go with a low poly scene? I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.


How to remove gameobjects that have the same transform position as each other? If I have 4 copies of the same gameobject in my scene and they all have the exact same transform position as each other, how can I remove the 3 duplicates so that only one unique gameobject remains? This is what I tried so far... private void Update() if (Input.GetKeyDown(KeyCode.Space)) RemoveDuplicate(GameObject.FindGameObjectsWithTag("Path")) private void RemoveDuplicate(GameObject other) for (int i 0 i lt GameObject.FindGameObjectsWithTag("Path").Length i ) if (GameObject.FindGameObjectsWithTag("Path") i other i ) continue if (GameObject.FindGameObjectsWithTag("Path") i .transform.position other i .transform.position) Destroy(other i ) But it doesn't work at all. Any ideas?


I can't find a way to make my projectile gameobject collide with my ofscreen collider so my code on my collider is as followed public class Collide MonoBehaviour private void OnCollisionEnter2D(Collision2D collision) Debug.Log("Collision") the projectile has a rigidbody2D and a capsule Collider 2D. collider has a box collider 2D. the projectile spawns from my player and moves upwards in the direction of the collider (the collider is large enough that the projectile cant miss it). the projectile however goes straight through the collider and no message appears and I have no idea why. what I've tried and made sure of both are on the same layer and plane(z axis) gave the collider a rigidbody but changed nothing made the collider on trigger and not on trigger made the projectile dynamic and kinematic changed collider script to onCollisionEnter and onCollisionEnter2D


Minimum hardware requirements for developing for iOS and Android with Unity, Cocos2d x and GameSalad on a Mac I intend to create iOS and Android games. My main priority is to create 2D games. The software that I m planing to use are Unity, Cocos2d x and GameSalad. I am a bit interest in the Mac Mini, because it is cheap compared to other Apple machines. What are the minimum hardware requirements for an Apple machine?


I want a variable field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid? I want a field I declared (float attackRange) to be only declared when inheriting class set "bool haveLongRangeAttack" is set to true. I wanted to use Compiler Directives for this purpose. Here is the code I wrote using UnityEngine public abstract class Enemy lt T gt MonoBehaviour where T Enemy lt T gt SerializeField protected bool haveCloseRangeAttack false, haveLongRangeAttack false if haveLongRangeAttack true SerializeField protected float attackRange 1f endif SerializeField protected GameObject mainCharacter null protected GameObject enemy null protected virtual void ChasePlayer() if(haveCloseRangeAttack) ... else if(haveLongRangeAttack) ... I don't know if it is right way to of do what I want or using Compiler Directives so please review my code and tell me if there is a problem, or if there is a better way. It was before 6 months when I started writing code, and C was my first language. I am trying to learn new things concepts and writing at my own style. So there will be another way (maybe more efficient) if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me... TY for taking time . ! PS There is no compiler directives tag in Tags section. Maybe it will be useful to add this tag.


Still having problems using Json data in Unity I have the following classes and json file, i thought id followed the documentation exactly but I am clearly wrong. Can anyone see why I get an error just saying INVALID VALUE in my unity console using System.Collections using System.Collections.Generic using UnityEngine using System Serializable public class DataReader public float x public float y public float z GameController public class GameController MonoBehaviour public static GameController instance DataReader dataReader private string gameDataFileName "level1.json" private void Awake() dataReader JsonUtility.FromJson lt DataReader gt (gameDataFileName) instance this void Start () create level print("DATA " dataReader.x 0 ) and the json is stored in StreamingAssets folder (I also tried a copy in Resources folder) "x" 1 , 1 , 1 , 1 , "y" 1 , 1 , 1 , 1 , "z" 1 , 2 , 3 , 4


Canvas UI elements out of place in Unity3d I placed all elements in the places I want to show in the Game mode, nevertheless, when I go to Game Mode they are shown in the wrong place as it was shown in the pictures (they go to the center). I tried different modes of render mode but no one seems to work in this case. I want the elements to be fixed in the window no matter monitor size.


Instantiated prefabs dont trigger ontriggerEnter while prefabs created not on runtime, do I am new to unity and trying to make a bouble trouble game. I have enemy prefabs with BoxCollider with is triggered checked. I also have a shooting script. when I am trying to instantiate the enemy prefabs on runtime, they dont seem to trigger the OnTriggerEnter function, but if I am placing an Enemy prefab not ingame, it does trigger the funtion. I have no idea why. The on run time instantiate public class CreateBalls MonoBehaviour public Rigidbody prefab public Transform position1 void Awake() for (int i 0 i lt 1 i ) float random Random.Range( 45.08f, 44.41f) Vector3 vec new Vector3(random, position1.position.y, position1.position.z) Rigidbody ball Instantiate(prefab, vec, position1.rotation) as Rigidbody The funtion not being called public class DestroyBalls MonoBehaviour public Rigidbody potion public Transform posToSpawn private void OnTriggerEnter(Collider other) if (this.gameObject.tag quot Enemy quot amp amp other.gameObject.tag quot Bullet quot ) a code not relevent Any idea of why the funtion isnt being called? the bullets are tagged quot Bullet quot and the Enemies are tagged quot Enemy quot Update The funtion is triggered when colliding with another Enemy tagged, but not being trigged after collision with anyother tagged object Also, I have another component on the Enemy Prefab, which also instantiates enemies on run time and these trigger the function perfectly fine. very wierd. the code public Rigidbody ballToSpawn public Transform spawnPoint private void OnTriggerEnter(Collider other) if (this.gameObject.tag quot Enemy quot amp amp other.gameObject.tag quot Bullet quot ) if (this.gameObject.GetComponent lt Size gt ().size gt 1) Rigidbody small for (int i 0,y 1 i lt 2 i ,y 2) Vector3 vec new Vector3(spawnPoint.position.x y, spawnPoint.position.y, spawnPoint.position.z) small Instantiate(ballToSpawn, vec, spawnPoint.rotation) as Rigidbody small.gameObject.transform.localScale new Vector3(1, 1, 0) small.gameObject.GetComponent lt AutoMoveForBall gt ().GoToX this.gameObject.GetComponent lt AutoMoveForBall gt ().GoToX small.gameObject.GetComponent lt AutoMoveForBall gt ().GoToY this.gameObject.GetComponent lt AutoMoveForBall gt ().GoToY small.gameObject.GetComponent lt Size gt ().size this.gameObject.GetComponent lt Size gt ().size 1


How to know if mouse coordinates is delta or absolute on Window and Android in Unity? I wrote sample application, that allows to "rotate" object by mouse. Rotation occured by rotating of camera object around central object and the code is following float mouseX Input.GetAxis("Mouse X") float mouseY Input.GetAxis("Mouse Y") float magnitude transform.position.magnitude Vector3 mouseSwipe new Vector3(mouseX, mouseY, 0) Vector3 startPoint new Vector3((float)camera.pixelWidth 2, (float)camera.pixelHeight 2, magnitude 1) Vector3 startPointWorld camera.ScreenToViewportPoint(startPoint) Vector3 endPointWord camera.ScreenToViewportPoint(startPoint mouseSwipe) Vector3 mouseSwipeWord endPointWord startPointWorld float dragLat mouseSwipeWord.y float dragLng mouseSwipeWord.x Vector3 oldPosition transform.position magnitude float lat Mathf.Asin(oldPosition.y) float rsmall Mathf.Acos(oldPosition.y) float lng Mathf.Atan2(oldPosition.z rsmall, oldPosition.x rsmall) lat dragLat 10 2 Mathf.PI if( lat 180 Mathf.PI gt 80 ) lat 80 Mathf.PI 180 else if( lat 180 Mathf.PI lt 80) lat 80 Mathf.PI 180 lng dragLng 10 2 Mathf.PI 2 float y Mathf.Sin(lat) rsmall Mathf.Cos(lat) float x rsmall Mathf.Cos(lng) float z rsmall Mathf.Sin(lng) Vector3 newPosition new Vector3(x, y, z) newPosition magnitude transform.position newPosition LookAtTarget() The code assumes that mouse returns delta value on each swipe and this works well on Windows. For example, if I do several separate swipes, I can gradually rotate object for full circle. Unfortunately, when I run this on Android, it doesn't happen. Each swipe object restarts from some position, depending on swipe point. I.e. on Android, swipes return in absolute value. Is it possible to know, whether swipes retunrs delta or absolute values and how? Is it possible to claim compatible return units?


How can shader code duplication be reduced in Unity? In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code. On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again. How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?


Fill all unallocated space with texture I have a system of bunkers underground, and I need to fill all the free space where there are no buildings with earth. Yes, I can manually add a ground texture to the plane, but I have procedural level generation. I thought there might be some kind of filter on the camera that I don't know about. Or maybe there are some other solutions?


In Unity, why does my IndexOutOfRange exception disappear when trying to debug it? I don't get errors when playing from Unity "Game" tab. But when I build an executable (development or not) it stucks. I get "IndexOutOfRange" exception. Which also magically disappears (yes) when I add some debug lines This does not work for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i Out of range b 7 j Out of range submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j This works for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i b 7 j if (a lt 0 a gt 15) now with this never gets out of range Debug.Log("A out of range " a) if (b lt 0 b gt 15) now with this never gets out of range Debug.Log("B out of range " b) submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j I can't find any sense. The exception literally hides from me Additional info maybe is useful x1 (CurrentWalkableTile.x 7) gt 0 ? 7 (int)CurrentWalkableTile.x x2 (CurrentWalkableTile.x 7) lt world.wmap x size ? 7 (world.wmap x size (int)CurrentWalkableTile.x 1) y1 (CurrentWalkableTile.y 7) gt 0 ? 7 (int)CurrentWalkableTile.y y2 (CurrentWalkableTile.y 7) lt world.wmap y size ? 7 (world.wmap y size (int)CurrentWalkableTile.y 1) I'd like to post more information, but I can't even debug to find the problem.


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


How to output to the Oculus and a 2D screen? We'd like to present an Oculus game to a large group of people. Not everyone will have an Oculus headset, so we'd like to output to both the Oculus and a second display. The problem is that the project uses an Oculus plugin to render its output, so all they output is two distorted circles, which doesn't display well when not wearing the Oculus headset. I thought of making a second Unity client (the "audience" client, running on the same computer as the Oculus application) that receives the output texture of an "audience" camera from the client running the Oculus version. My question is Can I use the network to send the output of a camera to the "audience" client so I can set it up for the second display, bypassing the Oculus plugin? How would I get the input on the "audience" client to map it to the screen?


How can I switch between cinemachine free look cameras by script? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook freeLookCameras public float timeBeforeSwitching Start is called before the first frame update void Start() StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void Update() IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) for(int i 0 i lt freeLookCameras.Length i ) freeLookCameras i .en If I have two or more cameras I want that after X seconds start switching between all the cameras in the array by disabling enable the cameras. disable the first enable the second then disable the second enable the third and so on.


C Script file is not showing in Onclick Event in Unity 5.0.4f1? I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me? C code using UnityEngine using System.Collections public class LevelLoader MonoBehaviour Use this for initialization void Start () Update is called once per frame public void LoadLevel(int a) Application.LoadLevel(a) public void Quit() Application.Quit() Correct me where I am wrong. I am following this racing car game tutorial. At 7 58 he added this event. Please help me!!!


Unity installed version higher than game project version can't open the game project anymore Long story short I had to uninstall Unity and Unity Hub and reinstall them again. I ended up installing Unity version 2020.2.1f1. Some of my game projects were made using version 2020.1.6f1 Now I cannot open them there is a yellow warning triangle next to those games in Unity Hub. I am installing version 2020.1.17f1 as I type these. So my questions Is there no backwards compatibility between newer versions of Unity and older games? How do people deal with this? I've heard people transition their games during development into newer versions of Unity but I wasn't even able to open the games made with older version. How would I go around this if I had spent 2 years or more of development time and was suddenly locked out from my game project how do I prevent situations like these? Here are my Unity versions installed And here are my games (tutorials mostly) I may have answered my own question, but still need your input guys. I just noticed that there is a 'Select Version' dropdown on the right that allows me to open a game project in Unity version I have installed on my system. Is this how you deal with those issues?


How heavy is a scene load in Unity assuming all referenced objects are in memory? From what I understand, resources that are local to a particular scene( not a prefab, or texture, material asset etc ) are embedded in the scene file itself, while external resources are just referenced and loaded if needed. The game I'm working on requires all scene be loaded from an asset bundle. Which means by the time the level is loaded, all data should be in memory. In order to show relatively accurate load progress, I sum of the total bytes of all the needed asset bundles to load the level and divide that by the (approximate) number of bytes loaded so far( calculated using the file size of the asset bundle in bytes multiplied by Unity's AssetBundleRequest.progress value ). However, this isn't possible with Application.LoadLevel since there's no way to weigh how long it might take relative to the time it took to load the asset bundles. So, my question is, does Application.LoadLevel take long enough to be an issue if ignored? The presence of an async version of this method leads me to believe there is some need for this. That might only apply for scenes that were built into the game rather than into an asset bundle though.


Any problems with flipping a sprite by scale? (2d Platformer) I am wondering if there are any problems with flipping a sprite on the x axis using vector2 to tell which direction it is facing flip. Though doing this helps me write less code for Ray cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning.


Rotation around arbitrary vector (using quaternions?) I currently have a camera which orbits a specific target object, always looking at it. The user can drag the mouse to move the camera left right up down and the camera will move over the surface of a sphere of fixed radius (note, I clamp the vertical angle to 89 ). Currently it looks something like this... Store position of camera for future reference private Vector2 rotation new Vector2(120, 25) Was intended to be the vector from planet to target. Only works with up private rotationalPole Vector3.up if (isDragging) rotation new Vector2( Input.GetAxis( quot Mouse X quot ) xSpeed radius 0.02f, Input.GetAxis( quot Mouse Y quot ) ySpeed 0.02f) target is the GameObject to center on... var pos target.transform.position camObj.transform.position pos (Vector3.back actualRadius) camObj.transform.LookAt(pos, rotationalPole) camObj.transform.RotateAround(pos, Vector3.right, rotation.y) camObj.transform.RotateAround(pos, rotationalPole, rotation.x) This works fine when up is in the y direction. Now, however, instead of an object on the ground, the target is something in orbit around a planet (currently on an equatorial orbit but hopefully on an arbitrary one in future). I want the camera to behave the same as before, but with up being the vector from the center of the planet through the target. Nominally forward will be the direction of orbit (but since the user can spin through 360 quot horizontally quot , that's less important). Currently it looks like this... Basically, I'd like to rotate the image above counter clockwise by 90 (which I believe I can do by playing with the camera transform's up and right vectors) but also that my arbitrary rotation honors the new orientation. Some research shows that I need to use quaternions but while my mental model for basic trig is fine, I can't picture how to use quaternions correctly in this situation. Following on from Jon's answer below... I've now got the following. var planetToTarget (target.transform.position planet.transform.position).normalized quot Reset quot the camera before I do any transforms this.transform.position target.transform.position tgtMovement actualRadius this.transform.up Vector3.up this.transform.LookAt(target.transform.position) var camToTarget (transform.position target.transform.position).normalized Debug.Log(string.Format( quot targetMotion 0 , planetToTarget 1 , camToTarget 2 quot , tgtMovement, planetToTarget, camToTarget)) Line that's not working... this.transform.Rotate(camToTarget, 90) To be added in when the above is working... this.transform.Rotate(Vector3.Cross(camToTarget, planetToTarget), rotation.y) this.transform.Rotate(planetToTarget, rotation.x) this.transform.up planetToTarget The uncommented code (excluding the last line) keeps the camera behind the target, looking forward... Initially, I get targetMotion (0.0, 0.0, 1.0), planetToTarget ( 1.0, 0.0, 0.0), camToTarget (0.0, 0.0, 1.0) Which generates However, as the target moves around the planet, it changes to targetMotion (0.4, 0.0, 0.9), planetToTarget ( 0.9, 0.0, 0.4), camToTarget ( 0.4, 0.0, 0.9) By which point, the camera is slewing to the side... So I'm clearly still missing something. I don't appear to be rotating around camToTarget correctly?


Way to check overlaps of a collider2d that's not set to "is trigger" in Unity I have a system where physics2d objects are spawned and I need to know when they spawn outside of a region defined by a box collider set to quot is Trigger quot . Using onTriggerEnter and onTriggerExit to know if an object exits re enters the bounds (with some other conditions determining whether to kill the object when it exits the bounds). That stuff works fine. However I can't detect when an object spawns outside of the collider (which I want to allow, but just know when it happens). I tried the following in the Start method of the spawned object List lt Collider2D gt results new List lt Collider2D gt () boundsCollider.OverlapCollider(new ContactFilter2D(), results) bool spawned outside !results.Contains( thisCollider) However at the time that method runs, the booundsCollider doesn't register it. Subsequent frames it will, but that's too late. OverlapCollder can't be run on the collider for the spawned object since it isn't set as a trigger. Is there any way I can query the spawned object's own collider to determine if it is in contact with the bounds collider? Thanks! PS I can't trivially just reference the coords of the object and check if they're out of bounds because the bounds collider will move, and I want to know with precision wether just a corner is overlapping or whatever so I'd need something that amounts to my own simple collision system


OnCollisionEnter2D just flat out not running for certain objects I am working with the Unity3D Engine in 2D mode. Currently I am trying to make a circle collider bounce off of a composite collider for the walls of my game. The only issue is that for some reason the OnCollisionEnter2D function does not seem to even trigger when the circle collider hits the walls. I have used the log to determine this. I am curious as to why it has this behviour, since it does end up triggering when the player contacts the circle collider? Here is the important parts of the script public class sword MonoBehaviour public Rigidbody2D rb public CircleCollider2D coll public float speed public Vector2 trajectory public GameObject Player Use this for initialization void Start () speed 0.0f anim Player.GetComponent lt Animator gt () private void OnCollisionEnter2D(Collision2D collision) Debug.Log("collided") if (collision.gameObject.tag "player") transform.position new Vector2( 1000, 1000) Player.GetComponent lt movement gt ().equipped true if (collision.gameObject.tag "solid") ContactPoint2D otherObject collision.contacts 0 Vector2 hit otherObject.point Vector2 normal otherObject.normal trajectory Vector2.Reflect(trajectory, normal) private void FixedUpdate() constantly calculating new velocity rb.velocity speed trajectory speed speed 0.93f drag if (speed lt 0.0001f) speed 0.0f if (speed gt 1) Physics2D.IgnoreCollision(Player.GetComponent lt CircleCollider2D gt (), coll, true) else Physics2D.IgnoreCollision(Player.GetComponent lt CircleCollider2D gt (), coll, false) More Details My speed variable is set from a separate script, in case you are wondering. Everything is on the layer 0.. The Rigidbody for player is dynamic, for the ball it is kinematic, and for the walls it is static. Also here is an image of what the game screen would look like, I've labelled the walls and the circle collider (used for a sword). Thank you.


Restarting a level but with more time? So I'm trying to add a "Rewarded video ad" with the reward being more time to play in the next game. my RewardedAd.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.SceneManagement public class RewardedAd MonoBehaviour public static RewardedAd singleton private void Awake() if (singleton null) singleton this else if (singleton ! this) Destroy(gameObject) public void ShowRewardedAd() if (Advertisement.IsReady("rewardedVideo")) var options new ShowOptions resultCallback HandleShowResult Advertisement.Show("rewardedVideo", options) private void HandleShowResult(ShowResult result) switch (result) case ShowResult.Finished Debug.Log("The ad was successfully shown.") StartCoroutine(NewGameWithTime()) break case ShowResult.Skipped Debug.Log("The ad was skipped before reaching the end.") SceneManager.LoadScene(0) break case ShowResult.Failed Debug.LogError("The ad failed to be shown.") SceneManager.LoadScene(0) break IEnumerator NewGameWithTime() Debug.Log("NewGame Started") GameOverManager.singleton.GameOverAfterRewardAd() SceneManager.LoadScene(1) Timer.singleton.AddBonusTime(20) Debug.Log("NewGame Ended") yield return new WaitForSeconds(1) and my Timer.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement using UnityEngine.UI using System public class Timer MonoBehaviour public static Timer singleton public Text timeTF private float seconds 10f private void Awake() if (singleton null) singleton this else if (singleton ! this) Destroy(gameObject) private void Update() if (seconds gt 0f) seconds Time.deltaTime TimeSpan timeSpan TimeSpan.FromSeconds(seconds) string timeLeft string.Format(" 0 D2 ",timeSpan.Seconds) timeTF.text timeLeft TimeLeftCheck(seconds) public void AddBonusTime(float bonusTime) seconds bonusTime Debug.Log("New Timer script ") Debug.Log(seconds) private void TimeLeftCheck(float time) if ( time lt 5) Debug.Log("RunningOutTime sound") SoundManager.singleton.Sound RunningOutofTime() if ( time lt 2) Debug.Log("Out of Time sound") SoundManager.singleton.Sound OutofTime() if ( time lt 1) Debug.Log("Game Over") GameOverManager.singleton.GameOver() The video ad is playing fine and it's resetting my ad counter in my game over manager but I can't seem to figure out how to start the next game with more time (20 seconds to so) but ONLY if they've watched the ad. Also, I'm still learning so any suggestions or things I can improve, more than happy to take that criticism too!


Managing Character Bones in Unity 3D at runtime I'm trying to do the following Have a rotation only (no transforms) with x,y,z. Each rotation axis above respectfully having a minimal and maximum rotation angle with a current angle. This will be for each bone of said character's skeleton, note the weights will be applied as per usual when doing animations, however there will be no animation data. bones to rotation info, apply changes, info back to bones, apply changes, info back to bones... Q SetBones And GetBones, how would I get and set the bone data? imports... public class BoneControllerClass MonoBehaviour used to modify the bone data struct for each bone (ediable via Unity Editor) public BoneConstraintData BoneData gets refs to bone data from character public Bones GetBones() ..Help..Here.. public BoneConstraintData SetBoneConstraints(BoneConstraintData BoneData) ..CODE..HERE.. public void SetBones(BoneConstraintData BoneData) ..Help..Here.. public void Start() generate bone data with zeros BoneData GetBones() set bone data constraints BoneData SetBoneConstraints(BoneData) public void Update() do something for smooth clamping, optionally this could be applied above as with Delta Time... CODE EXAMPLE HERE, optionally another function can be added... BoneData 0 .currentXAngle 12.0f Time.DeltaTime or BoneDataNew 0 .currentXAngle 12.0f END CODE EXAMPLE HERE applies new bone rotation information, (note each bone carries the bone information of rotation like in IK Bone Logic...) SetBones(BoneData) holds Min, Max, Current Angles And Bone Ref. public class BoneConstraintData string bone name float minXAngle, maxXAngle, currentXAngle float minYAngle, maxYAngle, currentYAngle float minZAngle, maxZAngle, currentZAngle I'm using version 5.x.x of Unity 3D.


Can I always assume that fixed time step in Unity is reliable? I was thinking about games on low end machines or phones where the CPU would be limited. If I were to move all of my game logic into FixedUpdate() can I assume that it will always be called with the same time delta? Or would it still be worth adding code to make it take the actual time delta into account?


How to draw an arc between two angles? I'd like to draw an arc between two specific angles. For example, "draw an angle between 0 and 90 degrees" and it will draw only that part of the circle and ignore the rest.


How do I configure a joint for a sliding door in Unity? I have this sliding door where i want to use a joint to limit its motion ...but I am confused about how to configure a joint to provide this sliding motion. I've found the Hinge Joint component, but the comments below say this is for rotating motion. What kind of joint do I use to create a sliding motion?


Unity wall jump issue I've got a very annoying problem that I have been stuck on for a few days and I can't figure it out. It is for a wall jump. I basically want my wall jump to have a bit of force away from to wall to make it look and feel better than just jumping up straight. The problem is, when i add a force on the x axis, it does not register when i am also holding the arrow towards the wall. If I am not holding down the walking button, then press jump...then the x force works. I have a feeling that the horizontal axis force is competing with the opposite force that i want to add to the player when he hits the jump button... Walking code private void ApplyMovement() if (isGrounded) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection ! 0) Vector2 forceToAdd new Vector2(movementForceInAir movementInputDirection, 0) myRigidbody.AddForce(forceToAdd) if (Mathf.Abs(myRigidbody.velocity.x) gt movementSpeed) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection 0) myRigidbody.velocity new Vector2(myRigidbody.velocity.x airDragMultiplier, myRigidbody.velocity.y) if (isWallSliding) if (myRigidbody.velocity.y lt wallSlideSpeed) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, wallSlideSpeed) Jump code private void Jump() if (canJump amp amp !isWallSliding) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, jumpForce) numberOfJumpsLeft else if ((isWallSliding isTouchingWall) amp amp !isGrounded amp amp canJump) isWallSliding false numberOfJumpsLeft Vector2 forceToAdd new Vector2(wallPushForce facingDirection, wallJumpForce wallJumpDirection.y) myRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse) Where I call The code void Update() CheckInput() private void FixedUpdate() ApplyMovement() private void CheckInput() movementInputDirection CrossPlatformInputManager.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() if (Input.GetButtonUp("Jump")) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, myRigidbody.velocity.y variableJumpHeightMultiplier) Any help would be much appreciated. Thanks in advance


How can I provide a csv file to a player on mobile? It seems many people do this with regards to game data so they recommend userprefs, but I just want the user to have the file in the end, whether this is the Files app on iOS or choosing a folder to save in on Android or even just attaching the file as an attachment to an email that they can send using their preferred mail app or something.


Stop animation from playing while waiting to destroy object I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object? C void Die() GetComponent lt Animation gt ().CrossFade(die.name) If the current animation time is greater than 90 of the entire animation length, destroy the object. if(GetComponent lt Animation gt () die.name .time gt GetComponent lt Animation gt () die.name .length 0.9) StartCoroutine(RemoveBody()) IEnumerator RemoveBody() yield return new WaitForSeconds(5) Destroy(gameObject)


Unity Round(Circle) Buttons I have been using unity and C scripting now for the past 2 or 3 weeks. So yeah i am very new to unity and C . I wanted to know if there is a way to make a round(circle) button without using the rect. The problem I have now, I am using a 2d sprite to make the button appear round, however when you hover or click with in the rect, it still works. I saw this asset in the asset store called Alpha Raycaster Check asset out Alpha Raycaster on Unity Asset Store I cannot afford to pay for it right now so I was wondering if there is a free alternative to the Alpha Raycaster for now. Dose anyone know how we can solve this issue? I obviously only want the button to function when the user hovers or clicks within the sprite and NOT on the alpha surrounding the sprite.


Sprite disappears after adding a material to it I have background which is FirsLayer, order in layer 0 and platform over it which is FirstLayer, order in layer 1. Once I add a material to the platform, the layer doesn't seem to change but it gets rendered behind the background. The material that I add 1)Why do I get such results? 2) How can I add the material to the platform and still keep it above the background? P.S. For further clarification if somebody didn't understand, I expected the sprite to stay on its original position(i.e. not to go behind the background when a material is being added to it)


How to make an object jump an equal height whenever it hits the ground? So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried Used Physics.CheckSphere isGrounded Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer) if(isGrounded ) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) Used Raycast bool groundHit Physics.Raycast(rayPoint.position, transform.up, rayDistance, groundLayer) if(groundHit) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?


Allow player to restart animation after it plays fully I have this code that plays an animation when the player touches the screen. The animation lasts 3 seconds. public class canCDanim MonoBehaviour public Animator anim private void Start() anim GetComponent lt Animator gt () void Update() Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) anim.Play( quot CanReload quot ) The trouble is that if the player touches the screen again, the animation will not play again. How can I make it so that I can restart the animation, but only after it's finished playing?


Xcode workspace with Unity3D as a sub project? Let's say we're developing a 2D game with Cocos2d iPhone and UIKit and CoreAnimation. But we're also considering leveraging the 3D capabilities of Unity 3D. Is it possible that we add the Unity3D generated Xcode project as a sub project into the workspace and expose the 3D UI element as some kind of UIView subclass so that the native UIKit and CoreAnimation code could use them without the need to mess up with their underlying Unity3D implementation?


How to make an animation play when a button is pressed once? I have added an idle and jump animation to a character in unity. I can make the animation happen when the button is pressed. If the button is up middle at the animation the character goes to the idle position. But I want the whole animation happen in one press to the button and then go back to the idle position. My current script and Animator views are if (Input.GetKeyDown(KeyCode.Space)) Anim.SetBool("is jumping", true) ApplyInput(moveAxis, turnAxis) else if (Input.GetKeyUp(KeyCode.Space)) Anim.SetBool("is jumping", false)


Position child on the edge of the parent circle while scaling unity3d I have come across to some different situation. I have one circle sprite and i am rotating circle continuously while rotating i want to make circle smaller and larger. I have one object on the edge of the circle i have made that object as child of the circle. Now my problem is how to make this child object to stay at the edge while i scale circle sprite . I s this possible ? Thanks.


Unity 2D Position Child Object to center of Parent Object What I'm trying to achieve is snapping a child object to the center of its parent object after dragging and dropping it. The moving object successfully follows the mouse, and drops. It also successfully selects a dynamic parent when it moves over a new node. What it does NOT do is then snap to the center of its parent. It instead jumps all over the screen and snaps to nothing. Here is all of my code using System.Collections using System.Collections.Generic using UnityEngine public class Object Moveable MonoBehaviour private Vector2 mousePos public float moveSpeed public float offset 0f private bool following private GameObject SelectedNode Use this for initialization void Start() following false offset 10 void Update() if (Input.GetMouseButtonDown(0) amp amp ((Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position).magnitude lt offset)) following true if (following) transform.position Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed) if (Input.GetMouseButtonUp(0)) following false Attach (Node, 0, 0) transform.localPosition SelectedNode.transform.position void OnTriggerEnter2D(Collider2D trigger) if (trigger.tag "pipenode") transform.SetParent(trigger.transform) SelectedNode trigger.gameObject


Why doesn't my SpriteRenderer's color change when setting .color new Color(166, 33, 33)? I need to change the color of my SpriteRenderer, and so I looked up how to do it and come up with this code spaceOne.GetComponent lt SpriteRenderer gt ().color new Color(166, 33, 33) (In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a GameObject.) This should change the color, but it doesn't. As I was writing this, I found that replacing new Color(166, 33, 33) with Color.red actually does change it to red. So now I am wondering, why does the new Color(166, 33, 33) code not work, and how can I fix it? P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with new Color(166, 33, 33, 255) .


AR Foundation video player in Unity without Vuforia I am trying to follow this mini tutorial and I can detect an image and replace it with my 3D object. The object is an AR Session Origin tracked image prefab, but when I try to add a Video Player instead, nothing happens. I was using Unity 2019.2 and got an error when trying to put the video player on the object, then searched about it and Unity fixed that issue on 2019.3. I am now using 2019.3 and don't get the error anymore, but there is also nothing on the screen when the image is detected.


How to enable the option "edit physics shape" in the Sprite Editor? I can successfully import .png files, create tilesets, and use them in my tilemaps in Unity. Thanks to DMGregory, I just learned that there exists an option to customize the Tilemap Collider 2D in the Sprite Editor, which allows me to set a custom collider for every tile instead of going through them one by one. The steps I follow while creating a tileset in Unity is as follows. Import the .png file. Open the Sprite Editor. Select the option Multiple for Sprite Mode. Select Slice from the Sprite Editor. Then, I create a Tile Palette in a folder, drop and drag my created tiles, and start creating my level. I have never encountered the option to modify the colliders tile by tile. What am I doing wrong?


Elegantly exposing properties in Unity inspector There are various game objects in my scene that share some common characteristics, so I created an interface, like so public interface IHasLimitedRangeOfMotionAlongZAxis float MinimumZ get float MaximumZ get For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity. I am aware that one approach is to write C scripts in the Editor folder to implement an ExposePropertyAttribute (see here). However, this approach is unsatisfactory for two reasons My solution is not co located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C language features introduced beyond C 4.0, which nonetheless target .NET Framework 3.5.) I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code. Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties?


How do I connect Unity to a server backend developed in .net core? I'm currently running to a wall in my game development and I need now some discussion to clear my mind... In my mind I have a plan for some little online game (focused around clicking and idling), which I imagined could be served both on website and winapp, and in future even in mobile platforms. I have chosen C for it, build some server backend (join server, game server), but 'cause I want this server components be runned on linux, I have chosen .net core. Which is now my problem, because I'm building the game client in Unity, which only works in .net standard. My main problem now is that I have build some quot base network library quot for communication, written in .netcore with plenty of NuGet packages, which I now have implement to Unity to get it work, but there are now conflicts (the main one is that unity is using another version of System.Threading). Now I am wondering what steps should I choose nexts... There are some work behind now (but not so much, there are only some basic proceses for login and creating game worlds), so probably make that base network package compatible with .netstandard and .netcore. Or I am thinking if it isn't more suitable to choose some another technology like c and some 2D engine in it (which to choose?). What are you opinions? And what would you do in this situation?


Finding Endpoint of line in Unity I have a startpoint, magnitude(length) and direction and want to find endpoint to construct the line here is the code to make question more clear private Vector2 GetEndPoint(Vector2 startPoint, Vector2 direction, float magnitude) Vector2 endPoint some stfuff with parameters return endPoint And this is the visualization of what I want Hope I am clear enough, any suggestions is welcomed


Merging box colliders for optimization Look at the picture. The figure on the left shows the individual box colliders in green. The yellow boxes on the right are the results of the optimization of the original box colliders. What is the algorithm that makes this possible?


Skipping a loop in foreach? I'm trying to get Unity to filter through a list of nodes, but I am unsure on how to do so. This is what I have derived. foreach (TileNode z in map.nodes) int num TileNode z if(num 2 0) continue z.collider.enabled true However an error prompt states that 'z' is an unexpected symbol. Any advice on the proper syntax to deal with this will be greatly appreciated. Also, an example of how do peform filtering using LINQ will be helpful.


Unity how to check if object is fully covered by another objects (2d) I am creating an educational game for kids , and in one of the levels player must to paint animals , like in color book, so I created scene where 2 object , already colorful lion and white lion (white is above) and script, which is instantiating circle sprite masks in players touch position , how can I check if white lion is fully covered by masks and not visiable . P. S. If you have better idea for painting (like painting with brush) and checking , please say.


How to make my player move forward? PlayerMovement.cs using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 2000f void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(!Input.touchSupported) Still support PC keys if(Input.GetKey(KeyCode.D)) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey(KeyCode.A)) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) else For touch devices if(Input.touchCount 1) var touch Input.GetTouch(0) var touchPos touch.position var isRight touchPos.x gt Screen.width 2f if(isRight) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(Physics.Raycast(transform.position,Vector3.down,0.5f) false) rb.velocity new Vector3(0, rb.velocity.y, 0) rb.constraints RigidbodyConstraints.FreezePositionZ else rb.constraints RigidbodyConstraints.None if(rb.position.y lt 1f) FindObjectOfType lt GameManager gt ().EndGame() I tried to debug am I able to click any button. Than, I noticed I got message in console. I think I am unable to add force to player. PlayerCollision.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame() else if(collisionInfo.collider.name quot END quot ) FindObjectOfType lt GameManager gt ().CompleteLevel() void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) Ground Actually, now I think physics isn't working on Player. The Player object is floating. it isn't falling down. Even, it has RigidBody it's not freeze while running the game.


Reading a word list into an array I am making a simple hangman game, I have a small list of words in a .txt file separated by new lines. I put the word list into the assets folder. How can I find the path to the word list so I can use string wordlist System.IO.File.ReadAllLines("pathToFile") Or is there another solution of converting the word list into a string array?


Detect collision without reaction Okay, so this has been bugging me for quite some time now. I'm making an old school platformer type of game in 2.5D, I want objects to pass through each other, but I still want a collision to be detected. If the player gets hit by an enemy, I just want to detect a collision for receiving damage to the player, I don't want the player to move on impact, and I just want the enemy to continue moving where he was heading. I'm using rigidbodies and box colliders on my objects. First I thought using triggers combined with ignoring layers was the solution, but apparently trigger events aren't called when ignoring layers. I still want to be able to use AddForce and stuff for moving objects. Is there someway I can still utilize Unity's OnCollision... OnTrigger... Or other... for just detecting a collision and having no impact movement added when a collision occurs? Have a nice day!


Quaternion not giving correct value back. What am I doing wrong here? Right so I made a quaternion and assigned it a value but it reports back the wrong value. Here is the relevant code... Quaternion LeftTurnLimit Quaternion.identity float test 0.1f LeftTurnLimit Quaternion.Euler(test, 0, 0) Debug.Log(LeftTurnLimit) Expected result (0.1, 0, 0) (x, y, z) Result (0.0, 0.0, 0.0, 1.0) (x, y, z, w) So what am I doing wrong here?


Game testing solutions? I have a unity web browser game. Since I'm working on a small company with limited machines which are all of either 2GB RAM or 4 GB RAM with decent processors. I'd like to know if there are any web based or software 'solutions' to test the game with low configuration both hardware and network bandwidth. And, I have tried cross browser testing solutions, But I didn't see any solution with the option of testing a browser game made for the unity web player .


How do I remove specfic OptionData from Dropdown? How would I remove one of the elements from the dropdown? For example, how would I remove Sprites? Here is my code public Dropdown researchFeatureDropDown researchFeatureDropDown.options.Add(new Dropdown.OptionData("Sprites")) researchFeatureDropDown.options.Add(new Dropdown.OptionData("Scrolling 2000"))


How can I return the class as a Transform in the array instead of each property? public class TransformInfo public string sceneName public string name public Transform parent public Vector3 pos public Quaternion rot public Vector3 scale Then the method public static TransformInfo LoadTransformInfo() string jsonTransform File.ReadAllText( "d json json.txt") if (jsonTransform null) return null TransformInfo savedTransforms JsonHelper.FromJson lt TransformInfo gt (jsonTransform) return savedTransforms The return is But then when using it var test TransformSaver.LoadTransformInfo() Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info. So I can do for example Transform test1 test 0 Instead make a loop and assign each property from the Test to the new Transform test1.


How to load and unload objects at a certain radius from the player? I am making a procedurally generated space exploration game in unity. I'm currently generating 5000 stars in a cube of a fixed size. Each star just gets a random 3d coordinate. What I would like to do is to dynamically load and unload stars at a certain radius from the player. This would be the maximum view distance. The algorithm that does this must be working with a seed for the universe, as the stars need to be loaded in the same spot when you revisit them. My idea is something like in the amazing Space Engine. I have pretty much no knowledge of algorithms that can do this, so I ask for your help.


How do I use guilayout toggle event to check if true or false? OnGUI() for (int i 0 i lt scenes i ) GUILayout.Toggle(false, SceneManager.GetSceneAt(i).name) if (GUILayout.Toggle(true, "New Scene")) Debug.Log("True now !") First in the loop I'm adding some toggles. Then I want to do that if specific toggle is checked(true) do something and if unchecked(false) do something else. But the way I did it it's just changing the toggle to true automatic.


Check if GameComponent is ready in Unity? I am trying to create a MessageBox in Unity, but I'm having some troubles in C .. This is my code (I'll explain my problem later) MsgBox.cs public class MsgBox MonoBehaviour private UIButton btn ok NGUI Button private UILabel caption NGUI Label private GameObject box The message box container void Start() box this.gameObject btn ok box.transform.Find("btn ok").GetComponent lt UIButton gt () caption box.transform.Find("Title").GetComponent lt UILabel gt () the line below works fine, but I don't want to change the caption here this.Caption "This Works" public string Caption get return caption.text set caption.text value My Saved Prefab As you can see, my prefab have the MsgBox.cs attached to the Box component (wich is the box variable). But this code doesn't work Fail Code function createBox() GameObject wnd (GameObject)Instantiate(Resources.Load("Box")) MsgBox mb wnd.GetComponent lt MsgBox gt () bool foo true if (mb null) Debug.Log("MsgBox is null") foo false if (!(mb is MsgBox)) Debug.Log("mb is not MsgBox") foo false if (foo) Debug.Log("passed!") mb.Caption "Hello!" Console Output passed!NullReferenceException Object reference not set to an instance of an object MsgBox.set Caption (System.String value) (at Assets scripts MsgBox.cs) If I change this public string Caption get return caption.text set caption.text value to this public string Caption get return caption.text set if ( caption null) Debug.Log("Caption is null") else caption.text value and call createBox, the console give me this Caption is null Why? Why I can't change the caption from outside the MsgBox? Maybe the createBox() is being called first than Start()? PS. Using Unity 5 64 bit. My platform is WebGL. PS . English is not my native language, sorry.


Touch goes through UI objects on mobile I know this question has been asked a lot of times, and I have tried the solutions that were provided and I still have no valuable result, so I thought...maybe a new set of eyes could help. I have a game in which the player can navigate around the scene environment using a virtual joystick and look around the scene by scrolling through the screen(like it is seen in most mobile fps games). The problem that I am having now is that my "look around" script allows touch inputs to pass through UI elements on mobile, but everything works fine on the editor. Useful tips 1) I am using Unity 2019.3.0f5 2) I setup the script to work with Cinemachine Free Look, and my script(seen below) is attached to it. Here is my code using UnityEngine.EventSystems using UnityEngine using Cinemachine public class CinemachineCoreInputTouchAxis MonoBehaviour private readonly float TouchSensitivity x 10f private readonly float TouchSensitivity y 10f SerializeField private bool UseTouchControls true private static int Index 0 void Start() if(UseTouchControls) CinemachineCore.GetInputAxis HandleAxisInputDelegate private float HandleAxisInputDelegate(string axisName) switch (axisName) case "Mouse X" if (Input.touchCount gt 0 amp amp !IsPointerOverUIObject()) return Input.touches Index .deltaPosition.x TouchSensitivity x else return Input.GetAxis(axisName) case "Mouse Y" if (Input.touchCount gt 0 amp amp !IsPointerOverUIObject()) return Input.touches Index .deltaPosition.y TouchSensitivity y else return Input.GetAxis(axisName) default Debug.LogError("Input lt " axisName " gt not recognized.", this) break return 0f public static bool IsPointerOverUIObject() Called to check if the pointer is over a ui object bool value false for (int i 0 i lt Input.touches.Length i ) Index i value EventSystem.current.IsPointerOverGameObject(Input.GetTouch(Index).fingerId) if (value) break return value Can anyone please let me know what I am failing to see and how to fix it?


Is it possible to debug a Unity Android game directly on a device? I'm working on my game and every time I make changes to it I send the game to my mobile device to debug it. I want to know how I can directly debug my game using an Android device instead of the MonoDevelop editor?


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


How to stop a jump midair and remove y velocity in the process What I want to do is to cut a jump midair by turning off the y velocity when the player releases the jump button (like in Hollow Knight). I managed to do that with rb.velocity new Vector2(rb.velocity.x, 0f) My problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously. I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PlayerController MonoBehaviour public Animator animator private Rigidbody2D rb public float speed private float moveInput public float jumpForce private bool isGrounded public Transform feetPos public float checkRadius public LayerMask whatIsGround private float jumpTimeCounter public float jumpTime private bool isJumping private bool facingRight true public float jumpDownForceY 0 void Start() rb GetComponent lt Rigidbody2D gt () void Update() isGrounded Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround) if (Input.GetButtonDown( quot Jump quot ) amp amp rb.velocity.y 0) rb.AddForce(Vector2.up 700f) if (Mathf.Abs(moveInput) gt 0 amp amp rb.velocity.y 0) animator.SetBool( quot Running quot , true) else animator.SetBool( quot Running quot , false) if (rb.velocity.y 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , false) if (rb.velocity.y gt 0.2) animator.SetBool( quot Jumping quot , true) if (rb.velocity.y lt 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , true) if (isGrounded true amp amp Input.GetButtonDown( quot Jump quot )) isJumping true jumpTimeCounter jumpTime rb.velocity Vector2.up jumpForce if (Input.GetButton( quot Jump quot ) amp amp isJumping true) if (jumpTimeCounter gt 0) rb.velocity Vector2.up jumpForce jumpTimeCounter Time.deltaTime else isJumping false if (Input.GetButtonUp( quot Jump quot )) isJumping false rb.velocity new Vector2(rb.velocity.x, 0f) void FixedUpdate() moveInput Input.GetAxisRaw( quot Horizontal quot ) rb.velocity new Vector2(moveInput speed, rb.velocity.y) Flip(moveInput) private void Flip(float moveInput) if (moveInput gt 0 amp amp !facingRight moveInput lt 0 amp amp facingRight) facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale


All scripts in Unity game can not be loaded I can not provide a "why" here, because as far as I can tell it happened spontaneously after saving an edit to one of my scripts, it just started happening. But here's the problem Every single one of my scripts, while still in the same Scripts file, can no longer be found and loaded. All the Script Components (take the Game Manager component for example) now look like this or like this Attempting to locate the scripts by going Add Component Scripts Desired Script doesn't work, because there isn't even a Scripts item in the Add Component menu. I have already looked this up, and none of the answers I found were applicable Yes, every script's file name is the same as the Class name within them I have tried reimporting all assets (Assets Reimport All), no success. Taking all scripts out of the project, restarting unity and then reimporting the scripts. Nothing Removing all script components, then reapplying them. It didn't work because, as I said, there was no Script item in the Components menu. This is a pretty game breaking, literally, because this is a hobby game (I'm not doing this as a job, it's just in spare time). If I can't restore the game as it was, I won't be able to bring myself to restart it. So any help is greatly appreciated.


Draw "rasterize" irregular circle onto a 2D grid I'm using the midpoint circle algorithm to choose cells on a 2D grid which outline a circle. However, I need to incorporate some random noise so that I get an irregular circle, and this method won't work anymore given how it works. Another stack exchange answer describes an equation (the "pink noise" example) I'd like to try but I'm not sure on the best approach to implement it. I can replicate the equation via code, but I'll need to start choosing grid cells coordinates differently and I'm not sure the best solution. How can I "rasterize" an irregular circle like this?


Keeping 2 objects within cameras view I have two object to control and I wanted to keep them at cameras view without adjusting the cameras size but the camera can move only in positive y axis meaning ones it goes up it shouldn't move down but it's okay if one object gets out of bounds. Since its 2D the camera is Orthographic view.


How can I add an in game level editor? I have 200 prefabs and a scene with an infinite flat plane. I want to allow user to edit the scene add, remove, rotate, place that prefabs and save load resulting "scene" in some custom format. How can I implement this?


How to delay jump to syncronize with an animation ? I'm using Unity and First Person Controller. If i press the jump button, my charachter jump immediately. I want,instead, that jump movement starts after (for instance) 1 second, to be syncronized with a jumping animation I trigger. How to do that ? Thanks


How can I add a glow effect around a pair of wings in Unity without post processing? Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C script hanging in the main camera. Any idea to implement?


Some submeshes of my gameobject dissapear when I set the bindposes Well, I'm trying to animate some Source models imported into Unity3D using this Unity Source Tools library https github.com lewa j Unity Source Tools To animate a Mesh generated by this tool I need to create a SkinnedMeshRenderer replacing the MeshRenderer and the MeshFilter components, so I created this method private static void ReplaceRenderer(this GameObject obj, SourceStudioModelv2 model) if (obj.GetComponent lt SkinnedMeshRenderer gt () ! null) return var mesh Object.Instantiate(obj.GetComponent lt MeshFilter gt ().sharedMesh) const bool debugPoses true const bool useNativePoses true var nativeBuilder debugPoses ? new StringBuilder( quot Native Matrix n new string(' ', 10) n quot ) null var unityBuilder debugPoses ? new StringBuilder( quot Unity Matrix n new string(' ', 10) n quot ) null var nativeMatrix model.GetBindPosesFromModel(nativeBuilder).ToArray() var unityMatrix obj.transform.GetBindPoses(model.Bones, unityBuilder).ToArray() if (debugPoses) Debug.Log(nativeBuilder.ToString()) Debug.Log(unityBuilder.ToString()) var matrix useNativePoses ? nativeMatrix unityMatrix mesh.bindposes matrix Object.Destroy(obj.GetComponent lt MeshFilter gt ()) Object.Destroy(obj.GetComponent lt MeshRenderer gt ()) var skinned obj.AddComponent lt SkinnedMeshRenderer gt () skinned.sharedMesh mesh skinned.rootBone obj.transform skinned.bones model.Bones As you can see, I'm creating two bind poses, because one of them is created from this part of the code https github.com lewa j Unity Source Tools blob c5469deb1d630c1582c940ff3cdb0f69fc55eda3 Assets Code Read SourceStudioModel.cs L724 L728 And this is how I create the bindposes Native Poses private static IEnumerable lt Matrix4x4 gt GetBindPosesFromModel(this SourceStudioModelv2 model, StringBuilder sb null) for (var i 0 i lt model.MdlBones.Length i ) var mdlBone model.MdlBones i From https stackoverflow.com a 49268287 3286975 var matrix (new Matrix4x4( new Vector4(mdlBone.PoseToBone 0 , mdlBone.PoseToBone 1 , mdlBone.PoseToBone 2 , mdlBone.PoseToBone 3 ), new Vector4(mdlBone.PoseToBone 4 , mdlBone.PoseToBone 5 , mdlBone.PoseToBone 6 , mdlBone.PoseToBone 7 ), new Vector4(mdlBone.PoseToBone 8 , mdlBone.PoseToBone 9 , mdlBone.PoseToBone 10 , mdlBone.PoseToBone 11 ), new Vector4(0, 0, 0, 1) )).transpose sb?.AppendLine( quot i matrix.ToString( quot F2 quot ) quot ) yield return matrix Unity Poses private static IEnumerable lt Matrix4x4 gt GetBindPoses(this Transform transform, Transform bones, StringBuilder sb null) for (var i 0 i lt bones.Length i ) var bone bones i var matrix bone.worldToLocalMatrix transform.localToWorldMatrix sb?.AppendLine( quot i matrix.ToString( quot F2 quot ) quot ) yield return matrix And these are the values that each of them gives to me Unity Bindposes https pastebin.com 9tybGq7Z And this is the result Native Bindposes https pastebin.com YRZVq04y But this one doesn't show anything. I saw this reference on internet https hg.alliedmods.net hl2sdks hl2sdk file 4966093d3274 utils studiomdl simplify.cpp l3745 But I'm not sure if I'll be able to transcript this into Unity and if it will be useful... If you would like to test this model out I created a .unitypackage file for you to test https mega.nz file xKpRSYwJ j3ckM3GyFDFZKI6Y OvN2cmcGC GudGe2finLRQoA4U So I don't know how to proceed in this case, could anybody help me out with this?


Should I code game logic separately from game engine scripts I'm developing a game in Unity3d, economic strategy. I wonder if I should code logic inside unity scripts, or write it as an external module library? By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc. If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client server) without rewriting whole logic for server side, where unity cannot be used. I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily. Is this a common practice, or should I avoid it, or maybe there is some alternative patterns?


How to smooth jagged pixel edges in Unity? So I am reading an image from a png file into a 2D sprite. This sprite serves as a "province" in my game. Currently, I am getting this If you look closely, you will notice that you are seeing the square corners of each pixel, because I am mapping the image on a 1 1 ratio of pixels world coordinates. What I want is a slightly rounded corner in these places. Look at the 2 dimensional provinces in this example I have been googling around for algorithms, but most answers simply say "use a shader" and don't describe the techniques used to do this (until now I have not done much with shaders). If you would like to see my working code for the province system, it is posted on my answer to my own question here.


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


Animator consecutive set parameter problem I'm having a little problem with my animations transitions. I have this diagram http imgur.com Se8Ix1L My transitions is made by updating the parameter "stateparam". My code, changing the parameter http imgur.com HlypG2L I change stateparam to 2 and right after to 0, then my animation don't restart every frame. But when I play, the my parameter doesn't change the animation and only change the stateparam to 0. I already debugged and it's passing in the line that change to valid transition value. But i don't know why my animation doesn't changes. If I play and change stateparam manually, it works. If I take off the SetInteger "0", let only the valid value, the code works, but my animation keep restarting before it can finish itself. I don't know if the parameter change it's too fast to do the transition or it's any buggy. Any help ?


How to make Flood fill algorithm return different Lists of separate groups in the grid? So i have this flood fill method public int groupedCells(int y, int x, int value) base state if (!gSetup.isValidLocation(y, x) gSetup.getCell(y, x).value ! value gSetup.getCell(y, x).cMAtch.isInMatchPool) return 0 keep track of matched cells gSetup.getCell(y, x).cMAtch.isInMatchPool true collect int up groupedCells(y 1, x, value) up int left groupedCells(y, x 1, value) left int right groupedCells(y, x 1, value) right int down groupedCells(y 1, x, value) down sum int total up left right down 1 return total basically i have this grid and currently if i click on a yellow triangle, the method above will tell me how many of them are next to each other. What i want is a solution that will run all over the grid, and check if a group has less than 3 triangles then do (A) if it has 3 triangles then do (B) if it has 4 triangles then do (C) etc ... Am not sure about this, but i thought the best way is to have a list for every group, and then check those conditions over the lists. I tried it here but the list keep re initializing itself, so it always either have 0 cells or 1 public List lt CellSetup gt listedCells(int y, int x, int value) List lt CellSetup gt cList new List lt CellSetup gt () base state if (!gSetup.isValidLocation(y, x) gSetup.getCell(y, x).value ! value gSetup.getCell(y, x).cMAtch.isInMatchPool) return cList keep track of matched cells gSetup.getCell(y, x).cMAtch.isInMatchPool true cList.Add(gSetup.getCell(y, x)) collect List lt CellSetup gt up listedCells(y 1, x, value) up List lt CellSetup gt left listedCells(y, x 1, value) left List lt CellSetup gt right listedCells(y, x 1, value) right List lt CellSetup gt down listedCells(y 1, x, value) down return cList The result of that method when its called here for (int y 0 y lt gSetup.cell2DArray.GetLength(0) y ) for (int x 0 x lt gSetup.cell2DArray.GetLength(1) x ) print(listedCells(y, x, 1).Count) is printing "1" three times and "0" 22 times. Thank you


What is the most efficient technique for range detection? I have a bunch of patrolling enemies that fire projectiles when the player is in projectile range a specific radius. Which method is the most efficient and elegant? overlapSphere sphereCast triggers square magnitude anything else? I am using Unity.


Why don't my generated instances update when I change their prefab? I m making an Editor tool a ScriptableWizard that instantiates a prefab on a grid. But I find that when I update the prefab, the instances don t update. When I instantiate prefabs interactively in the Editor by dragging them from the Project panel to the Scene or Hierarchy, then updates to the prefab affect the instances as expected. I see another difference between my scripted instances and the ones created when I drag the prefab into the scene when I do it interactively, the instance in the hierarchy is listed in blue. But the instances I create from script using the same prefab are listed in black, similar to objects created directly in the scene. Here s the hierarchy the JitterPrefab was dragged into the scene, and the ones under gridParent were instances of the JitterPrefab generated from my script Here s how I m generating the instances public GameObject prefab ... void OnWizardCreate() ... Transform instance Instantiate (prefab.transform, pos, rot, parent.transform) instance.name string.Format ("L 0 D2 R 1 D2 C 2 D2 ", l, r, c) ... When I make a change on the prefab, e.g. change the radius of the Jitter script from 0.025 to 0.25, the manually created instance updates But the script generated instances do not What am I doing wrong? Why are my scripted instances no longer connected to the original prefab? And, separately, how to I tell in the editor (or in script) whether an object in the scene is an instance of a prefab or not?


Unity OnRenderImage hides UI I have a component which renders a few different cameras and the images. However, this obscures my UI when in Screen Space Overlay mode. I can put the canvas in WorldSpace mode, which works, but then the UI is affected by the image effect I've built and is, of course, not locked to the camera. Suggestions? Update additional details At design time, the OVR camera rig contains a single camera centered between the "eyes." This component is attached to the camera rig's centerEyeAnchor. At run time, the rig creates two additional cameras one for each eye. These aren't supposed to be modified by user code. (Among other things, their projection matrices are pretty weird.) I need to modify the image per eye. I created a new component which create two additional cameras per eye. One renders a low res version of the entire scene, the other renders a high res image of a portion of the screen, each to a dedicated RenderTexture. Pseudocode void Update() called once per frame called twice per frame once per eye void OnPreRender() called twice per frame once per eye void OnRenderImage(RenderTexture source, RenderTexture destination) low res render of entire scene var camOuter m cameras ... hi res render of part of the scene 10 20 of original image area var camInner m cameras ... update cameras to match current eye camera camOuter.copyFrom(Camera.current) camOuter.targetTexture m outerTexture render scene to low res texture camOuter.Render() camInner.copyFrom(Camera.current) camInner.targetTexture m innerTexture target texture that the Oculus wants to render to var ovrTexture Camera.current.targetTexture save projection matrix var originalProjectionMatrix camInner.projectionMatrix var scale new Vector3(m innerTexture.width 1.0f ovrTexture.width, m innerTexture.height 1.0f ovrTexture.height) zoom pan matrix to clip to part of the scene var gazeMatrix Matrix4x4.Scale(scale) offset projection gazeMatrix.m03 (1 2 gaze.x) scale.x gazeMatrix.m13 (1 2 gaze.y) scale.y camOuter.projectionMatrix gazeMatrix amp originalPRojectionMatrix render hi res portion of the scene centered at gaze pixel camOuter.Render() restore projection matrix cam.projectionMatrix originalProjectionMatrix composite images m material.SetTexture("InnerTexture", m innerTexture) m material.SetTexture("OuterTexture", m outerTexture) Graphics.Blit(null, destination, m material) (I'm also worried that there may be additional scene renders happening in the background.) The problem is that the UI does not render if set to Screenspace Overlay or Screenspace Camera. I can get it to render in Worldspace, which may be the only way to do this, but then it seems I'd need to create yet another hi res texture matching the viewport dimensions and render the UI layer to that, and keep it locked to the current eye's camera position. Alternatively, I could re use one of the current cameras, I guess, and just tweak its settings. Is there a better way to do this? Ideally, I'd like to have the engine just render the UI as it does in other applications without having to jump through hoops. However, at this point, I'll take anything I can get that works and looks good. Update the 2nd Okay, it looks like the UI is rendered perfectly if I use a regular camera instead of the OVR rig. ( Having the rig in the scene, though, prevents it from drawing at all.