C#C
C#11mo ago
18 replies
CTMWood

(Beginner) Instantiate objects of a class at runtime

I am learning C# by following tutorials and practicing code in Visual Studio. I will be moving on to Unity at some point, but I want a firmer understanding of C# before I do that.

I can create classes and create objects of those classes in the code. eg:

class Enemy //define an 'enemy' class
{
int xLocation;
int yLocation;
string name;
}

Enemy enemy1 = new Enemy(); // create an enemy object (in Main of course)

This creates an object that I can use in various ways. (yes, I understand constructors and initialising the fields too, I'm just keeping it short)

But what if I want to create Enemy objects at runtime. ie lets say I get an input from the user and want to 'spawn' some enemies. In my mind this means I am instantiating objects at runtime rather than in the code.

Is my understanding wrong? All my searches point me to Unity tutorials which makes me think I am misunderstanding something, I don't want to use Unity just yet. Any pointers in the right direction greatly appreciated.
Was this page helpful?