c# - 为什么要将 (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) 的真正作用。
我应该使用哪一个,为什么?
解决方案
你不需要
您的示例可能来自Instantiate
始终返回的较旧 Unity 版本,Object
您必须通过(GameObject)
显式或不知道更好的人输入强制类型转换;)
Instantiate
也可作为通用(见页面底部)
public static T Instantiate<T>(T original);
并返回与给定预制件相同的类型...在您的情况下,它已经是GameObject
.
请注意,即使在他们自己的示例中(在底部),附加<Missile>
也是多余的,因为参数已经是 aMissile
并T
为此调用定义
你可以简单地打电话
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);
推荐阅读
- javascript - 元素不符合要求
- c++ - c++ std::initializer_list 和构造函数
- powershell - 如何将排序添加到 get-aduser powershell 脚本?
- tomcat - Tomcat 上的 HttpSession(活动会话)(newRelic 信息)
- android - 调试时 R.id.X 值错误
- javascript - 我的堆栈的 JavaScript 实现中的 Peek 方法未定义
- python - 定义接受字符串值的函数,在数据框列中搜索它,如果它在列中并且包含单词“Sales”,则返回 TRUE
- reactjs - 如何正确测试 Promise
- apache-nifi - 队列大小作为参数
- ios - UIAlertController 未按预期运行