- Home /
DrawLine from enemy to player
Hi Guys, Simple question ( I Hope ).
I want debug to draw a line from the enemy to the player, what I'm currently doing does not work, it draws a line off ot the side not in any real relation to the player.
This debug is on the enemy script.
pointA = transform.position;
pointB = GameObject.FindGameObjectWithTag("Player").transform.position;
pointB = pointA + 3 * pointB;
Debug.DrawLine (pointA, pointB, Color.white, 0.5);
hey i try the same code but without "pointB = pointA = 3*pointB" its working fine it draw line b/w center of first object from center of second object.
Answer by fafase · Dec 03, 2012 at 01:14 PM
This is due to the fact that transform.position is a structure. It means it is a value type as opposed to reference type. When you do:
pointA = transform.position;
You are copying the value of transform.position at that moment. When you move later on, pointA is not updated and remains with the original value.
Same applies to pointB.
Now, transform is a component that is passed by reference. It means that you do not pass the value contained but instead you pass the address of it:
Transform myTransform = transform;
myTransform is a reference to transform (a pointer in old C/C++) that holds the address of transform. When using myTransform, the compiler finds an address and jumps there and finds transform. This way, transform is constantly updated and so is myTransform.
Now to fix your issue:
Transform pointA = transform;
Transform pointB = GameObject.FindGameObjectWithTag("Player").transform;
Debug.DrawLine (pointA.position, pointB.position, Color.white, 0.5);
This will draw from player to enemy.
If you want a larger article about all this, check out this one: http://unitygems.com/memorymanagement/