- Home /
I want to reset my object to its original position.
Hey guys,
I'm creating a game where I want a car to pass by over and over again. I know how to let the object move but I don't know how to reset it so it starts again at its starting point. I'm trying it like this but nothing happens, tried to find the right answer but there's none. I'm a noob in C#, do you also have tips to help me getting better at C#
public class Rewspawn : MonoBehaviour {
void Start()
{
}
void OnTriggerEnter(Collider other)
{
Vector3 orginalPosition = gameObject.transform.position;
if(other.gameObject.tag == "End")
{
gameObject.transform.position = orginalPosition;
}
}
}
//Note exObj is the object you want to use to set the original position, this works with images as well with images you can turn down the alpha to 0 and it will be invisible, also this script must go on the object that you want to move back to the original position or you can make a public GameObject myObj set it as the object you want to set back and change transform.localPosition = originalPosition; to myObj.transform.localPosition = originalPosition;
public Vector3 originalPosition;
public GameObject exObj;
void Start () { originalPosition = exObj.transform.localPosition; }
void OnTriggerEnter(Collider other) { if(other.gameObject.tag == "End") { transform.localPosition = originalPosition; }
}
Answer by FM-Productions · Jun 03, 2017 at 12:57 PM
Store the original position in the Start or Awake function:
Vector3 originalPos;
void Start()
{
originalPos = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
//alternatively, just: originalPos = gameObject.transform.position;
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "End")
{
gameObject.transform.position = originalPos;
}
}
Thank you, this helped me a lot. Also helps me better understanding C#.
alternatively, you can do: originalPos = transform.position;
and when comparing tags, use CompareTag(), like so:
void OnTriggerEnter ( Collider other )
{
if ( other.CompareTag ( "End" ) )
{
transform.position = originalPos;
}
}
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Timer variable set to zero 2 Answers
Prevent player from activating same checkpoint again. 2 Answers