- Home /
Array doesn't increase or add element
I'm making a racing simulator and I made this script for a replay system. But when i tried it it didn't add any elements, they just stayed at 3. this is how it looked :
#pragma strict
var recorded_obj : GameObject;//Object to record
var Positions : Vector3[];
var Rotations : Quaternion[];
var replayPosition : int;
function Start ()
{
}
function Update ()
{
AddPos();
AddRot();
if(Input.GetKey("r"))
{
Replay();
}
else
{
replayPosition = 0;
}
}
function AddPos()
{
var positionsarr = new Array(recorded_obj.transform.position);
positionsarr.length += 1;
positionsarr.Add(recorded_obj.transform.position);
Positions = positionsarr;
}
function AddRot()
{
var rotationsarr = new Array(recorded_obj.transform.rotation);
rotationsarr.length += 1;
rotationsarr.Add(recorded_obj.transform.position);
Rotations = rotationsarr;
}
function Replay()
{
//Position
recorded_obj.transform.position = Positions[replayPosition];
//Rotation
recorded_obj.transform.rotation = Rotations[replayPosition];
replayPosition += 1;
}
What's wrong? I've read the Add() description in the scripting API, and it says that it adds a for example value to the end of the Array.
Line 39
rotationsarr.Add(recorded_obj.transform.position);
Spot the mistake.
Answer by meat5000 · Feb 11, 2015 at 02:22 PM
Use a List
#pragma strict
import System.Collections.Generic; //Access Lists
var recorded_obj : GameObject;//Object to record
public var positionsarr : List.<Vector3>; //Make List of type
public var rotationsarr : List.<Quaternion>; //Make List of type
var Positions : List.<Vector3>;
var Rotations : List.<Quaternion>;
var replayPosition : int;
function Update ()
{
AddPos();
AddRot();
if(Input.GetKey("r"))
{
Replay();
}
else
{
replayPosition = 0;
}
}
function AddPos()
{
positionsarr.Add(recorded_obj.transform.position);
Positions = positionsarr;
}
function AddRot()
{
rotationsarr.Add(recorded_obj.transform.rotation);
Rotations = rotationsarr;
}
function Replay()
{
recorded_obj.transform.position = Positions[replayPosition];
recorded_obj.transform.rotation = Rotations[replayPosition];
replayPosition += 1;
}
Note : If you experience a slowdown with this script, its because the editor is trying to update everything to the inspector. Hide the values from inspector or simply close the List fields by clicking the triangles.
@meat5000 Thanks! it works fine now. i really appreciate yor help
Your answer
Follow this Question
Related Questions
NGUI - Vector 3 Position different from position 1 Answer
Adding to an array - C# 2 Answers
problem moving a prefab object in script (c#) 0 Answers
Make object move in a direction depending on where it spawns? (C#) 1 Answer
How to set to game objects's position from 2 different game objects arrays equal to each other? 0 Answers