0

I am trying to make a 3D gravity simulator. I have an object that will loop over all the gameobjects with rigidBody components, apply the appropriate gravitational force for each of them, and keep moving. I want to have a prefab of this object so i can add as many objects as i want.

However, I need to make the prefab so that i can adjust the mass variable for each copy, so that I can make solar systems with say.. a heavy sun and lighter planets. is there any way I can do this. if not, what alternatives are there?

Jay
  • 2,553
  • 3
  • 17
  • 37
Adhrit
  • 59
  • 5
  • Well a prefab of your planets etc is normal. But not of the controller. If there will be only 1 why bother. You could have the planets have a script which contains a static list so on start registers in the list so you just constantly iterate the list. – BugFinder Apr 17 '23 at 19:54

2 Answers2

1

Are you instantiating each copy of the prefab by hand or by code? If you are doing by code, you can edit settings right after instantiating.

This is just an concept, modify to your needs:

GameObject solarSystem = Instantiate(solarSystem, transform..., rotation...);
GameObject[] planets;

for (int i = 0; i < solarSystem.transform.childCount; i++){

    planets[i] = originalGameObject.transform.GetChild(i).gameObject;

    //Do something with child
    if (planets[i].CompareTag("Earth")){
        // If tag is earth, do your magic
    }
    else if (planets[i].CompareTag("...")){
        // Planet is ..., do your magic
    }
}

This may not work perfectly as intended, but can give you some directions.

If you are setting by hand, you need to save some information inside of the object so you can modify:
(Like creating a INT type and modify in code based in this type)

// Put here the tag that every system root will have
GameObject[] solarSystems = GameObject.FindGameObjectsWithTag("Solar System");

for (int i = 0; i < solarSystems.count; i++){
    for (int k = 0; k < solarSystems[i].transform.childCount; k++){
        GameObject planet = solarSystems[i].transform.GetChild(k).gameObject;

        if (planet.GetComponent<PlanetScript>().planetType == 1){
            // Change to your needs
        }
        else if (planet.GetComponent<PlanetScript>().planetType == ...){
            // Just keep adding this to match your needs
        }

    }
}
Raphael Frei
  • 361
  • 1
  • 10
1

Once the Prefabs are instantiated you can modify any of the properties on that game object you want at runtime. If you want to have a base planet prefab that you can tweak in editor to create variants look in to prefab variants which inherit properties from a parent GameObject.

Kit MacAllister
  • 234
  • 1
  • 8