How to solve IndexOutOfRangeException? - unity3d

I have some error related to IndexOutOfRangeException. The number of errors is over 200 and the error comes up when I play the game.
Error shown like this:
IndexOutOfRangeException: Array index is out of range. GameController.OnGUI () (at Assets/MicroRacers Assets/Scripts/GameController.js:67)
Here is the code of my game controller.
var CheckPoints:Transform[];
var LapsToWin:int = 5;
var PointsPerPlace:Array = new Array(8,4,2,1);
var CountDownToStart:float = 5;
var Items:Transform[];
var ItemCopy:Object;
var SpawnTime:Vector2 = Vector2(5,10);
private var SpawnTimeCount:float = 0;
var MaximumItems:int = 5;
private var ItemCount:int = 0;
private var FinishPlace:int = 0;
private var Players:int = 1;
var RaceEndDelay:float = 5;
//~ function Awake()
//~ {
//~ Application.targetFrameRate = 30;
//~ }
function Start()
{
SpawnTimeCount = Random.Range(SpawnTime.x, SpawnTime.y);
}
function Update ()
{
if ( SpawnTimeCount > 0 )
{
SpawnTimeCount -= Time.deltaTime;
}
else if ( ItemCount < MaximumItems )
{
SpawnTimeCount = Random.Range(SpawnTime.x, SpawnTime.y);
ItemCount++;
ItemCopy = Instantiate(Items[Mathf.Floor(Random.Range(0, Items.length - 1))], CheckPoints[Mathf.Floor(Random.Range(0, CheckPoints.length - 1))].position + Vector3.up * 0.3, Quaternion.identity);
ItemCopy.transform.Translate(Vector3.right * Random.Range(-3,3), Space.Self);
}
if ( Players == 0 )
{
RaceEndDelay -= Time.deltaTime;
if ( RaceEndDelay <= 0 )
{
Application.LoadLevel("end");
}
}
}
//This script displays the HUD, with current weapon, ammo left, Health, Shield, and score
var GUIskin:GUISkin; //The skin gui we'll use
var CountdownTextures:Texture2D[];
private var CountdownTextureIndex:int = 0;
function OnGUI()
{
GUI.skin = GUIskin; //The skin gui we'll use
if ( CountDownToStart > Time.timeSinceLevelLoad )
{
GUI.DrawTexture(Rect( (Screen.width - CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].width) * 0.5, (Screen.height - CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].height) * 0.5, CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].width, CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].height), CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)]); //Draw the HUD texture
}
}

Mathf.Round(Time.timeSinceLevelLoad) is just bigger CountdownTextures array size.
Maybe try adding this:
Debug.Log("Index: "+Mathf.Round(Time.timeSinceLevelLoad)+", Array size: "+ CountdownTextures.Length);
And you should see that index is bigger than size.
You can also add kind of safety check inside if, something like this:
if(Mathf.Round(Time.timeSinceLevelLoad) < CountdownTextures.Length && <your second statement>)

Related

Why can't these gameobjects instantiate in Unity3D?

In the below code snippet I'm trying to instantiate gameobjects at different probability rates but I keep on getting the following error:
No appropriate version of 'UnityEngine.Object.Instantiate' for the argument list '(Spawn06[])' was found.
The help would be much appreicated. Thanks.
public var Characters : Spawn06[];
function SpawnCharacters() {
var i = Random.Range(0, 100);
for(var j = 0; j < Characters.Length; j++) {
if(i >= Characters [j].minProbabilityRange && i <= Characters [j].maxProbabilityRange) {
temp = Instantiate(Characters);
pos = temp.transform.position;
temp.transform.position = new Vector3(Random.Range(-3, 4), pos.y, pos.z);
}
}
}
public class Spawn06 {
public var spawnCharacters : GameObject;
public var minProbabilityRange : int = 0;
public var maxProbabilityRange : int = 0;
}
You can't pass your an array of your class to Instantiate.
for(var j = 0; j < Characters.Length; j++) {
if(i >= Characters [j].minProbabilityRange && i <= Characters [j].maxProbabilityRange) {
temp = Instantiate(Characters[j].spawnCharacters); // Pass a GameObject instead of an Array of Spawn06
pos = temp.transform.position;
temp.transform.position = new Vector3(Random.Range(-3, 4), pos.y, pos.z);
}
}
}

