- Home /
Changing object location every 3 second
I am working on very simple slender man game. The problem is my location change code works really weird.
Here is the code:
#pragma strict
var Spawn1 : Transform;
var Spawn2 : Transform;
var Spawn3 : Transform;
var Spawn4 : Transform;
function Update ()
{
spawn();
}
function spawn ()
{
yield WaitForSeconds (3);
this.transform.position = Spawn1.position;
yield WaitForSeconds (3);
this.transform.position = Spawn2.position;
}
i'm not sure what really weird means. Perhaps you can explain exactly what is happening or what you find weird about your currently solution.
idk how to explain that but it is really weird. If you are avaliable to test that on your own unity you will see that somethings are really wrong at this script.
I am really sorry but my english isnt enough to explain that. Actually I am not sure about I can explain this even in my native language.
okay, hows this, what is this script attached to? Now also remember, the code above will execute once per frame, stacking 3 second calls and yielding during the entire game play.
It can be attached to any obect. $$anonymous$$y goal with this script is;
It will change the location of object every 3 seconds with this line:
Spawn1
wait 3 seconds
Spawn2
wait 3 seconds
Spawn 3
Wait 3 seconds
Spawn 4
and then again spawn 1, spawn 2, spawn 3, spawn 4.
Actually I tried to make a loop.
Answer by Landern · Aug 19, 2014 at 08:16 PM
Try this(it was not tested), assign the Transforms in the inspector.
import System.Collections.Generic; // To use list
#pragma strict
var spawnPositions : List.<Transform> = new List.<Transform>(); // Add as many as you want in the inspector
var spawnIndex : int = 0;
function Update ()
{
// If not invoking, invoke the spawn method.
if (!IsInvoking("spawn"))
Invoke("spawn", 3); // Invoke every 3 seconds if not invoking already
}
function spawn ()
{
this.transform.position = spawnPositions[spawnIndex].position; // Set this gameobjects transform to the spawnIndex of spawnPositions
spawnIndex++; // Increment the currentIndex
// The index is 0 based when accessing items in the list, we need to compare the count minus 1 to see if we need to reset the spawnIndex.
if (spawnIndex > spawnPositions.Count - 1)
spawnIndex = 0;
}
Answer by Cherno · Aug 20, 2014 at 03:33 PM
var t : float;
var threshold : float = 3.0f;
var newPos : Vector3;
function Update() {
t += Timer.deltaTime;
if(t >= threshold) {
t = 0.0f;
transform.position = newPos;
}
}
How you determing the next position is up to you; you could use
newPos = new Vector3(Random.Range(0,100), 0, Random.Range(0,100));
so it randomly pikcs a ground position between 0 and 100 and the x and z axis.
Your answer
Follow this Question
Related Questions
Turning character slowly with Slerp 1 Answer
distance to variable object 1 Answer
Instantiate as a child at position 2 Answers
Position of a GameObject 2 Answers
Locating Position of Object not Working? 2 Answers