Global Function in C# in Unity (27977)

I’m trying to create a global function that creates game objects and attaches components based off of the type passed into the function, such as this code:

using UnityEngine;
using System.Collections;
using System;

//Global Function that Creates game object 
public class CreateGameObject
{
	public static void CreateNewGameObject(object newGameObject, Type gameObjectType, string gameObjectName)
	{
		GameObject go = new GameObject();
		gameObjectType = newGameObject.GetType();
		newGameObject = go.AddComponent<gameObjectType>();
		go.name = gameObjectName;
	}
}

I get this compiler error:
Error CS0246: The type or namespace name `gameObjectType’ could not be found. Are you missing a using directive or an assembly reference? (CS0246) (Assembly-CSharp)

The goal is to have a global function that takes in any object type and attaches a component based off its type.

I was wondering if someone could suggest something I’m doing fundamentally wrong here, I’m sure I am, I’m just a beginner and am not sure exactly myself. Thank you.

1 Answer

1

“I was wondering if someone could suggest something I’m doing fundamentally wrong here, I’m sure I am, I’m just a beginner and am not sure exactly myself. Thank you.”

What you’re doing fundamentally wrong here is that Type is not a variable, it’s a Type.

There is a way to do exactly what you want to do though, they’re called Generic function parameters. I didn’t understand the first parameter of your function, are you trying to clone a gameobject and attach a component? That’s what this’ll do:

public static void CreateNewGameObject< T >( GameObject go, string name) where T : Component
{
   GameObject newGo = Instantiate( go );
   newGo.AddComponent< T >();
   newGo.name = name;
}

You’d call this function like: CreateGameObject.CreateNewGameObject< Renderer >( this.gameObject, myClone ) which would clone this gameObject and add a renderer.

You have a point that it was sloppy not to declare a new variable for the new go, although it doesnt matter. And it would make more practical sense to return a reference to the new go, but I was trying to keep my example close to his.. ;) Now it doesnt matter for the gc, als go's do not get gc'd, you,have to explicitly call Destroy.