Help with Code

Hi Everyone,

Would be grateful for some help

I’m trying to follow this book to learn but have hit a stumbling box, below is the passage from the book

and below the that is the code in the Player.cs script.

Any advice would be appreciated.

Thank you in advance,

Code Below:

using UnityEngine;

public class Player : Characters
{

}
void OnTriggerEnter2D(Collider2D collision)
{


// 2
if (collision.gameObject.CompareTag("CanBePickedUp"))
{
// 3
collision.gameObject.SetActive(false);
}

6459676--724234--upload_2020-10-26_20-28-52.png

What are you confused about?

(Also, when pasting code, use code tags, it makes it much easier to read and discuss)

2 Likes

Advice on what? You didn’t specify your issue.
And @StarManta beat me to this. But yeah, code tags. You’ll get more people to help you with them.

1 Like

Sorry, thank you for replying, I’ve forgot to mention the error:

Below are the errors that arose when I saved the script and loaded back into Unity.

Assets\Scripts\MonoBehaviours\Player.cs(7,6): error CS0116: A namespace cannot directly contain members such as fields or methods

Assets\Scripts\MonoBehaviours\Player.cs(3,24): error CS0246: The type or namespace name ‘Characters’ could not be found (are you missing a using directive or an assembly reference?)

NullReferenceException: Object reference not set to an instance of an object

I would be grateful for the help as I’m an absolute newbie, I didn’t even think I’d get as far as i did in the book.

Thank you in advance.

Hi StarManta,

I have made the adjustments to my post perhaps you would be willing to take a second look.

My issue appears only when I import this code into the game, i am unsure what i am doing wrong its to do with a player and collider with objects such as coins ect…

Thank you in advance

Hello Brathnann i have adjusted my post if you can offer any support i would be grateful.

:smile:

What is “Characters”? Where did that come from? It’s not a class I’ve seen, and your compiler doesn’t know what it is either. 9/10 times there should be MonoBehaviour where that is. (In Unity, all scripts that attach to GameObjects derive from MonoBehaviour, either directly or indirectly.)

Methods must be inside classes. When the text says to add the text “toward the bottom”, it does still need to be inside the }

So:

public class Player : MonoBehaviour {

  // some other stuff, whatever may already be in the class

  void OnTriggerEnter2D(Collider2D collision)
  {
    if (collision.gameObject.CompareTag("CanBePickedUp"))
    {
      collision.gameObject.SetActive(false);
    } //closes the if statement
  } // closes the method
} //closes the class

Thank you for your reply, I will present more information soon and i will do what you suggested.

best wishes,

J

It worked thank you so much, I so grateful. :smile: