I
I
Igor2017-07-19 10:04:42
2D
Igor, 2017-07-19 10:04:42

How to register the interaction of the player with the object?

The game has an object (lever) and you need to register the player's interaction with it.
The principle is as follows:
The player approaches the lever, presses the interaction key and the lever must do something (for example, open the door).

Lever interaction program code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeverScript : MonoBehaviour
{
    // Объект на который влияет рычаг
    public GameObject GO;

    public void OnTriggerStay2D(Collider2D coll)
    {
        if (coll.gameObject.tag == "Player")
            {
            if (Input.GetKey(KeyCode.E))
                {
                   // Проверка на наличие Объекта
                    if (GO != null) ChangeGOStat(GO);
                }
            }
        }
    // Функция по изменению статуса объекта на противоположный
    public void ChangeGOStat(GameObject GO)
    {
        GO.gameObject.SetActive(!(GO.gameObject.activeSelf));
    }
}

The problem is that after the script has been put into the lever, nothing happens in the game when interacting with it. How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arseniy Efremov, 2017-07-19
@ElMigele

1. Check if your player object has the "Player" tag.
2. Have you linked in the inspector (or somewhere else) the lever object to the GO.
3. Check if the lever collider is a trigger and if the player can interact with it .
4. GameObject.activeSelf can sometimes return the wrong value if the object's activity is not set by you, but by someone in the hierarchy. Check if you have such that false is passed to SetActive all the time, for example.
In order to view the values ​​during program execution, you can use the debug information output Debug.Log

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question