对象未实例化(C#)

时间:2019-01-29 22:31:09

标签: c# unity3d instantiation

我正在Unity中编写塔防游戏,但在尝试找出放置塔的方法时遇到了麻烦。我的想法是,当玩家有一定数量的积分时,能够在游戏中单击某个美术资产,并用塔代替该美术资产。不幸的是,即使玩家拥有正确的分数,该对象也不会实例化。我已经确保将预制件链接到脚本,但是它不起作用。我很困惑,代码的逻辑看似正确,但也许有人可以帮我找出问题所在。

public class PointManager : MonoBehaviour
{

    public int pointCount;
    public Text pointDisplay;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        pointDisplay.text = "Points: " + pointCount;
    }
}

public class PlaceTower: MonoBehaviour
{

    public GameObject Tower;
    private GameObject firstTower;
    int placeCost = 25;
    private PointManager pointsGained;

    // Start is called before the first frame update
    void Start()
    {
        pointsGained = GameObject.FindGameObjectWithTag("Point").GetComponent<PointManager>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnMouseDown()
    {
        if (pointsGained.pointCount >= placeCost)
        {
            firstTower = Instantiate(Tower, transform.position, Quaternion.identity);
            //Destroy(this.gameObject);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我明白了。问题不在于我的代码,而是我的预制件。在文档中,我误解了OnMouseDown适用于具有碰撞对象的对象。当我在要实例化的对象上设置了一个圆碰撞器时,我没有在要实例化的对象上放置一个对撞机。这样可以立即解决问题。如果没有第二种意见,我将完全忽略一个简单的错误。谢谢,Pac0!

相关问题