I’m stuck with class/objects. Please read and help!


I’m new in C# and I’m so confused now! I tried to make a very basic program for practice but I’m stuck now.

I want to do a program where I can create units and these units have properties (ID, hp, speed, range etc…) like in a game. Later I wanna to write to screen the properties of the certain unit by its ID and may change them. I don’t wish to create a game as I can’t to do, just a game-like example for practice.

My problems:

1 – Don’t know how to create different instance of units. A class is working as a blueprint and I can create objects from them. But I’d like to create a lot of objects with the same initial properties except its ID which must be different of course as it will indicate the different units!

2 – Don’t know how to properly reach a method/variable from a different namespace. I tried it but I had to create a new object in the other namespace by “Class1 obj = new Class1();” but it’s not good as an object represent a unit and I don’t want to create new ones everywhere in the code…

3 – Don’t know how to modify the properties later. Imagine a game where you upgrade a type of unit and every NEW unit AFTER upgrade will have the new upgraded properties but the old ones still unchanged!

That’s it! I give my bad example as a base of the help. I’m a really beginner so please provide a new code or change/upgrade mine, but don’t be too complex please.

Thank you!

using System; namespace ClassTest { class Program { static void Main(string[] args) { Start: Console.Clear(); Console.WriteLine("Navigation menu n"); Console.Write("Command Line: "); string input = Console.ReadLine(); Units.Archer iArcher = new Units.Archer(); if (input == "create: archer") { iArcher.create(); goto Start; } if (input == "property: archer") { Console.Clear(); Console.WriteLine(iArcher.getProp()); Console.ReadKey(); goto Start; } Console.WriteLine("End of program"); Console.ReadLine(); } } } namespace Units { class Archer { public int Id; public int Hp; public float Speed; public float Attack; public float Defence; public float Range; public void setProp(int id, int hp, float sp, float at, float de, float ra) { Id = id; Hp = hp; Speed = sp; Attack = at; Defence = de; Range = ra; } public string getProp() { string str = "ID = " + Id + "n" + "Health = " + Hp + "n" + "Speed = " + Speed + "n" + "Attack = " + Attack + "n" + "Defence = " + Defence + "n" + "Range = " + Range + "n" ; return str; } public void create() { int idCounter = 0; Archer iArcher = new Archer(); iArcher.setProp(idCounter++, 20, 4f, 8f, 3.5f, 25f); Console.Clear(); Console.WriteLine("An archer has been created. n"); Console.WriteLine("Properties:"); Console.WriteLine(iArcher.getProp()); Console.ReadLine(); } } } 

submitted by /u/gabor_gm
[link] [comments]

Leave a Reply