【问题标题】:Add custom object to the script将自定义对象添加到脚本
【发布时间】:2017-12-19 16:49:28
【问题描述】:

我只是无法将公共对象添加到我拥有的 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...我做错了什么? 非常感谢任何帮助!

【问题讨论】:

  • 从您在此处复制的代码看来,Player 类不应该是 MonoBehaviour..?它只保存统计值,也许试着让它不是 MonoBehaviour ?
  • 我确实尝试过这样做。那么我怎么能从另一个脚本中获取这个属性呢? GetComponent 不起作用。

标签: c# json object unity3d


【解决方案1】:

gameObject.AddComponent() 将 MonoBehaviour 派生组件添加到游戏对象。播放器不是从 MonoBehaviour 派生的,因此无法添加

看起来 Player 只是一个普通的类,所以你可以创建一个该类的对象

Player currentPlayerStats = new Player();

【讨论】:

  • 公共类播放器:MonoBehaviour。所以它是派生MonoBehaviour。
  • 我不敢相信我没有看到,我检查了三次,非常抱歉。但现在我看不出有什么问题。
  • 完全没问题。我确实解决了。感谢您的回复!
【解决方案2】:

我想通了。 Player 类必须是非 MonoBehaviour 类。我必须访问播放器类的类应该有一个公共属性:

public Player thePlayer;

不是

public GameObject thePlayer;

谢谢大家!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多