saving objects with properties in a c# list
hi guys , i'm trying to develop a game in which you'r driving a car convoy and adding members to the convoy . I want to add the new convoy members in a list and want to add properties to them like health points, armor etc. , how can i manage that and what type of list is needed for this?
Answer by Statement · Oct 22, 2015 at 05:11 PM
Create a class to define your ConvoyMember
properties.
Use List to easily add and remove members.
using UnityEngine;
public class ConvoyMember : MonoBehaviour
{
public string firstName = "John";
public string lastName = "Doe";
public string address = "Unity Help Room";
public Sprite icon = null;
public float health = 100;
public float armor = 100;
public override string ToString()
{
return firstName + " " + lastName + " from " + address;
}
}
Keep your members in your Convoy for instance.
using UnityEngine;
using System.Collections.Generic;
public class Convoy : MonoBehaviour
{
public List<ConvoyMember> members = new List<ConvoyMember>();
public void LogAllMembers()
{
foreach (var member in members)
print(member);
}
}
Ok thx , and if i want different members with different properties , do i need a second class and list?
And a second question , can i get these members to follow each other with a head controlling the movement?
Yes, you can subclass from Convoy$$anonymous$$ember to create specialized Convoy$$anonymous$$ember types, but think about what you actually are going to add and how they are going to be used. You could also add more components to the game object that Convoy$$anonymous$$ember sits on.
Yes, you can get them to follow each other. How to get them to follow each other is a separate question that should have it's own thread on this site. Solutions could range from path finding to boid behaviour to generating motion commands that should be executed in order. Figure out what is most important for you at this point and focus on that first.