3

So I have a script for getting into a car which, when mouse down is detected on the given game object it will teleport the player to the car, turn of the player's controller, and switch the player camera to the car camera.

The problem is I don't want to have to drag and drop the car game object, the player game object, and both cameras into the inspector for it to work.

Instead I would like it to have the script assign all those game objects based on the player who clicked on the car. Those game objects being the car the player, and the two cameras(one parented to the player and the other parented to the car). I have no clue how to go about this so I appreciate any help all the more.

Here is a picture of the inspector with the player script: enter image description here

Also here is my C# code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetInCar : MonoBehaviour {
    public GameObject player;
    public GameObject car;
    public Camera CarCam;
    public Camera PlayerCam;


    void Start () 
    {
    }



    void OnMouseDown ()
    {
        if (Input.GetKey (KeyCode.Mouse0))
        {
            player.transform.position = car.transform.position;
            print("MovedToCar");
            GameObject.Find ("Player").GetComponent<CharacterController> ().enabled = false;
            PlayerCam.enabled = false;
            CarCam.enabled = true;
        }
    }
}
Demindiro
  • 156
  • 8
nova nanite
  • 381
  • 1
  • 7
  • 19

1 Answers1

1

I would not use "OnMouseDown()" on the car script but instead use a raycast from the player script, e.g. in the player script:

void Update(){

    if(Input.GetKey(KeyCode.Mouse0)){

        RaycastHit rayInfo;
        if(Physics.Raycast(transform.position, transform.forward, out rayInfo)){

            GetInCar gic = rayInfo.collider.GetComponentInParent<GetInCar>();
            if(gic != null){ // If it is null, then it probably is the wrong object.
                // [...]
                // Here you can call some method like "gic.GetIn(CharacterController c)"
                // where c is the player script.
            }

        }

    }

}

Note that this example will have to be modified slightly if your player has a collider object (this can be achieved with layer-based collision detection)

Demindiro
  • 156
  • 8
  • 1
    As an aside, I will mention using Input.GetButton(...) or Input.GetButtonDown(...) (which is true only on the frame the button is depressed, rather than during the whole press duration) instead of Input.GetKey(...) as that allows the action to be rebindable by the end-user. Maybe they have a controller/joystick they want to use and the left mouse button is horribly inconvenient. – Draco18s no longer trusts SE Apr 18 '17 at 17:55