How to use bool from nested class.

Hello. I have a problem with c# scripting, with using of nested classes in other scripts to be exact.
I want to use bool from first script in second script (without editing first script), but this bool is nested within child class inside this first script . Usual methods do not work for me. I can achieve needed result by adding reference inside parent class of first script, but I want to know is it doable and how for learnig puposes.

Here are examples (link). I posted the same question on “Answers”, but it got rejected for unknown reasons.

Thanks.

Did you instantiate the nested class? or it is static?

It’s not static, it’s how it is in examples, I’ll copy them here.

1st script.

using UnityEngine;
using System;
public class Fruit : MonoBehaviour
{
     public class Apple
     {
         public bool green = true;
     }
     public int amount = 10;
}

2nd script.

using UnityEngine;
using System;
public class Potato : MonoBehaviour
{
     public int greenPotato = 5
     private Fruit _fruit;
     private Fruit.Apple _apple; /* my assumption */
     void Awake ()
     {
         _fruit = GetComponent<Fruit>();
         _apple = GetComponent<Fruit.Apple>(); /* this one too */
     }
     void Update ()
     {
         if (_apple.green) int score = greenPotato + _fruit.amount; /* how to make this one work? _apple.green don't exist */
     }
}

For whatever reason you wanna do that, it doesn’t work because Apple does not derive from MonoBehaviour or the like.

You could add that, but you would also need to manually call AddComponent<Fruit.Apple>() to your gameObject as it is contained in the script Fruit.cs.

There are probably better attempts to achieve what you wanna do, so provide some information about it and someone may help you out. :slight_smile:

Also note, that the if doesn’t do anything and will probably throw a warning or error without { } because you cannot declare a variable in an one-line statement.

2 Likes

Exactly what Suddoha said. Here! I made the changes and have tested then. works fine!

using UnityEngine;
using System.Collections;

public class Fruit : MonoBehaviour {
  public int amount = 10;

  public class Apple: MonoBehaviour {
    public bool green = true;
  }
}

and

using UnityEngine;
using System.Collections;

public class Potato : MonoBehaviour {
  public int greenPotato = 5;
  private Fruit _fruit;
  private Fruit.Apple _apple;
  void Awake ()
  {
    _fruit = GetComponent<Fruit>();
    _apple = gameObject.AddComponent<Fruit.Apple>(); // Here.... adding the Apple nested class into a object.

  }
  void Update ()
  {
    if (_apple.green) {
      int score = greenPotato + _fruit.amount;
    }
  }
}
1 Like

Well that structures totally going to turn around and bite you.

I’m not sure of your use case, but would strongly recommend a different structure.

1 Like