Passing a script in a method parameter automatically

Hi !

As I want to make the shortest and smartest code possible, something is disturbing me.

I want my function to be called like an extension method, so I don’t need to put in parameter my own script. Here is an example:

public static void ResetTransformation(this Transform trans)
{
    trans.position = Vector3.zero;
    trans.localRotation = Quaternion.identity;
    trans.localScale = new Vector3(1, 1, 1);
}

Then you call the function with:

transform.ResetTransformation();

So you don’t need to pass the Transform variable in parameter

How could I do this with my own code?

[ServerRpc]
public static void SpawnObjectServer(this PlayerSpawnObject script, Transform playerTransform, GameObject objectToSpawn)
{
    Debug.Log($"Spawning an object from {script.name} player");

    GameObject spawned = Instantiate(objectToSpawn, playerTransform.position + playerTransform.forward * 2 + Vector3.up, Quaternion.identity);
    ServerManager.Spawn(spawned);
    SetSpawnedObject(script, spawned);
}

By calling this from PlayerSpawnObject.cs:

SpawnObjectServer(transform, objectToSpawn);

The two functions are on the same script.

Thanks for your help!

In this situation you need to qualify the method with the this keyword:


  this.SpawnObjectServer(transform, objectToSpawn);

Or if the calling method is static, then you have to qualify it with the type name:


  PlayerSpawnObject.SpawnObjectServer(script, transform, objectToSpawn);