0

Basically is there an actually time saving way to creat a function that lets you create a GameObject specified by the function's parameter(s)?

like:

public void thing_maker(string gameobject_name, string sprite_name, string rg_body_name)
novasniff
  • 13
  • 2
  • Yup, you can either call `new GameObject()` (which will create a blank, empty GameObject) to which you might add components to (via `AddComponent()`) or call [`UnityEngine.Object.Instantiate(gameObjectToCopy)`](http://docs.unity3d.com/ScriptReference/Object.Instantiate.html) which will create a copy. You can also instantiate prefabs at runtime. Some detailed information here: http://docs.unity3d.com/Manual/InstantiatingPrefabs.html – Chris Sinclair Sep 06 '15 at 21:51
  • Great, but can you specify the `GameObject()`'s name from an argument `thing_maker()`? Like calling `thing_maker(go_player, sprt_player, rgdbdy_player)` Will create a gameobject with the name go_player, a sprite called sprt_player, etc. – novasniff Sep 06 '15 at 22:35
  • 1
    Sure, just check [the docs](http://docs.unity3d.com/ScriptReference/GameObject-ctor.html). You have to add the components yourself or instantiate a prefab, but what's stopping you from trying to implement this method? – 31eee384 Sep 06 '15 at 23:45

2 Answers2

1

this example should do what you need. it requires that you have a folder named Resources and that the sprite you want to load will be inside that folder.

another option is doing GameObject go = Instantite(SomePrefabName) as GameObject insted of new GameObject(), in case you have a prefab which is ready and you only want to maybe change some of its components' values.

Good luck.

public GameObject thing_maker(string gameobject_name, string sprite_name, string rg_body_name)
{
    GameObject go = new GameObject(gameobject_name);
    SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
    sr.sprite = Resources.Load<Sprite>(sprite_name);
    Rigidbody rb = go.AddComponent<Rigidbody>();

    /* now if you want to change values of the components you can just do it
       by accesing them directly. for instance: rb.isKinematic = true; will
       change the isKinematic value of this rigidbody to true. */

    return go;
}
Chaos Monkey
  • 964
  • 1
  • 6
  • 18
1

It seems to me that you could try something like this:

public void ThingMaker(string gameobject_name, Sprite spriteToDraw) {
    GameObject newObj;
    newObj= new GameObject(gameobject_name);
    newObj.AddComponent<Rigidbody2D>(); 
    newObj.AddComponent<SpriteRenderer>();
    newObj.GetComponent<SpriteRenderer>().sprite = spriteToDraw;
}
Anton Voronin
  • 98
  • 1
  • 6