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.
19 replies
Beginner problem with Classes
I am currently following the C# tutorial on w3schools.com and doing the exercises in Visual Studio at the same time so I can actually practice writing code a bit rather than just reading. The part of the tutorial I am stuck on is this bottom of this page on Classes: https://www.w3schools.com/cs/cs_classes_multi.php
I have created 2 separate .cs files in Visual Studio. The first contains the following code:
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); } } } and the second file contains the following code: class Car { public string color = "red"; } The error I am receiving is "The type or namespace 'Car' could not be found (are you missing a using directive or an assembly referece?)" I believe I have copied the tutorial code correctly and am unclear on why it isn't doing what it 'should'. My current thinking is that it's something about VS rather than the code. Any help gratefully received.
static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); } } } and the second file contains the following code: class Car { public string color = "red"; } The error I am receiving is "The type or namespace 'Car' could not be found (are you missing a using directive or an assembly referece?)" I believe I have copied the tutorial code correctly and am unclear on why it isn't doing what it 'should'. My current thinking is that it's something about VS rather than the code. Any help gratefully received.
115 replies