unity3d脚本调用脚本_从Unity 3D中的其他行为脚本中调用方法

unity3d脚本调用脚本

In this tutorial we will learn how we can call a public method defined in one script from any other script attached to different gameObject.

在本教程中,我们将学习如何从附加到不同gameObject的任何其他脚本中调用一个脚本中定义的public方法。

One way to do so is by using the static method which we saw and used in our last tutorial, but that is not the right way.

一种方法是使用在上一教程中看到和使用的static方法,但这不是正确的方法。

Unity 3D:从其他脚本调用方法 (Unity 3D: Call a method from other Script)

Lets define a new behaviour class with name FirstScript

让我们定义一个名称为FirstScript的新行为类

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

public class FirstScript : MonoBehaviour
{
    
    void Start()
    {
        // some code
    }
    
    void Update() 
    {
        // some code
    }
    
    public void SayHello()
    {
        Debug.Log("Hey there!");
    }

}

Now lets define our second class with name SecondScript and call the method doSomething() defined in the first script in the second.

现在让我们用名字SecondScript定义我们的第二个类,并在第二个脚本中调用第一个脚本中定义的doSomething()方法。

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

public class SecondScript : MonoBehaviour
{
    public FirstScript first;
    
    void Start()
    {
        // some code
    }
    
    void Update() 
    {
        // calling SayHello() method every frame
        first.SayHello();
    }

}

Hey there! Hey there! Hey there! ...

嘿! 嘿! 嘿! ...

It will keep on printing Hey there! in the console until the game is in play mode.

它将继续打印嘿! 在控制台中,直到游戏进入播放模式。

翻译自: https://www.studytonight.com/game-development-in-2D/unity-call-method-from-other-script

unity3d脚本调用脚本