Okay, so as I have said, I am following a Pokemon game tutorial, and I have gotten to a section where the creator is changing the code that detects player object collision with grass to start a battle. Only it doesn’t work. There are several scripts involved, so I am going to start with the one that I have isolated the problem with.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Controller : MonoBehaviour
{
[SerializeField] string name;
[SerializeField] Sprite sprite;
private Vector2 input;
private Character character;
private void Awake()
{
character = GetComponent<Character>();
}
public void HandleUpdate()
{
if (!character.IsMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
// remove diagonal movement
if (input.x != 0) input.y = 0;
if (input != Vector2.zero)
{
StartCoroutine(character.Move(input, OnMoveOver));
}
}
character.HandleUpdate();
if (Input.GetKeyDown(KeyCode.Z))
Interact();
}
void Interact()
{
var facingDir = new Vector3(character.Animator.MoveX, character.Animator.MoveY);
var interactPos = transform.position + facingDir;
// Debug.DrawLine(transform.position, interactPos, Color.green, 0.5f);
var collider = Physics2D.OverlapCircle(interactPos, 0.3f, GameLayers.i.InteractableLayer);
if (collider != null)
{
collider.GetComponent<Interactable>()?.Interact(transform);
}
}
private void OnMoveOver()
{
var colliders = Physics2D.OverlapCircleAll(transform.position - new Vector3(0, character.OffsetY), 0.2f, GameLayers.i.TriggerableLayers);
foreach (var collider in colliders)
{
Debug.Log("Work dammit");
var triggerable = collider.GetComponent<IPlayerTriggerable>();
if (triggerable != null)
{
triggerable.OnPlayerTriggered(this);
break;
}
}
}
public string Name
{
get => name;
}
public Sprite Sprite
{
get => sprite;
}
public Character Character => character;
}
Okay, so the portion of the code that should activate the scripting that detects a collision between the grass and the player is in the OnMoveOver function.
The function works until it gets to the “foreach (var collider in colliders)” and that never activates the code within its parathesis. I created a break in the code, and when the game reaches that part, it considers and moves on. I suspect it is not detecting a collision. I want to investigate further into the reason, but I am not entirely sure how the foreach (var collider in colliders) part works and how it interacts with the var colliders line of code. If someone would explain that it might help me figure out where to investigate next.