- Home /
Many variables under the same name
Hi, I want to get variable from different class but under the same name like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpgradeItem : MonoBehaviour
{
public /* Some class */ item;
[HideInInspector]
public Crabs crab;
void Start()
{
switch (itemType)
{
case ItemType.Suspension:
item = crab.suspension;
break;
case ItemType.Wheel:
item = crab.wheel;
break;
}
}
}
public enum ItemType
{
Suspension,
Wheel
}
[System.Serializable]
public class Crabs
{
public Suspension suspension;
public Wheel wheel;
}
public class Wheel : MonoBehaviour {
public int mass;
public int maxLoad;
public float roadGrip;
public float terrainGrip;
public float radius;
}
public class Suspension : MonoBehaviour {
public int mass;
public int maxLoad;
public float softness;
}
And if I choose wheel I can call
item.roadGrip
or if I choose wheel I can call
item.softness
Is any way to do it? Thanks for help.
Comment
Answer by FortisVenaliter · May 02, 2017 at 08:37 PM
Yep, you definitely can. But it's not a concept that can be easily explained in this box.
To get you going in the right direction, I recommend reading up on Polymorphism and Generics.
Your answer

Follow this Question
Related Questions
How to connect shader and script 0 Answers
Player cannot jump if not in update or fixed update 2 Answers
Unity isn't properly syncing with project 0 Answers
Make Variables shared by several objects 2 Answers
Gun Recoil Help 0 Answers