How do you convert an object to a transform?
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);
}
}
Answer by Nano-Additcs · Dec 20, 2015 at 08:32 AM
So er... Two hours or so later and I (with a little help from the globalhypermeganet) have come up with a solution.
Posting it for anyone else who is trying to do something similar.
using UnityEngine;
using System.Collections;
public class PlanetGravity : MonoBehaviour
{
public float gravitationalForce = 344;
private Vector3 directionOfGameObjectPlayerStart;
GameObject[] players;
void Start () {
players = GameObject.FindGameObjectsWithTag("GameObjectPlayer");
directionOfGameObjectPlayerStart = Vector3.zero;
}
void FixedUpdate ()
{
foreach(GameObject GameObjectPlayerStart in players)
{
directionOfGameObjectPlayerStart = (transform.position-GameObjectPlayerStart.transform.position).normalized;
GameObjectPlayerStart.GetComponent<Rigidbody2D>().AddForce (directionOfGameObjectPlayerStart*gravitationalForce);
}
}
}