Unity - Change cube color before placement

So, I am making a Minecraft-like game, and you basically move around on a pre-generated floor and place blocks. My problem is that I need to get the ability for the player to change the block color by hitting a numberpad key, ex: 1 for red, 2 for blue, and so on.
Here is the script that generates the floor, and handles block placement.
var range : float = Mathf.Infinity;
var hit : RaycastHit;
for (var y = -4; y < 50; ++y)
for (var x = -4; x < 50; ++x) {
var block : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
block.transform.position = transform.position + Vector3(x, -3, y);
}
function Update () {
if (Input.GetMouseButtonDown(0) && Hit()) {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hit.transform.position + hit.normal;
}
if (Input.GetMouseButtonDown(1) && Hit())
Destroy(hit.transform.gameObject);
if (Input.GetKeyDown(KeyCode.Keypad1)) {
cube.renderer.material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.Keypad2)) {
cube.renderer.material.color = Color.blue;
}
if (Input.GetKeyDown(KeyCode.Keypad3)) {
cube.renderer.material.color = Color.yellow;
}
if (Input.GetKeyDown(KeyCode.Keypad4)) {
cube.renderer.material.color = Color.green;
}
if (Input.GetKeyDown(KeyCode.Keypad5)) {
cube.renderer.material.color = Color.magenta;
}
}
function Hit() : boolean {
return Physics.Raycast(transform.position, transform.forward, hit, range, 1);
}

Unity game engine having camera follow script transform change depending on car selected script?

