RecquireComponent with defaults?

Is there a way to set up component defaults outside of runtime? I know I could use getcomponent in Awake and change settings, but that doesn’t let me see the current values in the inspector until runtime. I’m wanting to enforce component dependency, but also have the dependency load with specific member value (like boxes checked or unchecked).

The default value for any component field is the value you initialized the field to.

Example:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
     public float range = 40.0f;
     public bool check = false;
}

Those values will be the default when you add the component in the editor. Is that what you meant?

Specifically I require RigidBody with my AI scripts, but by default I need some constraints and gravity turned off. Again, I COULD set these values in my initialization method, but that doesn’t let me see/verify values quickly outside of runtime in the inspector, which I want to do. So when I add my AI script it auto-adds the RigidBody script because of RecquireComponent. I’d like for my default values to be applied at the same time.

Maybe Unity - Scripting API: MonoBehaviour.OnValidate() could work? It’s called at edit time so you could getComponent and set your defaults there

Oh perfect. Thanks! This sounds like it will do the job.

EDIT: Meh. Bummer. This will validate on every change. So this makes defaults permanent settings instead of defaults. Values can change at runtime but any time a value is changed OnValidate will run again. If I used OnValidate to set default values I won’t be able to change them. What I need is something very similar to OnValidate, but only runs once when the component is attached… perhaps.

An alternative solution was to inherit from RigidBody. However I haven’t been able to do this. Whenever I try the compiler gets angry at me. I haven’t googled this one though so I’ll go do that…

I also found this, Unity - Scripting API: MonoBehaviour.Reset()

It will require a manual button press it looks like, but it beats setting values manually all the time

Mmmm… That’s also a cool thing but won’t work well for my goals. I’m learning a lot though, haha. There’s more than just me on the project so I want other people to be able to just add their custom script (inheriting from a standard base object) and have dependencies and their default values configured automatically. The goal here is obviously to make adding objects efficient and as error free as possible.

Hang on though, you could have a boolean called like, hasSetDefaults which you set to true after your validate function runs once, then when it’s called again, check that bool and return if it’s already true?

1 Like

This is why I just love people. They got your back. Simple solution. Don’t know how I overlooked that. Thank you sir this will do nicely.