You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2D中如何从另一个函数访问已实例化的GameObject

解决"The name 'newObject' does not exist in the current context"错误

你遇到的问题是变量作用域导致的:newObject是在thisFunction()方法内部声明的局部变量,它的作用范围只限于这个方法内部,Update()方法根本访问不到它,所以会报错。

解决方法很简单,把newObject提升为类的成员变量,让整个类的方法都能访问到:

  • 在类的顶部成员变量区域声明newObject
  • 在thisFunction()里直接给它赋值,不用再重新声明类型
  • 额外建议:在Update()里先判断newObject是否不为null,避免实例化失败后出现空引用异常

修改后的完整代码:

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

public class Deletenow : MonoBehaviour
{
    public Transform Player;
    public GameObject myObject;
    public Vector2 thisVector;
    // 提升为类成员变量
    private GameObject newObject;

    void Start()
    {
        thisFunction();
    }

    void Update()
    {
        // 先判断非空,避免空引用报错
        if (newObject != null)
        {
            thisVector = newObject.transform.position;
        }
    }

    public void thisFunction()
    {
        // 直接赋值,不用再声明GameObject
        newObject = Instantiate(myObject, Player.transform.position, Player.rotation);
    }
}

内容的提问来源于stack exchange,提问作者Asker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:50:27