- Home /
Static array variable
Hello everyone, i need 3 instances of an object at 3 different positions on the x axis between x = - 4 and x = 4. Then in another script, i need these 4 objects to start a ping pong movement along the x axis. So it seems i need a static array variable. I created this code but unity gives me lots of errors. Can you help me?
Script 1 (named GameController.js)
static var xpos : float[];
function Start(){
xpos = Random.Range (-4.0, 4.0);
}
function LevelEnd(){
Instantiate(enemy, Vector3(xpos[0], 0, 0), transform.rotation);
Instantiate(enemy, Vector3(xpos[1], 0, 0), transform.rotation);
Instantiate(enemy, Vector3(xpos[2], 0, 0), transform.rotation);
}
Script 2 (named EnemyMovement.js)
var pingpongspeed: float;
function Update () {
GameController.xpos += Time.deltaTime*pingpongspeed;
transform.position.x = Mathf.PingPong (GameController.xpos, 8.0);
}
Answer by Kryptos · Jul 13, 2012 at 01:24 PM
You first created a static variable named xpos of type float[], but then try to read it as a float (not an array).
You may need to change your script this way (it is just a suggestion):
Script 1 (named GameController.js)
function Start(){
xpos = new float[3]; // C#-syntax, not sure if this is the same syntax in UnityScript.
xpos[0] = Random.Range (-4.0, 4.0);
xpos[1] = Random.Range (-4.0, 4.0);
xpos[2] = Random.Range (-4.0, 4.0);
}
Script 2 (named EnemyMovement.js)
var pingpongspeed: float;
var id: int; // id is between 0 and 3 included, different for each instance
function Update () {
GameController.xpos[id] += Time.deltaTime*pingpongspeed;
transform.position.x = Mathf.PingPong (GameController.xpos[id], 8.0);
}
it worked in a strange way, the istances teleport at the same position on the x axis and then start moving (following the same path).
This line is responsible for it (and I$$anonymous$$HO it does not make sense):
GameController.xpos += Time.deltaTime*pingpongspeed; // or GameController.xpos[id] in my answer
I just pointed out the modification needed for the script to run. But you may have to review the logic.
The first parameter of $$anonymous$$ath.PingPong should be a time not a position.
i tried to change the code as this but the result is the same
function Update () {
transform.position.x = $$anonymous$$athf.PingPong (Time.time, 8.0);
}
i tried to change the code as this but the result is the same
function Update () {
transform.position.x = $$anonymous$$athf.PingPong (Time.time, 8.0) - 4.0;
}
Your answer
Follow this Question
Related Questions
Script effects all gameobjects. 1 Answer
Command all array variable values 1 Answer
Increasing a score value? 2 Answers
Will static variables not work if negative? 1 Answer
Reset a static variable? 1 Answer