首页 > 解决方案 > 为什么要将 (GameObject) 放在实例化之前?

问题描述

所以我有这个脚本,它创建一个炮弹的实例,然后在你单击鼠标左键时对其施加力。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CannonControl : MonoBehaviour {

    public GameObject cannonBall;
    public GameObject cannonBallSpawn;

    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            GameObject cannonBallClone = Instantiate(cannonBall, cannonBallSpawn.transform.position, Quaternion.identity);
            cannonBallClone.GetComponent<Rigidbody>().AddForce(cannonBallSpawn.transform.forward * 2000); 
        }
    }
}

在许多教程中,人们会使用(GameObject)Instantiate

GameObject cannonBallClone = (GameObject)Instantiate(cannonBall, cannonBallSpawn.transform.position, Quaternion.identity);

我两种方式都试过了,看不出有什么区别。我也找不到(GameObject) 的真正作用。

我应该使用哪一个,为什么?

标签: c#unity3d

解决方案


你不需要

您的示例可能来自Instantiate始终返回的较旧 Unity 版本,Object您必须通过(GameObject)显式或不知道更好的人输入强制类型转换;)

Instantiate也可作为通用(见页面底部)

public static T Instantiate<T>(T original);

并返回与给定预制件相同的类型...在您的情况下,它已经GameObject.

请注意,即使在他们自己的示例中(在底部),附加<Missile>也是多余的,因为参数已经是 aMissileT为此调用定义

你可以简单地打电话

GameObject cannonBallClone = Instantiate(cannonBall, cannonBallSpawn.transform.position, Quaternion.identity);

GetComponent这是一个额外的提示:如果您立即制作正确类型的预制字段,您可以摆脱调用

public Rigidbody cannonBall;
public Transform cannonBallSpawn;

这也确保您只能引用实际附加了所需组件的对象/预制。然后你可以短一点的电话

// will now return a Rigidbody instead
var cannonBallClone = Instantiate(cannonBall, cannonBallSpawn.position, Quaternion.identity);
cannonBallClone.AddForce(cannonBallSpawn.forward * 2000); 

推荐阅读