I want to set gunS to Shotgun type or AR15 type but dont know how and this code dont work
public Shotgun gunS2;
public AR15 gunS3;
public MonoBehaviour gunS;
private void Start()
{
set();
}
public void set()
{
if(gunT.name == "Shotgun")
{
gunS = gunT.GetComponent<Shotgun>();
}
else
{
gunS = gunT.GetComponent<AR15>();
}
}
CodePudding user response:
Give them a common interface.
interface IWeapon
{
}
class AR15 : IWeapon
{
}
class Shotgun : IWeapon
{
}
If your classes are defined this way (you obviously have to add implementation) then you can write a variable that can contain any IWeapon
.
public IWeapon gunS;
public void set()
{
if(gunT.name == "Shotgun")
{
gunS = gunT.GetComponent<Shotgun>();
}
else
{
gunS = gunT.GetComponent<AR15>();
}
}
CodePudding user response:
Either use a base class and/or interface
public interface IWeapon
{
// whatever public properties and methods shall be accessible through this interface
}
public abstract class Weapon : MonoBehaviour //, IWeapon
{
// whatever fields, properties and methods are shared between all subtypes
// if using the interface implementation of it
}
and then
public class ShotGun : Weapon
// or if for some reason you don't want a common base class
//public class ShotGun : MonoBehaviour, IWeapon
{
// whatever additional or override fields, properties and methods this needs
// or if using the interface the implementation of it
}
and
public class AK74 : Weapon
// or if for some reason you don't want a common base class
//public class AK74 : MonoBehaviour, IWeapon
{
// whatever additional or override fields, properties and methods this needs
// or if using the interface the implementation of it
}
Then simply drag the according object/component into the exposed slot in the Inspector in Unity.
There is no need for your gunT
field (wherever it comes from)
// Already reference this via the Inspector in Unity
// then you don't need your Start/set method AT ALL!
public Weapon gunS;
If for some reason this is not an option e.g. if using only the interface
public IWeapon gunS;
there still is no need to check the name or specify the type further. GetComponent
will return the first encountered component of the given type or a type inheriting from it. You can simply do
void Awake()
{
// as fallback if for whatever reason you can't directly reference it via the Inspector
// (which doesn't seem to be the case since somewhere you get gunT from ...)
if(!gunS) gunS = /*Wherever this comes from*/ gunT.GetComponent<Weapon>();
// or i only using the interface
//if(!gunS) gunS = /*Wherever this comes from*/ gunT.GetComponent<IWeapon>();
}