Dynamically Created Object Management

This is my first post, so I’m going to try and keep it brief but also try and keep it as descriptive as possible.

Keep in mind that my scripts are written in c# and not Javascript, so I use an ArrayList as opposed to an Array.

What I’m trying to do is create objects on the fly, but also keep track of them and call on methods that are attached to them.

Say I have a prefab named DynamicObject with a script attached to it named DynamicObjectScript.

Within DynamicObjectScript there is a method named SayHello.

public void SayHello()
{
Debug.Log(“Hello”);
}

In another script I have a method which creates a DynamicObject and stores it in an array. The other script is attached to another GameObject in the level. The GameObject has an ArrayList named dynamicObjectArray. The method is as follows.

public void SpawnDynamicObject()
{
// create the dynamic object
// in the same position as the
// object creating it
GameObject go = Instantiate(m_beatNodeObject, transform.position, transform.rotation) as GameObject;

// store this object in an array
dynamicObjectArray.Add(bn);
}

Now for the problem. If I want to access the DynamicObjects from the array I have made a method like so.

public void AllSayHello()
{
// make sure array is populated
if(dynamicObjectArray.Count > 0)
{
// loop through all the objects in
// the array
for(int i = 0; i < dynamicObjectArray.Count; i++)
{
// create a variable to refer to
// the object
GameObject go = _m_beatNodes[0] as GameObject;
// call the PrintMe() method
go.GetComponent(“DynamicObjectScript”).PrintMe();
}
}
}

Doing this has only brought me errors.

‘UnityEngine.Component’ does not contain a definition for ‘PrintMe’

Any help would be greatly appreciated.

Thanks in advance.

Fyi,

If you don’t use bbcode code blocks then nobody is likely to answer your post. Code is just about impossible to read just pasted into the body of a message.

Hi I'm a code block!

Try changing this:

go.GetComponent("DynamicObjectScript").PrintMe();

to this:

YourClass thisComponent = go.GetComponent("DynamicObjectScript") as YourClass;
thisComponent.PrintMe();

(Disclaimer: I work in JS usually so my C# is not great. I think that one is right though.)

Sorry for not using code blocks. I’ll remember to use them in the future.
I changed my code over to Javascript and casted the scripts after calling get component and everything works fine now.

Thanks for the replies guys.