- Home /
How to change variables from another script?
I have a class named Gun, which has variables including: public float damage; public float range; public bool fullAuto; public float rateOfFire;
I want to be able to set these variables with values, just like you would using the Unity Editor in the Inspector; I want to do it through C# instead. I am guessing it is possible since if Unity can do it, I'm sure you can do it through the scripting.
I have spent way too long trying to find an answer online, perhaps around 3-4 hours and it is really starting to annoy me.
I've attempted many types of inheritance and polymorphism; it looks like I'm doing something wrong as I have gotten nowhere.
The other class is named Rifle and all I want to do is:
damage = 11f; range = 100f;
fullAuto = false; rateOfFire = 1;
I can set all the above things in the editor/inspector and it works fine.
Answer by ImpOfThePerverse · May 11, 2018 at 08:35 PM
I would think you'd just attach your gun script to a prefab called "Gun" and a prefab called "Rifle" and specify different stats for them there. There's no real need to use inheritance unless the behavior logic is different. Like, if there was an "aim through scope" behavior for the rifle, but not the gun, both scripts would have an "Aim" function, but the gun's would just raise the weapon up to eye level while the rifle's would cause zoom and a crosshair overlay.
You can't override the default values for public variables in the script if your rifle script inherits from "gun" unless the variables are virtual properties. So you could replace
public float damage;
with
// in the Gun class:
public virtual float damage
{
get { return 5f; }
}
// in the Rifle class, if it inherits from Gun:
public override float damage
{
get { return 11f; }
}
This prevents you from being able to adjust the values in the inspector though.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Derived Class Fields 3 Answers
C# serialization with polymorphism/inheritance. 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers