Problem with script in multiple scenes needing to refer to FPS Controller.
I have 2 scenes currently, and an FPS controller that can move between these scenes, however always starts in scene 1. I have a pick up script on a cube in scene one so that the player can pick up this cube and place it on a pressure pad. This has a public transform, so that the cube is locked to a position in front of the player when being held. This transform is a child of the FPS Controller and situated just in front, as to appear being held. However, you have to select that child object as the public transform in the script. This is fine for my first scene as the child object exists there, however in my second scene the FPS controller does not exist there since the player will move to this scene when they play. This means I can't select the child object as the public transform. Is there any way to resolve this??
Here is my pick up script for reference:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
public Transform theDest;
void OnMouseDown()
{
GetComponent<BoxCollider>().enabled = false;
GetComponent<Rigidbody>().useGravity = false;
this.transform.position = theDest.position;
this.transform.parent = GameObject.Find("Destination").transform;
}
void OnMouseUp()
{
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
GetComponent<BoxCollider>().enabled = true;
}
}
Answer by Kyprto_Knight · Apr 14, 2019 at 03:17 PM
Figured this out! For anyone else stuck in my situation, you can create a void start that defines "theDest" as "GameObject.Find("Destination").transform; just insert the name of the gameobject you want in those brackets. I'll include my script below for reference. This works by when the scene is loaded, it will automatically find the correct GameObect, so you don't have to manually set it. That means it works for any scene!
My new script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PickUp : MonoBehaviour { public Transform theDest;
private void Start()
{
theDest = GameObject.Find("Destination").transform;
}
void OnMouseDown()
{
GetComponent<BoxCollider>().enabled = false;
GetComponent<Rigidbody>().useGravity = false;
this.transform.position = theDest.position;
this.transform.parent = GameObject.Find("Destination").transform;
}
void OnMouseUp()
{
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
GetComponent<BoxCollider>().enabled = true;
}
}
Your answer
Follow this Question
Related Questions
How I can Open a Previous Scene with button back !? 3 Answers
need help transferring something from 1 scene to the other 0 Answers
How to rotate RigidBodyFPSController (C#) 1 Answer
Complicated level change problem 1 Answer
Coroutine couldn't be started because the game object 'Scene Loader' is inactive 1 Answer