Unity3D/C#: PEBKAC

As you can probably tell from these blog posts that I’m moving at a casual pace through Unity3D. The bits in between is me learning new things and trying to move from the Dark Basic Professional frame of mind and onto a Unity3D/C# one.

Stupid mistakes happen, like me trying to figure out when using an array why the hell I couldn’t take control of a second character controller. It just wasn’t making sense to me. As far as I was aware I was making arrays in the right fashion and using them properly and no syntax errors occurred in C#. Then I decided it’d be a good idea to check Unity3D’s console, “Array Index is out of range”. Also known as, the number you’re using for your array isn’t declared. I have 2 Arrays, but that doesn’t meant ‘array[2]’ is the second one, because ‘0’ is counted. So that’s why object #2 wouldn’t do anything.

So…how do you take control of multiple objects in Unity3D? Might as well post this in case it helps anybody else out there.

Everything I’m doing is inside of my GUI class.

Declare the array. With this you’ll see something I find beautiful about C#:

public Vector3 MoveChar { get; set; }

public CharacterController[] character;

In Dark Basic Pro, I wouldn’t be able to use an object as I would with a variable, like a string or a float. Sure you get User Defined Types in DBP, so you can have ‘dim char(20) as character’ but within that UDT you may have a collection of variables you might use to refer to an object later in the code, but you’re not using that actual object. In OOP with C#, it’s a different matter.

Now, you might wish to declare the highest index for that array (as it’s currently empty). You could write that in code. But because this is a public variable, it means it’ll show up in the editor and you can set the highest index there and not only that, but drag and drop the objects you want each array to refer to. As I’m using ‘character controllers’ you can only use objects with a ‘Character Controller’ physics component (which can be attached in the Unity3D editor).

The next bit of code should show how you might interact with it:

void MoveCharacter()
{

MoveChar = new Vector3(5, 5, 5);
character[1].Move(MoveChar);

}

This will just move the second character attached in the editor by ‘5’ on each axis. You’ll notice in the editor each part of the array is labelled in this format:

Element 0, Element 1, Element 2…

That should help you think about which object you’re reference to in code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s