I am trying to make my own realistic gravity, and need to access all relavent game objects, but I am having lots of problems
My script is:
public class Gravity : MonoBehaviour
{
public GameObject[] NewGravObj;
public float Grav
// Start is called before the first frame update
void Start()
{
NewGravObj = (Gravity)gameObject.GetComponent(typeof(Gravity));
}
// Update is called once per frame
void Update()
{
for (int i = 0; i< NewGravObj.Length; i++){
if (NewGravObj*.GetComponent("Gravity")!=null)*
//Gives easy access to the other Gravity Script
_ Gravity GravForce = NewGravObj*.GetComponent(“Gravity”);_
_ f (GravForce.Grav * Mathf.Pow(1.0f - 0.00002f, Vector3.Distance(transform.position, NewGravObj.transform.position)) <= 0.2f) {*_
* }*
* }*
* }*
* }*
}
I am running into problems with my only line in Start(), and when I make the GravForce variable. Does anyone know how to create a list of all GameObjects and call a script from a game object?
I don’t really know what you’re trying to attempt in your start method,
You are trying to retrieve a Gravity script from the gameobject the gravity script is attached to.
So a reference to itself? Which is pointless, and then you are trying to put that reference into a GameObject type variable, which obviously it cannot because it is of type Gravity.
You will have to be a bit more specific with which objects you exactly want.
You could do something like: Unity - Scripting API: Object.FindObjectsOfType
NewGravObj = FindObjectsOfType<GameObject>(); //Will return and store all gameobjects in the scene in the NewGravObj array.
Note that FindObjectsOfType is not a very performant method call, and it should not be overdone.
You declared NewGravObj as a list of GameObjects, you are trying to assign it as a Gravity component. What you need is FindObjectsOfType, this will return an array of all the objects of that type you want. This question has been answered on here a few times already, it came up when I typed your question into google.
Though I feel like you should study lists a little to get a better handle on them.