Jho*_*per 2 instantiation unity-game-engine
我有一个武器,我想实例化一个对象(在本例中是子弹),然后等到该子弹击中一个对象后,才允许该武器实例化另一个对象。
我目前正在通过在武器脚本上添加以下内容来做到这一点:
public class weaponScript : MonoBehaviour
{
public gameobject projectilePrefab;
public bool launchable;
void Update{
if(launchable){
Instantiate(projectilePrefab, firePoint.transform.position, transform.rotation);
launchable = false;
}
}
Run Code Online (Sandbox Code Playgroud)
子弹脚本上是这样的:
public class projectile : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D other){
weaponScript.launchable = true;
}
}
Run Code Online (Sandbox Code Playgroud)
这非常适合我的需要,但是这不起作用,因为射弹没有定义weaponScript,因此它无法launchable将 上的变量设置weaponScript为 true。
我可以使用 FindObjectOdType() 函数,当场景中有一种武器时,该函数就可以工作,但是一旦场景中一次有多个 WeaponScript,您就开始难以确定谁是谁。
有没有办法让 WeaponScript 在实例化对象时将自身设置为变量,如下所示:
public class weaponScript : MonoBehaviour
{
public gameobject projectilePrefab;
public bool launchable;
void Update{
if(launchable){
Instantiate(projectilePrefab, firePoint.transform.position, transform.rotation);
[InstanciatedObjectHere].parentWeapon = this.gameobject;
launchable = false;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,弹丸所要做的就是:
public class projectile : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D other){
parentWeapon.launchable = true;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道 Pastebin 不会永远保留脚本,所以我将把答案作为编辑放在这里:(而且它让其他可能偶然发现这个的人更容易阅读)
我遵循了 Peridis 的答案,但它并没有立即起作用,所以我最终调整了它并想出了这个:
public class weaponScript : MonoBehaviour
{
public gameobject projectilePrefab;
public bool launchable;
private projectile projectileScript;
void Update{
if(launchable){
GameObject projectileIntantiated = Instantiate(projectilePrefab, firePoint.transform.position, transform.rotation);
projectileScript = projectileIntantiated.GetComponent<projectile>();
projectileScript.parentWeapon = this.gameObject.GetComponent<weaponScript>();
launchable = false;
}
}
public class projectile : MonoBehaviour
{
public weaponScript parentWeapon;
void OnCollisionEnter2D(Collision2D other){
parentWeapon.launchable = true;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢佩里迪斯的帮助!
您可以在实例化射弹时创建 GameObject 类型的变量
GameObject projectileIntantiated = Instantiate(projectilePrefab, firePoint.transform.position, transform.rotation);
projectileIntantiated.GetComponent<projectile>().parentWeapon = this.gameobject;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6588 次 |
| 最近记录: |