我是游戏编程和 C# 的新手,但我有一些 javaScript 和 PHP 的编程经验。
好的,我们开始吧,我有一个 C# 脚本,我想用它来生成怪物。我在 Youtube 上一直关注 Tom Adamson,直到他开始生成随机值,在这里可以看到:UNITY3D C# with Tom Adamson
这是我的脚本:
using UnityEngine;
using System.Collections;
public class myMonster : MonoBehaviour {
public class aMonster {
//The properties
public int id;
public int age;
public string name;
public string race;
public int health;
//A method
public void monsterData() {
print("ID: " + id);
print("Race: " + race);
print("Name: " + name);
print("Age: " + age);
print("Health: " + health);
}
} // End of class definition
//-----------------------------------------------------------------------------------------
void Start () {
aMonster[] bigMonster = new aMonster[51];
for (int i = 1; i <= 50;) {
bigMonster[i] = new aMonster();
bigMonster[i].id = i;
bigMonster[i].name = "Gorky";
bigMonster[i].race = "Orc";
bigMonster[i].age = 320;
bigMonster[i].health = 200;
i++;
bigMonster[i] = new aMonster();
bigMonster[i].id = i;
bigMonster[i].name = "Runathu";
bigMonster[i].race = "Shaman";
bigMonster[i].age = 670;
bigMonster[i].health = 100;
i++;
}
for (int i = 1; i <= 2; i++) {
bigMonster[i].monsterData();
}
}
}
当我只有 2 个怪物时,这可以正常工作,但是当我尝试添加第三个怪物时,我收到此错误:
IndexOutOfRangeException:数组索引超出范围。(wrapper stelemref) object:stelemref (object,intptr,object) myMonster.Start () (at Assets/myMonster.cs:50)
我添加了这样的第三个怪物:
bigMonster[i] = new aMonster();
bigMonster[i].id = i;
bigMonster[i].name = "Gorky";
bigMonster[i].race = "Orc";
bigMonster[i].age = 320;
bigMonster[i].health = 200;
i++;
bigMonster[i] = new aMonster();
bigMonster[i].id = i;
bigMonster[i].name = "Runathu";
bigMonster[i].race = "Shaman";
bigMonster[i].age = 670;
bigMonster[i].health = 100;
i++;
bigMonster[i] = new aMonster();
bigMonster[i].id = i;
bigMonster[i].name = "Tiny";
bigMonster[i].race = "Spider";
bigMonster[i].age = 90;
bigMonster[i].health = 45;
i++;
谁能告诉我我做错了什么?我想 i++ 是错误的做法,因为第三个怪物导致了错误。
任何帮助深表感谢。