- Home /
Vector 3 in array
hi
i'm trying to use an array containing three Vector3's which refer to 3 respawning locations.
when the player dies (or in the code, has a transform.x >80) then new respawn position is randomly chosen from the array.
function Start () { var array = new Array (Vector3(0, 5, 70), Vector3(-50, 5, -50), Vector3(60, 5, -20)); }
function Update () { var randomposition = Random.Range (0, 2); // select random number var newlocation: Vector3[] = array[randomposition]; //new Vector 3 from array
if(transform.position.x >80) // player moves past arbitary point, new location { transform.position = newlocation; } }
however i get the error message
BCE0048: Type 'System.Type' does not support slicing.
i'm fairly new to Unity so apologies if i'm making a fundamental mistake here!
cheers duncan
Answer by Peter G · Nov 06, 2010 at 12:34 PM
I'm going to give you 2 codes, the first, since you are new to this will explain what you did wrong or could do better, and the second will be a functional version to help you out.
function Start () { var array = new Array (Vector3(0, 5, 70), Vector3(-50, 5, -50), Vector3(60, 5, -20)); //You can make an array like this, but they are slower for several reasons. //.Net arrays , like you did below, are a better choice.
//And, you created this array locally, so when you access it in your
//other methods, it does not exist.
}
function Update () { var randomposition : int = Random.Range (0, 2); // select random number var newlocation: Vector3[] = array[randomposition]; //new Vector 3 from array // This is the line with the error. You are creating a new Vector3[] but are assigning it the value of a Vector3.
if(transform.position.x >80) // player moves past arbitary point, new location
//You should also not hardcode values.
{
transform.position = newlocation;
//This is fine except you assigned it the wrong type above.
}
}
Here is the corrected code.
var spawnPoints : Vector3[]; //create an array of positions var minDistForRand : float = 80; //Add both these values in the inspector.
function Update () { var randomIndex : int = Random.Range(0, spawnPoints.Length); //Choose a random number based on the length of the array
var newLocation : Vector3 = spawnPoints[randomIndex];
//Choose a new point from the array of spawn points.
if(transform.position.x > minDistForRand) {
transform.position = newLocation;
}
}
Random.Range should use spawnPoints.Length, not Length - 1. See the docs for Random.Range with integers. Also it should be just "`var spawnPoints : Vector3[];`"
Your answer
Follow this Question
Related Questions
Vector1, Vector2, Vector3? 1 Answer
Rotate Vector3 array around a point 1 Answer
Javascript - find a value in an array 0 Answers
Multiple Fire Points 2 Answers
Get size of a vector3 array c# 1 Answer