OVERALL GOAL: Have the camera change target to the selected car
I'm new to the unity game engine and got a bit of a problem.
So, I have a successful car selector which changes between cars and starts the match with that car. Everything there works. The only issue is that my "CarCameraScript" has a transform variable which is always 1 of the 3 cars. I want it to change dependant on the selected car.
Here is the look at the code of the CarCameraScript
#pragma strict
var car : Transform;
var distance: float = 6.4;
var height: float = 1.4;
var rotationDamping : float = 3.0;
var heightDamping: float = 2.0;
var zoomRatio : float = 0.5;
var DefaultFOV : float = 60;
private var rotationVector : Vector3;
function Start () {
}
function LateUpdate () {
var wantedAngel = rotationVector.y;
var wantedHeight = car.position.y + height;
var myAngel = transform.eulerAngles.y;
var myHeight = transform.position.y;
myAngel = Mathf.LerpAngle(myAngel,wantedAngel,rotationDamping*Time.deltaTime);
myHeight = Mathf.Lerp(myHeight,wantedHeight,heightDamping*Time.deltaTime);
var currentRotation = Quaternion.Euler(0,myAngel,0);
transform.position = car.position;
transform.position -= currentRotation*Vector3.forward*distance;
transform.position.y = myHeight;
transform.LookAt(car);
}
function FixedUpdate () {
var localVilocity = car.InverseTransformDirection(car.rigidbody.velocity);
if (localVilocity.z<-0.5) {
rotationVector.y = car.eulerAngles.y + 180;
} else {
rotationVector.y = car.eulerAngles.y;
}
var acc = car.rigidbody.velocity.magnitude;
camera.fieldOfView = DefaultFOV + acc*zoomRatio;
}
This is what it looks like on the side panel.
http://i.stack.imgur.com/lYJP7.jpg
The area that says none (transform) is the place that should be variable dependant on the currently selected car.
Now, Here is my other script being the CharacterSelectScript
#pragma strict
//this is the currently selected Player. Also the one that will be saved to PlayerPrefs
var selectedPlayer : int = 0;
function Update()
{
if (Input.GetMouseButtonUp (0)) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
// The pink text is where you would put the name of the object you want to click on (has attached collider).
if(hit.collider.name == "Player1")
SelectedCharacter1(); //Sends this click down to a function called "SelectedCharacter1(). Which is where all of our stuff happens.
if(hit.collider.name == "Player2")
SelectedCharacter2();
if(hit.collider.name == "Player3")
SelectedCharacter3();
}
else
{
return;
}
}
}
function SelectedCharacter1() {
Debug.Log ("Character 1 SELECTED"); //Print out in the Unity console which character was selected.
selectedPlayer = 1;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter2() {
Debug.Log ("Character 2 SELECTED");
selectedPlayer = 2;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter3() {
Debug.Log ("Character 3 SELECTED");
selectedPlayer = 3;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
How would I get it so that the SelectedPlayer changes the transform in the first script?
Any ideas?
I also have the prefab script which probably isnt important.
Also, should I join both scripts into one?
OVERALL GOAL: Have the camera change target to the selected car

Starling on iOS - Touch event handler "dies off"

I have a method that applies force to a ball in Box2d.
Testing it locally on desktop it works fine, but on iPad (ios7)
the method get executed only until the half!
I never came accross such a weird error, what is wrong here:
function onTouch(e:TouchEvent) {
var touch:Touch = e.getTouch(this) as Touch;
if (touch && touch.phase == TouchPhase.ENDED) {
//do something
_debugT.text = "works";
var mouseX_m:Number = touch.globalX;
var mouseY_m:Number = touch.globalY;
_debugT.text = "stops here...";
var xDiff:Number = mouseX_m - (_whiteBall.GetPosition().x * WORLD_SCALE);
var yDiff:Number = mouseY_m - (_whiteBall.GetPosition().y * WORLD_SCALE);
var angle:Number = Math.atan2(yDiff, xDiff);
var angleDeg:Number = angle * 180 / Math.PI;
_debugT.text = "never gets executed"
var len = Math.sqrt((xDiff * xDiff) + (yDiff * yDiff));
var vx = len * Math.cos(angle);
var vy = len * Math.sin(angle);
var vel = _whiteBall.GetLinearVelocity();
vel.x += (vx * 5);
vel.y += (vy * 5);
var force = new b2Vec2(vel.x, vel.y);
_whiteBall.SetAwake(vel);
_whiteBall.SetLinearVelocity(force);
}
}
To me it looks like Multitouch.inputMode = MultitouchInputMode.GESTURE; causes this problem.
I had the same issue and commented out this line and it works now.

Easeljs: Displayobject ontick event not work in for loop

i'm a newbie and i'm terrible at english but hopefully you can understand my problem
i create a simple space shooting game with easeljs, when i tried to create multiple bullets and assign an onTick handle to each one, i relize just one bullet fire out. Here is the code:
//handle fire(shooting)
if(fire && cd === 0){
for(var i=0; i<5; i++){
//codartjs.Bullet is a class extend createjs.Bitmap
var b = new codartjs.Bullet(bullet_img);
b.x = 200;
b.y = 200;
stage.addChild(b);
b.onTick = function(){
//this event handler work for only first instance
b.y -= 10;
};
}
cd = 100;
setTimeout(function(){
cd = 0;
},100);
}
What you can also try is having a central ticker and loop through each bullet element and update its position that way. Here is quick demo that will illustrate my point.
<script>
var canvas, stage;
var bullets;
var speed;
function init() {
stage = new createjs.Stage("test");
bullets = [];
var bg = new createjs.Shape();
bg.graphics.beginFill("#FFFFFF").drawRect(0, 0, stage.canvas.width, stage.canvas.height).endFill();
bg.cache(0, 0, stage.canvas.width, stage.canvas.height);
speed = 15;
stage.onClick = handleClick;
stage.mouseEnabled = true;
stage.enableMouseOver(10);
createjs.Ticker.setFPS(24);
stage.addChild(bg);
createjs.Ticker.addListener(window);
}
function getSprite() {
var s = new createjs.Shape();
s.graphics.beginFill("#000000").drawCircle(0, 0, 10).endFill();
return s;
}
function tick() {
for(var i=0;i<bullets.length;i++) {
var s = bullets[i];
s.x += speed;
}
stage.update();
}
function handleClick(event) {
var s = getSprite();
s.x = event.stageX;
s.y = event.stageY;
bullets.push(s);
stage.addChild(s);
}
</script>
Hope this helps.