Call Method script

Posted: 31 Aug 2023 16:22
by Alatriste

Hi, I asked ChatGPT to create a custom commando for Naninovel that can run methods for a given gameObject in the scene. Guess what, it works perfectly fine. So here it is just in case someone need it.

The sintaxis is:

Code: Select all

@callMethod GameObjectName:[gameObject] ScriptName:[ScriptName] MethodName:[MethodName]

Code: Select all

using Naninovel;
using Naninovel.Commands;
using UnityEngine;

[CommandAlias("callMethod")]
public class CallGameObjectMethod : Command
{
    public StringParameter GameObjectName;
    public StringParameter ScriptName;
    public StringParameter MethodName;

    public override async UniTask ExecuteAsync(AsyncToken asyncToken = default)
    {
        Debug.Log("callMethod: Command started.");

        if (!Assigned(GameObjectName) || !Assigned(ScriptName) || !Assigned(MethodName))
        {
            Debug.LogError("callMethod: Parameters are not set.");
            return;
        }

        GameObject targetGameObject = GameObject.Find(GameObjectName);

        if (targetGameObject == null)
        {
            Debug.LogError($"callMethod: GameObject '{GameObjectName}' not found.");
            return;
        }

        Debug.Log($"callMethod: Found GameObject '{GameObjectName}'.");

        Component scriptComponent = targetGameObject.GetComponent(ScriptName);


        MonoBehaviour monoBehaviour = scriptComponent as MonoBehaviour;
        
        System.Reflection.MethodInfo methodInfo = monoBehaviour.GetType().GetMethod(MethodName);

        methodInfo.Invoke(monoBehaviour, null);

        await UniTask.CompletedTask;
    }
}

Re: Call Method script

Posted: 31 Aug 2023 18:31
by Elringus

Thanks for sharing! Just be aware, that GameObject.Find and reflection are slow. It may be ok if the command is not invoked frequently.


Re: Call Method script

Posted: 06 Sep 2023 16:19
by BigBenEco

Very Cool!