Nebulont
Nebulont

Reputation: 1

How to set all bools in one script to the ones in the other script?

Right, so I have two instances of the same script on two gameObjects. They have bools.

public class Values: MonoBehaviour {
    public bool One;
    public bool Two;
}

Right. Now I want to copy the values from one gameobject to the other. But if I add a value to this script, I don't want to have to change the script that copies over the values. Is there a way to automatically cycle through all the booleans and set them to the value in once script?

Upvotes: 0

Views: 79

Answers (2)

nipercop
nipercop

Reputation: 387

If i correctly understood, you want to create "shared" variables.

So, for that you can use ScriptableObject. Create new script in assets folder with name BoolVariable and put this code:

using UnityEngine;
[CreateAssetMenu(menuName = "Shared/Bool")]
public class BoolVariable : ScriptableObject{
    public bool Value;
}

Then create your bool objects enter image description here

Your Values class will be changed to:

public class Values: MonoBehaviour {
    public BoolVariable One;
    public BoolVariable Two;
}

And setup your new 'Bools'

enter image description here

Hope this helps you, or, gives some ideas!

Upvotes: 0

Leonardo Menezes
Leonardo Menezes

Reputation: 516

Sure.

This is an example of how this can be accomplished:

public class Program
{
    public static void Main(string[] args)
    {
        var original = new Values();
        original.One = true;
        original.Two = false;
        var copy = CopyValuesToAnotherValues(original);
        Console.WriteLine($"one value: {copy.One}; two value: {copy.Two}");
        Console.ReadLine();
    }

    public static AnotherValues CopyValuesToAnotherValues(Values originalValue)
    {
        var valuesProperties = typeof(Values).GetProperties();
        var anotherValuesProperties = typeof(AnotherValues).GetProperties();

        var anotherValueInstance = new AnotherValues();

        foreach (PropertyInfo property in valuesProperties)
        {
            if (property.PropertyType != typeof(bool))
            {
                continue;
            }

            var booleanValue = property.GetValue(originalValue);
            anotherValuesProperties.Where(x => x.Name == property.Name).Single().SetValue(anotherValueInstance, booleanValue);
        }

        return anotherValueInstance;
    }
}

public class Values
{
    public bool One { get; set; }
    public bool Two { get; set; }
}

public class AnotherValues
{
    public bool One { get; set; }
    public bool Two { get; set; }
}

Of course, this need to be adapted to your use case, but this is the basics of it and it works, give it a try and try to understand the mechanics.

Another way of accomplishing this is with AutoMapper, take a look at it later and decide if you want to roll your own code for this or use this library.

Upvotes: 2

Related Questions