[C#] problem with an access to list defined in another script

I’m new to unity and I wanted to see how the scripting system is handling lists from a script to another

Problem: only the last “if” seems to be working to apply a list of sideral period (list sideralPeriod). Other prefabs get the “else” applied.

Description:
I’m building a small solar system simulation. Every celestial object is a prefab instantiated through a script

I have a “Sun” object generated by a script (StarGeneration.cs) attached to an empty gameobject called SolarSystem. In this script I started to define the list of sideral periods
StarGeneration.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StarGeneration : MonoBehaviour {
      
        public Transform StarObject;
        public List<float> sideralPeriod; //to list sideral periods
        public Vector3 position = new Vector3(0,0,0);
        void Start()  {
      

            Instantiate(StarObject, position, StarObject.rotation);
            StarObject.name = "Sun";
           
          //building of the sideral periods list:
           sideralPeriod.Add(87.969f);//mercury
            sideralPeriod.Add(224.701f);//venus
            sideralPeriod.Add(365.256f);//Earth
            // , -224.701f, 365.256f, 686.980f, 4332.6f,10759.2f, 30688.4f, 60181.3f,90469.7f, 203830f } ;

      
        }


 
}

Once the Sun is instantiated, the Sun as its own attached script “PlanetGeneration.cs” generating planets
PlanetGeneration.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlanetGeneration : MonoBehaviour {



    public int[] planetTypes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Use this for initialization
    void Start () {

   
        List<GameObject> planetList = new List<GameObject>();
      
        //list of solar system. To be replaced by imported data
        string[] planetNames = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluton", "Eris" };

        //Dummy list of vector3 for development purposes. To be replaced by imported data
        Vector3[] planetPosition = {
            new Vector3(36.8f,0,0),
            new Vector3(67.2f,0,0),
            new Vector3(93f,0,0),
            new Vector3(141.6f,0,0),
            new Vector3(483.6f,0,0),
            new Vector3(886.5f,0,0),
            new Vector3(1783.7f,0,0),
            new Vector3(2795.2f,0,0),
            new Vector3(3670.1f,0,0),
            new Vector3(6324,0,0)
        };
        // all list will be replaced by a serie of generated arrays
        //dummy list of planet sizes for development purposes
        float[] planetsSizes = { 2.4397f, 6.0519f, 6.3728f, 3.4025f,68.366f,60.268f,25.559f,24.622f,2.370f,2.326f }; //true size in Mm.

        //dummy list of planet types for development purposes
    
        //list of moons of solar system's celestial bodies. To be replaced by imported data
        int[] planetMoons = { 0, 0, 1, 2, 4, 9, 6, 1, 1, 1 };

        // recovery of the size of the name's array to create a for loop.
        var tableLength = planetNames.Length;


        //Creation of planets
        //FIXME: using maps & indexes please.
        for (int index = 0; index <tableLength ; index++)
        {
            //loading prefabs from resources.
            string prefabToLoad = FindTheCorrespondingPrefab(index);

            GameObject instancePlanet = Instantiate(Resources.Load(prefabToLoad, typeof(GameObject))) as GameObject;
            // instance is renamed for better clarity
            instancePlanet.name = planetNames[index];
            //instance is placed
            instancePlanet.transform.position = planetPosition[index];
            //instance is sized
            instancePlanet.transform.localScale = new Vector3(planetsSizes[index], planetsSizes[index], planetsSizes[index]);

            //Set the sun as parent
            instancePlanet.transform.parent = gameObject.transform;
            //instance of planet added to the list of planet for later works
            planetList.Add(instancePlanet);


            //let's instantiate the moons
            for (int numMoons = 0; numMoons < planetMoons[index]; numMoons++)
            {
                //loading prefabs from resources.
                GameObject instanceMoon = Instantiate(Resources.Load("PlanetsPrefabs/Moon", typeof(GameObject))) as GameObject;
              
                // instance is renamed for better clarity


                instanceMoon.name = planetNames[index] + (numMoons + 1); //Should make Earth1 Mars1, Mars2etc...

                instanceMoon.transform.SetParent(instancePlanet.transform);

                instanceMoon.transform.position = planetPosition[index]+ new Vector3 (planetsSizes[index],0,0) + new Vector3((float)numMoons,0,0);
            }

        }

   

        //planet's list with intended moons
        //Mercury
        //Venus
        //Earth : Moon
        //Mars: Phobos and Deimos
        //Jupiter: IO Europa Ganymede Callisto
        //Saturn: Mimas Enceladus Tethys Dione Rhea Titan Hyperion Iapetus Phoebe
        //Uranus: puck Miranda Ariel Umbriel Titania Oberon
        //Neptune
        //Pluto: Charon
        //Eris: Dysnomia


    }
    string FindTheCorrespondingPrefab(int index) //FIXME : use lists made from imported data.
    {
        string prefabToLoad = "";
        //MErcury
        if (planetTypes[index] == 1) {
            prefabToLoad = "PlanetsPrefabs/planetMercuryType1";
        }
        //Venus
        if (planetTypes[index] == 2)
        {
            prefabToLoad = "PlanetsPrefabs/planetVenusType1";
        }

        //EArth
        if (planetTypes[index] == 3)
        {
            prefabToLoad = "PlanetsPrefabs/planetEarthType1";
        }

        //Mars
        if (planetTypes[index] == 4)
        {
            prefabToLoad = "PlanetsPrefabs/planetMarsType1";
        }

        //jupiter
        if (planetTypes[index] == 5)
        {
            prefabToLoad = "PlanetsPrefabs/planetJupiterType1";
        }
        //saturn
        if (planetTypes[index] == 6)
        {
            prefabToLoad = "PlanetsPrefabs/planetSaturnType1";
        }
        //Uranus
        if (planetTypes[index] == 7)
        {
            prefabToLoad = "PlanetsPrefabs/planetUranusType1";
        }
        //Neptune
        if (planetTypes[index] == 8)
        {
            prefabToLoad = "PlanetsPrefabs/planetNeptuneType1";
        }
        //Pluto
        if (planetTypes[index] == 9)
        {
            prefabToLoad = "PlanetsPrefabs/planetPlutoType1";
        }
        //Eris
        if (planetTypes[index] == 10)
        {
            prefabToLoad = "PlanetsPrefabs/planetErisType1";
        }
      
        return prefabToLoad;

    }
}

Each prefab has a script “OrbitalMovement.cs” attached.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OrbitalMovement : MonoBehaviour {




    float speed;
    string planetID;
    // Update is called once per frame
    void Update () {
        planetID = gameObject.name;

        speed = 365/GetSideralPeriod(planetID);
        OrbitalMove(speed);//Method to make the body orbiting the star/planet parent.

    }

    void OrbitalMove(float speed) {
     
        transform.RotateAround(transform.parent.position, Vector3.down, speed * Time.deltaTime); // makes the planet orbiting the star/planet parent
      

    }



    float GetSideralPeriod(string planetID) {

        float sideralPeriod =0;
        var scriptContainer = FindObjectOfType<StarGeneration>();// why var? Doesn't seem to exist a "ScriptObject" or whatever

        if (planetID == "Mercury")
        {
            sideralPeriod = scriptContainer.sideralPeriod[0];
        
        }
        if (planetID == "Venus")
        {
            sideralPeriod = scriptContainer.sideralPeriod[1];
          
        }
        if (planetID == "Earth")
        {
            sideralPeriod = scriptContainer.sideralPeriod[2];
         
        }
        else {
            sideralPeriod = -1; // if anything go wrong, they'll go reverse :p
        }
        return sideralPeriod;


    }


}

The funny thing is that only earth(the last one definied in GetSideralPeriod(string planetID) gets its sideral period applied. All other prefabs get -1 applied. Even mercury and venus :XD:
If I add Mars period to the list, only Mars get its period applied etc…

How I can use the list of sideral period for each prefab? And why my current codes are giving me this results?

You need to use “else if” instead of “if” on lines 40 and 45 of OrbitalMovement.cs.The three if statements are separate from each other. You want only one of the if statements to succeed, so you need to link them all together with “else if” instead of just “if”.

As @Mitnainartinarian said, you should be using else if. What is basically happening right now is it checks each if statement, but when it hits earth, it resolves to false, which means it falls into the else part of the statement, overwriting any change made before that. Even if planetID == Venus for example. So basically anything not equal to Earth is set to -1.

You can also consider switch statements for something like this which can be a little clearer to understand.

1 Like