I am new to coding. I have 3 c# script components. CharacterControl.cs is attached to the player game object. Openable.cs is attached to the interactable game object. Interactable.cs is abstract class so i didn’t attach it to anything. I want to call the Interact() method when the player is near the interactable game object. Debug.Log(“rctest”); is fine, it returns “rctest” to console but line 38 rc.transform.GetComponent().Interact(); method should call “public override void Interact()” in Openable class. But it does nothing. Do you guys have any suggestions?
I referenced this video:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterControl : MonoBehaviour
{
private GameObject Player;
private Vector2 boxSize = new Vector2(0.1f, 1f);
private RaycastHit2D[] hits;
private void Start()
{
Player = GameObject.Find("Player");
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
CheckInteraction();
}
}
public void CheckInteraction()
{
RaycastHit2D[] hits = Physics2D.BoxCastAll(transform.position, boxSize, 0, Vector2.zero);
if (hits.Length > 0)
{
foreach(RaycastHit2D rc in hits)
{
if (rc.transform.GetComponent<Interactable>())
{
Debug.Log("rctest");
rc.transform.GetComponent<Interactable>().Interact();
return;
}
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class Openable : Interactable
{
private GameObject assistant;
private SpriteRenderer sr;
public void Awake()
{
assistant = GameObject.Find("UI_Assistant");
sr = GetComponent<SpriteRenderer>();
}
public override void Interact()
{
assistant.SetActive(true);
sr.enabled = false;
Debug.Log("Interactworks");
}
public void Start()
{
Debug.Log("starttest");
Interact();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public abstract class Interactable : MonoBehaviour
{
private void Reset()
{
GetComponent<BoxCollider2D>().isTrigger = true;
}
public abstract void Interact();
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
collision.GetComponent<CharacterControl>().OpenInteractableIcon();
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
collision.GetComponent<CharacterControl>().CloseInteractableIcon();
}
}


