Unity如何同时调用另一个脚本的函数和变量

之前用脚本调用另一个脚本的变量我都是用简单的static变量来解决的,但是今天看unity官方教程的时候发现可以同时调用

另一个脚本的函数和变量。自己尝试运行了一下,可是报错了。好尴尬 ̄□ ̄||

官方的代码是这样的:

    void Start ()
    {
        alpha = 29;

        myOtherclass = new otherAccess();
        myOtherclass .FruitMachine (alpha ,myOtherclass .apples );
    }

……

此处省略一万字,要看源码的点下面链接:

https://blog.csdn.net/jennyhigh/article/details/81186595

查了一天的资料终于搞明白,有两个问题:一是:从MonoBehaviour继承过来的类,unity需创建实例才能调用。二是:Awake, Start, Update的时间周期问题。

这里非常感谢提供答案的小伙伴,这里贴出他们的解决链接:

https://blog.csdn.net/pdw_jsp/article/details/49924717(他写了原理,但是看了半天没看懂)

https://stackoverflow.com/questions/33577637/unity-test-tools-unit-test-with-gameobject-gives-you-are-trying-to-create-a-mon#comment54934619_33577806(在百度上查到的这个解答,给了我很好的解决方法,但是没有写完)如下图:

http://blog.sina.com.cn/s/blog_799860f90102vkvq.html(最后终于通过这篇文章把前两篇搞懂了)

所以,最后我的代码是:

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

public class test : MonoBehaviour {

    private otherAccess myOtherclass;
    public int alpha = 5;

    // Use this for initialization
    void Start () 
    {
        GameObject go=new GameObject ();
        go.AddComponent <otherAccess> ();
        myOtherclass = (otherAccess)go.GetComponent (typeof(otherAccess));
        myOtherclass.FruitMachine (alpha, myOtherclass.apples);
    }
    
    // Update is called once per frame
    void Update () {
    }
}

解释:C#使用MoboBehaviour必须要实例化,GameObject go=new GameObject ();

并且需要在新建的实例上用到, go.AddComponent <otherAccess> ();

最后要将应用到当前脚本,这句很重要: myOtherclass = (otherAccess)go.GetComponent (typeof(otherAccess));

只有他成功传递了,当前脚本才能正确调用函数和变量:myOtherclass.FruitMachine (alpha, myOtherclass.apples);

运行成功:

没有报错!!!

当然这里面有个隐藏的很关键的问题,就是刚才我们说到的第二点;

    void Start () 
    {
        apples = 1;
    }

    void Awake()

    {
        apples = 1;
    }

如果赋值是在Start里面完成,那么myOtherclass.apples是掉不到赋值后的数值的,而放在Awake里面则可以,因为

Awake是所有mono 调用start方法之前都会被调用的,这样可以避免某些调用的时候instance=null的情况。

看着好像很简单,其实花了好长时间才弄明白, 这也是基础不扎实的缘故吧!

加油ヾ(◍°∇°◍)ノ゙

猜你喜欢

转载自blog.csdn.net/jennyhigh/article/details/81187716
今日推荐