The question is answered, right answer was accepted. I found a solution through testing.
Can't set transform.position AND constantforce.force?
I'm working on a physics based marble maze/puzzle game. When a "puzzle" is solved the "marble" gameobject falls out of the playing field and it triggers a trigger with the following OnTriggerExit:
//Kill the current puzzle, load the next one, and reset the marble.
gameManager.GetComponent<LevelsManager> ().DestroyPuzzle ();
marble.GetComponent<ConstantForce> ().force = Vector3.zero;
gameManager.GetComponent<LevelsManager> ().LoadPuzzle ();
Destroy (marble);
marble = Instantiate(Resources.Load ("Prefabs/Marble", typeof (GameObject))) as GameObject;
// Rename the marble, move it to the StartMarker, and turn on its local gravity.
marble.name = "Marble";
string puzzleName = "Puzzle_" + gameManager.GetComponent<LevelsManager> ().StageCurrent.ToString ();
GameObject puzzlez = GameObject.Find(puzzleName);
float marbleScale = puzzlez.GetComponent<PuzzleProperties>().marbleScale;
marble.transform.localScale = new Vector3 (marbleScale, marbleScale, marbleScale);
marble.transform.position = GameObject.Find ("StartMarker").transform.position;
marble.GetComponent<ConstantForce> ().force = marbleForce;
The trouble is marble.transform.position AND marble.GetComponent ().force don't both set. If I leave the code as you see it above; ConstantForce.force sets properly but the marble doesn't translate to the StartMarker position. If I add a superfluous marble = GameObject.FindGameObjectWithTag ("Player"); the position is set properly but the trigger gameobject that holds this script loses the marble reference and the ConstantForce.force doesn't trigger.
This is particularly weird as I also have a reset function that uses the same commands that works every time.
public void ResetPuzzle ()
{
marble = GameObject.FindGameObjectWithTag ("Player");
marble.GetComponent<ConstantForce> ().force = Vector3.zero;
gameManager.GetComponent<LevelsManager> ().DestroyPuzzle ();
gameManager.GetComponent<LevelsManager> ().LoadPuzzle ();
marble.transform.position = GameObject.Find ("StartMarker").transform.position;
marble.GetComponent<ConstantForce>().force = marbleForce;
}
I honestly baffled. Any ideas? I might be able to call my reset function but that could get messy. :/
Answer by Chrury · May 08, 2017 at 12:55 AM
I asked a friend and it turns out that the script was running too fast and/or the startmarker search was happening before or at the same time of the load. So it wasn't getting caught. Closing.
Follow this Question
Related Questions
How do you pick up an instantiated object? 1 Answer
Wrong position (always 0,0,0) when Instantiate prefab. 1 Answer
How can I change position of instantiate objects (clones)? 1 Answer
Question About Unity Class Hierarchy 3 Answers
How to instantiate a game object every time when space key is pressed 2 Answers