Call Method script

Using Naninovel C# APIs: adding custom actor implementations or commands, overriding engine services, integrating with other systems, etc.
Post Reply
Alatriste
Posts: 11
Joined: 13 Aug 2023 21:38

Call Method script

Post 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;
    }
}
Elringus
admin
Posts: 530
Joined: 11 May 2020 18:03

Re: Call Method script

Post 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.

BigBenEco
Posts: 7
Joined: 24 Apr 2023 04:18

Re: Call Method script

Post by BigBenEco »

Very Cool!

Post Reply