hdbrnd
hdbrnd

Reputation: 47

Use script for GameObject creation / changes outside of runtime

I have a prefab, which is used multiple times in my game (it will not be instatiated during runtime, I only use the prefab by dragging it into scene view to build my level). Inside this prefab are many locations, where a specific text is written. This text is unique for every prefab.

So, it is like:

InstanceA

InstanceB

and so on ...

At the moment, I see two options to do it:

  1. I change every text manually in every instance. This would work, but is a little annoying, also I can see me making mistakes (like a misspelling or forget to change one of the texts).
  2. I solve it by a script and change the texts in the Awake or Start method. This would work, but it must be done every time, I start the game.

What I would hope for would be a solution like 2) but not every time (because nothing changes, it es every time the same) but only once - so it is generated by a script but after that, it will be always there. Even when I'm not in runtime and just work in the scene view.

Do you know any approach to get something done like this?

Thank you!

Upvotes: 1

Views: 407

Answers (1)

Quickz
Quickz

Reputation: 1836

If you wish to run a piece of code outside the run-time, you can use one of the following two options.

OnValidate method

OnValidate is triggered when your MonoBehaviour script is loaded or an inspector value has changed.

using UnityEngine;

public class TestScript : MonoBehaviour
{
    private void OnValidate()
    {
        Debug.Log("test");
    }
}

ExecuteInEditMode attribute

Adding ExecuteInEditMode to a MonoBehaviour class will make it function both during and outside the runtime. If you do not wish the script to function during the runtime, feel free to also use Application.isPlaying.

using UnityEngine;

[ExecuteInEditMode]
public class TestScript : MonoBehaviour
{
    private void Update()
    {
        if (!Application.isPlaying)
            Debug.Log("test");
    }
}

Upvotes: 1

Related Questions