- Home /
gameObject not destroyed after reaching desired coordinates.
pragma strict
var speed : int = 10; //velocity of bullet
var upLimit : float = 5.0;
function Start () {
}
function Update () {
transform.Translate(Vector3(0,0,speed*Time.deltaTime));
Debug.Log(transform.position.z);
if (transform.position.z >= upLimit){
Destroy(gameObject);
}
}
Hello guys. WhatI am trying to do is ro destroy my bullet after it reaches 5.0 or any desired coordinates in the grid. in the z axis. the code doesn't seem to work. Is it a semantics error? Im a beginner coder obviously. some help is greatly appreaciated.
thanks :)
Tried
transform.Translate(Vector3.forward * speed * Time.deltaTime);
?
Shouldnt really make a difference, just worth a go.
That code works for me when the script is attached to a simple cube in a brand new scene - I get a debug log of increasing positions, and then the object is destroyed. One thing I noticed - the "z" axis points forward in Unity, but the variable limit against which you're testing is called "UpLimit" - you do know that this moves the object forward, not up?
hi thanks for the tip on simplifying the code.$$anonymous$$aybe i wasn't clear with my question.
when transform.position.z => 5.0 lets say in the z axis. the gameObject is not destroyed?
when i debug the transform.Translate, it clearly traveled from 0 to infinity... technically it the object should be destroyed once it pass the 5.0 mark on the z axis right?
I could add a bumper and make it destroy on collision.
im just curious if i can do it the way i setup the code. or is there another better way to it?
Answer by EHogger · Sep 07, 2013 at 08:58 PM
The problem is that transform.translate moves the object on it's own local axis, but transform.position is in world space.
You need to add Space.World to the translate line. See here:
http://docs.unity3d.com/Documentation/ScriptReference/Transform.Translate.html
However, this is only going to move your bullet in one direction. If you wanted to move the bullet in it's own axis and limit the range, you'd need to store the starting position and measure the distance travelled instead.
exactly what i was looking for. how could i have missed that in the Ref. maybe i skimmed through it, will need to read carefully next time round!
thanks a lot! :)