Hi (and thanks)
I have a game where various objects orbit a planet. The following script is attached to the planet and I would like it to find all objects with tag rather than object name. Is there an elegant way to achieve this?
Currently the errors which appears are:
FindGameObjectWithTag can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don’t use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
Planet…ctor ()
UnityEditor.DockArea:OnGUI()
using UnityEngine;
using System.Collections;
public class Planet : MonoBehaviour
{
//private Transform GameObjectPlayerStart;
//private Transform GameObjectPlayerGamePlay;
private GameObject GameObjectPlayerStart = GameObject.FindGameObjectWithTag("GameObjectPlayerStart");
private GameObject GameObjectPlayerGamePlay = GameObject.FindGameObjectWithTag("GameObjectPlayerGamePlay");
public float gravitationalForce = 200;
private Vector3 directionOfGameObjectPlayerStart;
private Vector3 directionOfGameObjectPlayerGamePlay;
private Transform b;
private Transform c;
void Start ()
{
directionOfGameObjectPlayerStart = Vector3.zero;
directionOfGameObjectPlayerGamePlay = Vector3.zero;
b = GameObjectPlayerStart.transform;
c = GameObjectPlayerGamePlay.transform;
}
void FixedUpdate ()
{
directionOfGameObjectPlayerStart = (transform.position-b.position).normalized;
GameObjectPlayerStart.GetComponent<Rigidbody2D>().AddForce (directionOfGameObjectPlayerStart*gravitationalForce);
directionOfGameObjectPlayerGamePlay = (transform.position-c.position).normalized;
GameObjectPlayerGamePlay.GetComponent<Rigidbody2D>().AddForce (directionOfGameObjectPlayerGamePlay*gravitationalForce);
}
}