first of all I'm a rookie in Unity3D and especally in programming. At this moment i try diffrent things and study different documentations to create an economy simulation game.
So please be merciful to me if i dont understand your solutions instantly ;)
I need to access a twodimensional List from another script.
In Script1 I use a Class to make the 2D
public class OrderArray : MonoBehaviour
{
List<Order> orders;
public class Order
{
public string company{ get; set; }
public string date{ get; set; }
public int quantity{ get; set; }
public string deliverdate{ get; set; }
}
void Start()
{
orders= new List<Order>();
orders.Add(new Order
{ company = "Woodpecker Corp",
date = "21.11.2014",
quantity= 250,
deliverdate= "29.11.2014" });
// To access the Data in the list Im using:
Order order1= orders[0];;
Debug.Log(order1.company)
}
So far so good. Script1 runs good for me.
Now how can I access "order1.company" for example from a different Script on the same GameObject?
I knwo how I can access the variable in Script1 und Class Script in generall but I cant make it to accsess the variables in class "Order".
My result of Script2 till now
public class menu : MonoBehaviour
{
OrderArray orderarray;
Orderarray.Order orderclass;
void start()
{
orderarray= gameObject.GetComponent<OrderArray>();
}
Now I have access to the class OrderArray but I dont know how can i access the class Order inside OrderArray.
Maybe you could give me an approuch to solution or an example code I can transfer for my problem. Thank you.
You can extend your OrderArray with a GetOrderByIndex method:
public Order GetOrderByIndex(int index){
return orders[index];
}
You could use it in your start like this:
void start()
{
orderarray= gameObject.GetComponent<OrderArray>();
Order order1 = orderarray.GetOrderByIndex(0);
//do what you want with order1
}
Doing something like Mark Smit mentioned is probably best. One thing you should consider though is making "Order" a struct instead of a class since it doesn't hold a whole lot of data and you'll have a bunch of them I'd imagine. For further information take a look at this. And add a constructor to "Order" for easier creation of a new one ->
new Order("Woodpecker Corp", "21.11.2014", 250, "29.11.2014")
Related
Whenever I give new when instantiating a class or list, will it be recreated? I'm having trouble consuming a list that I fed into another class.
I'll give an example of my question to make it clearer:
I have the Customers class:
public class Customers
{
public int id { get; set; }
public string name { get; set; }
}
and I have another class called:
public class CustomerList
{
public List<Customers> dataCustomers;
}
these two are inside the same file or better same namespace.
Now I will feed this list through another Form1, so first I will instantiate it in this new form1:
CustomerList listCustomers = new CustomerList();
Now I'm going to feed the data into the class:
Customers customer = new Customers()
{
id = 1,
name = "Matthew"
}
and finally I will add the records inside the list:
listCustomer.dataCustomers.Add(customer);
Now I want to consume this list from another form/class, but I don't know how to do it. I tried instantiating it again in this new class. but it always returns saying that dataCustomers was null, saying that the object is not being referenced. so well I couldn't understand this concept well, how to consume a list that I fed into another form/class.
In this form that I want to consume, I did it like this, I instantiated it:
CustomerList objCliente = new CustomerList();
and to test, I tried to play inside a message box, just to see the result.
MessageBox.Show(objCliente.dataCustomers.ToString());
Make your property to be static, so that it can be accessed anywhere.
public class CustomerList
{
static public List<Customers> dataCustomers;
}
The way to add new customer now become like this :
CustomerList.dataCustomers.Add(customer);
and to access it also same. You can access it using this way :
CustomerList.dataCustomers
Work with me now, I'm a confused lost little child at this point.
Intro
I have an inventory that allows me to place items into a gear slot, instantiating that item in my players hand/ on body. For example, I have a simple rifle, I put it in my gear slot and it is created. My player can now run around shoot, kill, and unequip it too! BUUUT I can not figure out how to save my modified variables.
Problem Lore
All my items are Scriptable Objects while in the inventory, so I can easily create different items. The Scriptable Object holds; some text data, other things, and the actual prefab of the weapon I want to instantiate. The problem is, when I unequip the item from the gear slot it deletes the prefab, as it should, I don't want to see or use it anymore while in game. I can easily create an upgrade system, but saving those changed variables is a problem. I'm deleting it when I unequip it and instantiating a new copy when I equip it. My game allows the player to pickup the same weapon until the inventory is full too.
Overall Problems
How do I go about saving multiple modified prefabs instantiated from the same scriptable object?
Should I figure out how to create a unique Id that represents the weapon and allows the scriptable object to instantiate this unique Id?
I'm not sure if the second question is possible, but I think you might get the gist of the problem, any solutions are helpful, if I should recreate my inventory, I'd cry for sure, but I really want a weapon upgrade system in my game, so I'LL HECKIN DO IT! Thank you guys.
Problem
I will have a lot of various classes, which is very similar("simple sword", "diamond sword", "giga sword"...)
Solution
Strategy pattern, instead of creation whole new object, i will change the property of this object
Example
interface IHandle
{
public int Speed { get; set; }
}
class SimpleHandle : IHandle
{
public int Speed { get; set; }
public SimpleHandle()
{
Speed = 5;
}
}
interface IBlade
{
public int Damage { get; set; }
}
class SimpleBlade : IBlade
{
public int Damage { get; set; }
public SimpleBlade()
{
Damage = 5;
}
}
class Sword
{
private IHandle _handle { get; set; }
private IBlade _blade { get; set; }
public void ChangeHandle(IHandle handle)
{
_handle = handle;
}
public void ChangeBlade(IBlade blade)
{
_blade = blade;
}
}
I don't really know how to formulate my issue it's a bit complicated for me, i'll try my best to explain.
I'm making a space game, i have a base class which represent places, and i want to have different type of places like planets, space stations, asteroïds, trading ships etc. The player can click on those objects and get informations.
So my classes looks like something like this:
public class Place {
public int placeId;
public string placeName;
public string placeDescription;
/* Place constructor */
}
public class Planet : Place {
/* Specific proprieties of planet */
public PlanetType planetType;
public int planetSize;
...
// Planet constructor
public Planet(int placeId, string placeName, string placeDescription, PlanetType planetType, int planetSize) : base(placeId, placeName, placeDescription) {
this.planetType = planetType;
this.planetSize = planetSize;
...
}
}
And i have a delegate which accept a function like selectPlace with Place in parameters because i don't want to make a delegate for each type of Place i have.
In another script which is supposed to show the information of any kind of Place, i recieves the Place object that the player clicked on. I think i found a solution, however is this correct to do something like this ?
private void updateSelectedPlaceUI(object sender, EventsController.PlaceEventArgs placeArgs){
// This is just a test, i should check which type of subclass it is before
Planet planetTest = placeArgs.Place as Planet; // So now i can use planetTest.planetType
}
And placing this in a switch case so i can handle any type. I just want to be able to get the proprieties from any derived class of Place in order to display them in UI. I would like to know a better way to achieve this.
But i'm wondering if my design is ok and necessary, it has been a while since i haven't used inheritance / polymorphism, and i feel like i'm doing it the wrong way.
I would propably make the UI part of showing the properties a specific place generic to accept something like a PropertyItem, you can decide the properties yourself.
public class PropertyItem
{
public string Text { get; set; }
public object Value { get; set; }
}
And then in your select method you would just call the abstract method of your base class (make your base class abstract as well)
public abstract class Place
{
...
public abstract IEnumerable<PropertyItem> GetProperties();
}
And now you can override this in your Planet
public class Planet : Place
{
...
public override IEnumerable<PropertyItem> GetProperties()
{
yield return new PropertyItem { Text = "Size", Value = this.planetSize };
}
}
And eventually you would use the GetProperties() method to get the properties of your place and show them in a tabular or what ever format your UI knows how to handle the PropertyItem type.
private void updateSelectedPlaceUI(object sender, EventsController.PlaceEventArgs placeArgs)
{
MyUserInterfaceWidget.DisplayProperties(placeArgs.Place.GetProperties());
}
First I want to give some context. I got two different classes (class Player and class Enemy), each class contains different data, but they both hold the value "int Initiative".
public class Enemy : MonoBehaviour
{
public int initiative;
//More code
}
public class Player : MonoBehaviour
{
public int initiative;
//More code
}
On my project I have several units from both classes and they are stored on 2 different lists of objects
private List<Player> players;
private List<Enemy> enemies;
void Awake()
{
players = new List<Player>();
enemies = new List<Enemy>();
}
Is not shown in the code, but each unit is being sent and storaged on those list depending on their class.
Now my question:
Is there any way of combining both list into a single list keeping all the different objects? (I tried to do this, but didn't get far)
If there is no way of combining both lists because they contain different types of objects, could I create a single list that only storage the int initiative, type of object as well as the position on their previous list? (so I can refer to the lists (players and enemies) when needed. Please explain me how I could achieve this (if possible with some code).
With this I am trying to create some sort of system that will look at the initiative of each unit and call them in order starting for the one that has the highest.
Please I am pretty new in C# and coding in general, so excuse me if the question is too simple, or doesn't make sense.
Thanks in advance :)
You can do something like this:
public class MonoBehaviour
{
public int initiative;//Since you are using inheritance this can be set here
}
public class Enemy : MonoBehaviour
{
//More code
}
public class Player : MonoBehaviour
{
//More code
}
Here is the code to merge them into one list:
List<MonoBehaviour> list = new List<MonoBehaviour>()
list.Add(new Enemy());
list.Add(new Player());
When you want to process them differently somewhere for example you create a method as below:
void ProcessList(List<MonoBehaviour> list)
{
foreach(var l in list)
{
if(l is Enemy)
{
var enemy = (Enemy) l;
//process the enemy
}
else
{
var player = (Player) l;
//process as a player
}
}
}
You can use inheritance. Having base for both Enemy and Player.
public class AliveEntity
{
public string Name {get;set;}
public double HP {get;set;}
}
public class Player : AliveEntity
{ /*...*/ }
public class Enemy : AliveEntity
{ /*...*/ }
And then the list could be List<AliveEntity>.
I'm in the middle of creating a new library, and as I was building it something seemed a little odd.
Here's the code:
namespace traditional_poker
{
public class poker
{
public class hand
{
public String Name
{
get; set;
}
public String[] cards
{
get; set;
}
}
List<hand> players;
public void AddPlayer(String name)
{
hand newHand = new hand();
newHand.Name = name;
players.Add(newHand);
}
}
}
I have List<hand> players inside the Library itself, which means the library is storing data (albeit temporarily).
Is this bad practice?
Is there a better way to do this?
Or is the way I'm doing it completely legitimate?
It all depends on the way you want to tackle the problem.
If you want to have the data temporarily then it is Ok, If you want to save your data between different application instances or across different sessions then you should use a data persistent tool (filing, databases, ...)
namespace traditional_poker
{
public class poker
{
public class hand // use PascalCaseNamingConvention
{
public String Name
{
get; set;
}
public String[] cards // use PascalCaseNamingConvention
{
get; set;
}
}
List<hand> players;
public void AddPlayer(String name)
{
hand newHand = new hand();
newHand.Name = name;
players.Add(newHand); //null reference exception here! you should initialize players
}
}
}
The library is not storing data.
It offers functionality, using classes, which have fields. These classes are instantiated by an application using them, in the application memory space.
If it were bad practice to have data 'stored' in libraries, then libraries would not have classes or variables, and be severely limited.