Passing arguments to a script

I am attempting to recreate a specific function from Game Maker called instance_create.

The original works in the following manner
instance_create(position_x, position_y, object_name);

which creates an object (clone of a prefab in Unity) at a specific x and y location in a 2d game.

I’ll sort out the details later, but how would I create the C# script in such a way as to accept the arguments in a single line as written? It doesn’t have to be specific to this case, I just need to know how to do it so I can make other scripts in a similar fashion as well, meaning I am able to just type

script_name(arg1, arg2, arg3, etc);

And have it carry out its function.

In a single line, you could do this by making a function that takes those parameters. You could make it a static function so it’s available anywhere.

//in the class SomeClass.cs
public static GameObject instance_create(float x, float y, string object_name) {
GameObject spawned = Instantiate<GameObject>(somePrefab);
spawned.transform.position = new Vector3(x, y, 0f);
spawned.name = object_name;
return spawned;
}

//anywhere else
SomeClass.instance_create(1f, 2f, "foobar");
2 Likes

That looks exactly like what I need. Time to test it out. Thanks!

Also note you probably want to make SomeClass static as well. That way there is just one copy of it, you don’t have to instantiate. Its often useful to make a static Tools class with some static methods you use in various places.

I’ve modified it as so, so I can pass the prefab name to the function. So far so good. How would I make the whole thing static?

I added “static” in between “public” and “class GM” and get an error, “Static class ‘GM’ cannot derive from type ‘MonoBehavior’. Static classes must derive from object”

Also, can I remove the void Start and void Update, as they will not be used?

public class GM : MonoBehaviour {
  public static GameObject instance_create(float x, float y, string object_name)
  {
  GameObject spawned = (GameObject)Instantiate(Resources.Load(object_name));
  spawned.transform.position = new Vector3(x, y, 0f);
  spawned.name = object_name;
  return spawned;
  }
  // Use this for initialization
  void Start () {
   
   }
 
   // Update is called once per frame
   void Update () {
   
   }
}