Home > Software design >  How to Create a Custom Unity Function
How to Create a Custom Unity Function

Time:09-23

Im trying to create a custom function in unity that performs setActive false but with Delay. Without Using Coroutine or Invoke Methods.

Im trying to create something like the Function Destroy in Unity: Destroy(Object obj, float time) But with SetActive.

What I am aiming for is a function like this SetActiveWithDelay(GameObject obj, bool stateToChange, float delayTime) with which we can write a line like SetActiveWithDelay(GameObjectToPass,true,2f) this which setActive the Gameobject to true by 2sec.

This can be easily done with Invoke or the use of Coroutine. But I just am curious about how to make a custom function this way. Makes things a lot simpler, instead of creating an IEnumerator and Using StartCoroutine or Invoke with string.

I looked into the object class on how Destroy was written and tried to replicate it. But it was confusing to me how it works. So, Let me know if anyone has any ideas on how to do this. Thanks!

Here below are some of the things I tried but again the custom function had a use of coroutine. But I feel this is all the same and I can directly use coroutine. So I'm interested to know if there is any other method or if going with coroutine and invoke is a better option. With Coroutine:

Gameobject GOToMakeFalse;

void Start()
{
//Aiming for a simplified Custom Function to write this way. With Does As it says make gameobject false after two seconds
   
SetActiveWithDelay(GOToMakeFalse,false, 2f);
}

SetActiveWithDelay(GameObject obj ,bool inState,float delayTime)
{
//But without using a coroutire like this here
   StartCoroutine(DelayedSetActive(obj,inState, delayTime));
}

public IEnumerator DelayedSetActive(GameObject GO,bool inBoolState, float dT)
{
   yield return new WaitforSeconds(dT);
   GO.SetActive(false);
}

And im also curious if we can extend the GameObject Class something like this. GameObject.SetActiveWithDelay(true,2f); Even this would be a cool addition and make development easy.

CodePudding user response:

You can use Async await or a simple timer script if you don't want to use coroutines. For Async you need to add the namespace

using System.Threading.Tasks;

You can read more on how to delay using Async here.

CodePudding user response:

About extension, something like that should work:

public static class GameObjectExtensions
{
    public static void SetActiveWithDelay(this GameObject obj, bool inState, float delayTime)
    {
        // ...
    }
}

myGameObject.SetActiveWithDelay(true, 2f);

The important parts are the "static" class and the "this" in the first parameter of the static method.

  • Related