繁体   English   中英

Unity / C#:无法从另一个脚本访问 static 变量

[英]Unity / C#: Can't access static variable from another script

所以我有两个脚本:

渲染脚本:

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

public class RenderScript : MonoBehaviour
{
    public static int grid;
    void Start()
    {
        
    }

    void Update()
    {
        
    }
}

和 CreatureScript:

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

public class CreatureScript : MonoBehaviour
{
    void Start()
    {

    }

    
    void Update()
    {
        
    }

    public void Tick()
    {
        RenderScript.grid = 10;
    }
}

我想从 CreatureScript 中的 RenderScript 访问 static integer “网格”。

但是,在 CreatureScript 中,我收到一个错误 (CS0103),说“RenderScript”不存在。 为什么?

编辑:所以它似乎在 Unity 中工作,即使 VS 给我一个错误。 还是很烦人。

正确的方法是将您的 RenderScript 脚本放在一个单独的 object 上(以防我们破坏它)并使其成为 singleton。 (您也可以添加 DontDestoryOnLoad,这取决于您想如何使用它)。

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

public class RenderScript : MonoBehaviour
{
    public static RenderScript _instance;

    public int grid = 10;
    
    private void Awake()
    {
       if(!_instance)
          _instance = this;
       else
          Destroy(gameObject);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreatureScript : MonoBehaviour
{
    public void Tick()
    {
        RenderScript._instance.grid = 10;
    }
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM