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脚本调用脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值