简体   繁体   English

如何使克隆的游戏对象成为全局对象,以便可以在Unity功能之外使用它们?

[英]How do I make my cloned game objects global, so I can use them outside of the function in Unity?

I just recently got into Unity 3D and currently working on one of my first own projects. 我最近刚接触Unity 3D,目前从事我自己的第一个项目。 For the game im making, I need a spawner function, that respawns a clone of the enemy as soon as the enemy falls off the platform. 对于即时游戏,我需要一个生成器功能,当敌​​人从平台上掉下来时,它会重新生成敌人的克隆。 This is the code I have right now: 这是我现在拥有的代码:

using UnityEngine;

public class spawner : MonoBehaviour
{
    public GameObject enemyPrefab;
    public float spawnHeight = 0.75f;

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

    // Update is called once per frame
    void Update()
    {
        if (enemyClone.transform.position.y < -10)
        {
            Destroy(enemyClone);
            spawnEnemy();
        }
    }

    public void spawnEnemy()
    {
        var enemyPosition = new Vector3(Random.Range(-5, 5), spawnHeight, Random.Range(-5, 5));
        var enemyClone = Instantiate(enemyPrefab, enemyPosition, Quaternion.identity);
    }
}

The function spawnEnemy itself works fine, since it creates an enemy on game start, tho further enemies aren't spawned. spawnEnemy函数本身可以正常工作,因为它会在游戏开始时创建一个敌人,因此不会再产生其他敌人。 I get the message: "Assets\\spawner.cs(21,21): error CS0103: The name 'enemyClone' does not exist in the current context". 我收到消息:“ Assets \\ spawner.cs(21,21):错误CS0103:名称'enemyClone'在当前上下文中不存在”。

I do see why I get the message, don't know how to make enemyClone globally available however. 我确实知道为什么收到消息,但是不知道如何使敌人克隆在全球范围内可用。

Thanks to everybody in advance, 提前感谢大家,

bezunyl bezunyl

In the spawnEnemy() function, you say var enemyClone = Instantiate(...); spawnEnemy()函数中,您说var enemyClone = Instantiate(...); . enemyClone is a local variable that can only be used within the spawnEnemy function, or at least that's how you've written it. evilClone是一个局部变量,只能在spawnEnemy函数内使用,或者至少这就是您编写它的方式。

If you want to use the enemyClone outside of the spawnEnemy function, you need to declare the enemyClone variable outside of the function. 如果要在spawnEnemy函数之外使用敌人spawnEnemy ,则需要在函数外部声明敌人克隆变量。 (The example below will work if you DON'T want enemyClone to be accessible to other GameObjects) (如果您不希望其他游戏对象可以访问敌人克隆,那么下面的示例将起作用)

using UnityEngine;

public class spawner : MonoBehaviour
{
    public GameObject enemyPrefab;
    public float spawnHeight = 0.75f;

    private GameObject enemyClone //Added to allow enemyClone to be used anywhere in the class

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

    // Update is called once per frame
    void Update()
    {
        if (enemyClone.transform.position.y < -10)
        {
            Destroy(enemyClone);
            spawnEnemy();
        }
    }

    public void spawnEnemy()
    {
        var enemyPosition = new Vector3(Random.Range(-5, 5), spawnHeight, Random.Range(-5, 5));
        enemyClone = Instantiate(enemyPrefab, enemyPosition, Quaternion.identity);
    }
}

Now if you want enemyClone to be accessible by other GameObjects, then you'll want to make the enemyClone variable public instead of private . 现在,如果您希望其他游戏对象可以访问敌人克隆,那么您将需要使enemyClone变量成为public而不是private If you don't want it to show up in the inspector, add [HideInInspector] above the declaration of enemyClone, as shown below: 如果您不希望它显示在检查器中,请在[HideInInspector]的声明上方添加[HideInInspector] ,如下所示:

[HideInInspector]
public GameObject enemyClone;

Your issue is based on scope . 您的问题基于scope You might want to research it, it's important to know. 您可能需要研究它,知道这一点很重要。

The scope of a variable determines its visibility to the rest of a program. 变量的范围决定了其对程序其余部分的可见性。

http://www.blackwasp.co.uk/CSharpVariableScopes.aspx http://www.informit.com/articles/article.aspx?p=1609145&seqNum=4 http://www.blackwasp.co.uk/CSharpVariableScopes.aspx http://www.informit.com/articles/article.aspx?p=1609145&seqNum=4

Spawning GameObject on demand is expensive. 按需生成GameObject非常昂贵。 Instead of spawning it everytime, you should pool the GameObject. 而不是每次都生成它,您应该合并GameObject。

public class Spawner : MonoBehaviour {
    public Enemy enemyPrefab;
    public List<Enemy> enemyPool;
    public const SPAWN_HEIGHT = 0.75f;

    // Start is called before the first frame update
    void Start()
    {
        enemyPool = new List<Enemy>();
        spawnEnemy();
    }

    // Update is called once per frame
    public void Despawn(Enemy deadEnemy)
    {
        deadEnemy.gameObject.SetActive(false);
        enemyPool.Add(deadEnemy);
    }

    public void spawnEnemy() {
        Enemy newEnemy;
        if (enemyPool.Count > 0) {
            newEnemy = enemyPool[0];
            enemyPool.Remove(0);
        } else {
            newEnemy = Instantiate(enemyPrefab);
        }
        newEnemy.Init(this);

        newEnemy.position =  new Vector3(Random.Range(-5, 5), SPAWN_HEIGHT, Random.Range(-5, 5));
        newEnemy.gameObject.SetActive(true);
    }
}

public class Enemy : MonoBehaviour {
    private Spawner spawner;
    private const float DEATH_POSITION_Y = -10;

    public void Init(Spawner spawner) {
        this.spawner = spawner;
    }

    void Update() {
        if (transform.position.y < DEATH_POSITION_Y) {
            spawner.Despawn(this);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#Unity-当我在游戏中单击空格键时,如何启用“ PlayerMovement”脚本和“使用重力”复选框(刚体)? - C# Unity - How do I make my “PlayerMovement” script and “Use Gravity” checkbox (rigidbody) enable when I click SPACEBAR in game? 如何链接我的C#脚本,以便项目数影响Unity游戏中的得分? - How can I link my C# scripts so that item count influences score in my Unity game? 重新加载游戏场景时,对象不会统一加载 - When I reload my game scene the objects do not reload in unity 我正在努力让我的 Unity 游戏在游戏结束后重新启动 - I am trying to make it so that my Unity game restarts after the game has ended 我如何确保 Unity 可以找到我的游戏 object 而不会返回 Null? 问题是在调用之前初始化 object - How do I make sure that Unity can find my game object without it returning as Null? Problem is with initializing the object before calling it Enterprise Architect:如何添加我包含的程序集 (C# .NET 4) 以便我可以使用它们? - Enterprise Architect: How do I add my included assemblies (C# .NET 4) so I can use them? 如何在 Unity 中启用和禁用多个游戏对象? - How do I enable and disable multiple game objects in Unity? 如何存储对象列表的初始状态,以便可以将它们与更新的列表进行比较? - How do I store the initial state of a list of objects so that I can compare them to an updated list? 在 Unity 中与游戏对象发生碰撞时,如何让我的玩家加速? - How do I make my player speed up when collide with a game object in Unity? 如何在 Unity 2d 中为我的乒乓球比赛得分 - How can I make score in Unity 2d for my pong game
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM