我无法设法将公共对象添加到我的dcript中。 有代码:
public class Player : MonoBehaviour {
public string charName = "";
public int currentLevel = 0;
public int experiense = 0;
public int strength = 1;
public int agility = 1;
public int maxHealth = 30;
public float currentHealth = 30;
public int maxActionPoints = 5;
public int currentLevelPoints = 10;}
还有另一个脚本,我想在这个类中添加一个公共属性
public class CharManager : MonoBehaviour {
public GameObject currentCharacter;
public GameObject charMenu;
public Player currentPlayerStats;
public void changeCharacter(GameObject character)
{
if (currentCharacter){
saveCharacter ();
}
currentCharacter = character;
loadSavedInfo ();
}
void loadSavedInfo()
{
string playerJson = "";
if (currentCharacter.tag== "Man")
{
if (File.Exists(Application.persistentDataPath +"/Char1.json"))
{
playerJson = File.ReadAllText(Application.persistentDataPath +"/Char1.json");
}
}
else
{
if (File.Exists(Application.persistentDataPath +"/Char2.json"))
{
playerJson = File.ReadAllText(Application.persistentDataPath +"/Char2.json");
}
}
if (playerJson != string.Empty)
{
Player thePlayer = JsonConvert.DeserializeObject<Player>(playerJson);
currentPlayerStats = thePlayer;
}
else
{
currentPlayerStats = gameObject.AddComponent<Player>() as Player;
}
}
此代码添加新播放器组件,currentPlayerStats具有类CharManager ...我做错了什么? 任何帮助非常感谢!
答案 0 :(得分:1)
gameObject.AddComponent()将MonoBehaviour派生组件添加到游戏对象中。玩家不是从MonoBehaviour派生的,因此无法添加
看起来Player只是一个普通的类,所以你可以创建该类的对象
Player currentPlayerStats = new Player();
答案 1 :(得分:0)
我明白了。 Player类必须是非MonoBehaviour类。我必须访问玩家类的类应该有一个公共属性:
public Player thePlayer;
不是
public GameObject thePlayer;
谢谢大家!