Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I remember coding in javascript and creating & accessing objects was fairly simple. For example:
JavaScript
var country = {
    people:32,
    homes:{
        bigHomes:6,
        smallHomes:2,
        normalHomes:21
    },
    playgrounds:7,
    countryName:"Towns Country"
}; // Then when accessing these variables...

alert("There are " + country.people + " people living in " + country.countryName + "!!");


How do I replicate this in C#??

What I have tried:

I'm creating a game with unity. In my game there are units, and they have different stats, for example, health, damage, damage per second etc..

C#
using UnityEngine;
using System.Collections;

public class Unit(float health, float speed, float damage, string name, float attackSpeed) {
		this.health = health;
		this.speed = speed;
		this.damage = damage;
		this.name = name;
		this.attackSpeed = attackSpeed;
}

public class GameController : MonoBehaviour {
    public float amountOfBasicBoat = 0;
	public Unit BasicBoat = new Unit(99, 4, 15, "Basic Boat", 1.1);
}


I get a parsing error - Assets/_Scripts/GameController.cs(4,18): error CS8025: Parsing error.
Posted
Updated 6-May-17 2:57am

1 solution

If you don't know how to define a class in c# and can't discover such a basic thing from google then I don't see how you have the ability to write a game. I'd advise you to get a book on c# and go through it to learn the basics before you try anything more advanced. You can't expect to learn c# from posting questions on a forum.

public class Unit
{
    public float health { get; set; }
    public float speed { get; set; }
    public float damage { get; set; }
    public float attackSpeed { get; set; }
    public string name { get; set; }
            
    public Unit(float health, float speed, float damage, string name, float attackSpeed)
    {
        this.health = health;
        this.speed = speed;
        this.damage = damage;
        this.name = name;
        this.attackSpeed = attackSpeed;
    }
}


Usage

public Unit BasicBoat = new Unit(99F, 4F, 15F, "Basic Boat", 1.1F);


You can create properties on the fly (as you do in js) using "dynamic" but that is not likely to meet your overall requirements.
 
Share this answer
 
Comments
Member 13120882 7-May-17 3:39am    
I've coded in java, and I've learned the C# language. I just forgot about constructors. Next time try not to underestimate people. Within about ten minutes of posting this question, I solved my problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900