Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Error within my chess game

Discussion in 'Scripting' started by AnnNyn1, Feb 16, 2023.

  1. AnnNyn1

    AnnNyn1

    Joined:
    Oct 25, 2022
    Posts:
    2
    Hi everyone,
    I'm a beginner unity and C# user and I'm trying to make a chess game, however, when my chesspiece checkmates the king I get this error:
    NullReferenceException: Object reference not set to an instance of an object
    Game.Winner (System.String playerWinner) (at Assets/Scripts/Game.cs:113)

    I have tried to find the problem but I can't find it. Does someone see the problem here? I have included all the scripts I have.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Chessman : MonoBehaviour
    6. {
    7.   public GameObject controller;
    8.   public GameObject movePlate;
    9.  
    10.   private int xBoard = -1;
    11.   private int yBoard = -1;
    12.  
    13.   private string player;
    14.  
    15.   public Sprite black_kingG, black_rookG, black_queenG, black_pawnG, BBG, BKGroot;
    16.   public Sprite white_bishopG, white_kingG, white_rookG, white_queenG, white_pawnG, white_knightG;
    17.  
    18.   public void Activate()
    19.   {
    20.     controller = GameObject.FindGameObjectWithTag("GameController");
    21.  
    22.     SetCoords();
    23.  
    24.     switch (this.name)
    25.     {
    26.         case "black_kingG" : this.GetComponent<SpriteRenderer>().sprite = black_kingG; player = "black"; break;
    27.          case "black_rookG" : this.GetComponent<SpriteRenderer>().sprite = black_rookG; player = "black";break;
    28.           case "black_queenG" : this.GetComponent<SpriteRenderer>().sprite = black_queenG; player = "black";break;
    29.            case "black_pawnG" : this.GetComponent<SpriteRenderer>().sprite = black_pawnG; player = "black";break;
    30.             case "BBG" : this.GetComponent<SpriteRenderer>().sprite = BBG; player = "black"; break;
    31.              case "BKGroot" : this.GetComponent<SpriteRenderer>().sprite = BKGroot;player = "black"; break;
    32.  
    33.         case "white_kingG" : this.GetComponent<SpriteRenderer>().sprite = white_kingG; player = "white"; break;
    34.          case "white_rookG" : this.GetComponent<SpriteRenderer>().sprite = white_rookG; player = "white"; break;
    35.           case "white_queenG" : this.GetComponent<SpriteRenderer>().sprite = white_queenG; player = "white"; break;
    36.            case "white_pawnG" : this.GetComponent<SpriteRenderer>().sprite = white_pawnG; player = "white"; break;
    37.             case "white_bishopG" : this.GetComponent<SpriteRenderer>().sprite = white_bishopG; player = "white";break;
    38.              case "white_knightG" : this.GetComponent<SpriteRenderer>().sprite = white_knightG; player = "white";break;
    39.     }
    40.   }
    41.  
    42.   public void SetCoords(){
    43.     float x = xBoard;
    44.     float y = yBoard;
    45.  
    46.     x *= 0.66f;
    47.     y *= 0.66f;
    48.  
    49.     x += -2.3f;
    50.     y += -2.3f;
    51.  
    52.     this.transform.position = new Vector3(x,y,-1.0f);
    53.   }
    54.  
    55.  
    56.     public int GetXBoard(){
    57.         return xBoard;
    58.  
    59.     }
    60.       public int GetYBoard(){
    61.         return yBoard;
    62.  
    63.     }
    64.  
    65.     public void SetXBoard(int x){
    66.         xBoard = x;
    67.     }
    68.  
    69.      public void SetYBoard(int y){
    70.         yBoard = y;
    71.     }
    72.  
    73.         private void OnMouseUp()
    74.     {
    75.         if (!controller.GetComponent<Game>().IsGameOver() && controller.GetComponent<Game>().GetCurrentPlayer() == player)
    76.         {
    77.             DestroyMovePlates();
    78.  
    79.             InitiateMovePlates();
    80.         }
    81.     }
    82.  
    83.       public void DestroyMovePlates()
    84.     {
    85.      
    86.         GameObject[] movePlates = GameObject.FindGameObjectsWithTag("MovePlate");
    87.         for (int i = 0; i < movePlates.Length; i++)
    88.         {
    89.             Destroy(movePlates[i]);
    90.         }
    91.     }
    92.  
    93.     public void InitiateMovePlates()
    94.     {
    95.         switch (this.name)
    96.         {
    97.             case "black_queenG":
    98.             case "white_queenG":
    99.                 LineMovePlate(1, 0);
    100.                 LineMovePlate(0, 1);
    101.                 LineMovePlate(1, 1);
    102.                 LineMovePlate(-1, 0);
    103.                 LineMovePlate(0, -1);
    104.                 LineMovePlate(-1, -1);
    105.                 LineMovePlate(-1, 1);
    106.                 LineMovePlate(1, -1);
    107.                 break;
    108.             case "BKGroot":
    109.             case "white_knightG":
    110.                 LMovePlate();
    111.                 break;
    112.             case "BBG":
    113.             case "white_bishopG":
    114.                 LineMovePlate(1, 1);
    115.                 LineMovePlate(1, -1);
    116.                 LineMovePlate(-1, 1);
    117.                 LineMovePlate(-1, -1);
    118.                 break;
    119.             case "black_kingG":
    120.             case "white_kingG":
    121.                 SurroundMovePlate();
    122.                 break;
    123.             case "black_rookG":
    124.             case "white_rookG":
    125.                 LineMovePlate(1, 0);
    126.                 LineMovePlate(0, 1);
    127.                 LineMovePlate(-1, 0);
    128.                 LineMovePlate(0, -1);
    129.                 break;
    130.             case "black_pawnG":
    131.                 PawnMovePlate(xBoard, yBoard - 1);
    132.                 break;
    133.             case "white_pawnG":
    134.                 PawnMovePlate(xBoard, yBoard + 1);
    135.                 break;
    136.         }
    137.     }
    138.  
    139.     public void LineMovePlate(int xIncrement, int yIncrement)
    140.     {
    141.         Game sc = controller.GetComponent<Game>();
    142.  
    143.         int x = xBoard + xIncrement;
    144.         int y = yBoard + yIncrement;
    145.  
    146.         while (sc.PositionOnBoard(x, y) && sc.GetPosition(x, y) == null)
    147.         {
    148.             MovePlateSpawn(x, y);
    149.             x += xIncrement;
    150.             y += yIncrement;
    151.         }
    152.  
    153.         if (sc.PositionOnBoard(x, y) && sc.GetPosition(x, y).GetComponent<Chessman>().player != player)
    154.         {
    155.             MovePlateAttackSpawn(x, y);
    156.         }
    157.     }
    158.  
    159.     public void LMovePlate()
    160.     {
    161.         PointMovePlate(xBoard + 1, yBoard + 2);
    162.         PointMovePlate(xBoard - 1, yBoard + 2);
    163.         PointMovePlate(xBoard + 2, yBoard + 1);
    164.         PointMovePlate(xBoard + 2, yBoard - 1);
    165.         PointMovePlate(xBoard + 1, yBoard - 2);
    166.         PointMovePlate(xBoard - 1, yBoard - 2);
    167.         PointMovePlate(xBoard - 2, yBoard + 1);
    168.         PointMovePlate(xBoard - 2, yBoard - 1);
    169.     }
    170.  
    171.     public void SurroundMovePlate()
    172.     {
    173.         PointMovePlate(xBoard, yBoard + 1);
    174.         PointMovePlate(xBoard, yBoard - 1);
    175.         PointMovePlate(xBoard - 1, yBoard + 0);
    176.         PointMovePlate(xBoard - 1, yBoard - 1);
    177.         PointMovePlate(xBoard - 1, yBoard + 1);
    178.         PointMovePlate(xBoard + 1, yBoard + 0);
    179.         PointMovePlate(xBoard + 1, yBoard - 1);
    180.         PointMovePlate(xBoard + 1, yBoard + 1);
    181.     }
    182.  
    183.     public void PointMovePlate(int x, int y)
    184.     {
    185.         Game sc = controller.GetComponent<Game>();
    186.         if (sc.PositionOnBoard(x, y))
    187.         {
    188.             GameObject cp = sc.GetPosition(x, y);
    189.  
    190.             if (cp == null)
    191.             {
    192.                 MovePlateSpawn(x, y);
    193.             }
    194.             else if (cp.GetComponent<Chessman>().player != player)
    195.             {
    196.                 MovePlateAttackSpawn(x, y);
    197.             }
    198.         }
    199.     }
    200.  
    201.     public void PawnMovePlate(int x, int y)
    202.     {
    203.         Game sc = controller.GetComponent<Game>();
    204.         if (sc.PositionOnBoard(x, y))
    205.         {
    206.             if (sc.GetPosition(x, y) == null)
    207.             {
    208.                 MovePlateSpawn(x, y);
    209.             }
    210.  
    211.             if (sc.PositionOnBoard(x + 1, y) && sc.GetPosition(x + 1, y) != null && sc.GetPosition(x + 1, y).GetComponent<Chessman>().player != player)
    212.             {
    213.                 MovePlateAttackSpawn(x + 1, y);
    214.             }
    215.  
    216.             if (sc.PositionOnBoard(x - 1, y) && sc.GetPosition(x - 1, y) != null && sc.GetPosition(x - 1, y).GetComponent<Chessman>().player != player)
    217.             {
    218.                 MovePlateAttackSpawn(x - 1, y);
    219.             }
    220.         }
    221.     }
    222.  
    223.     public void MovePlateSpawn(int matrixX, int matrixY)
    224.     {
    225.         //Get the board value in order to convert to xy coords
    226.         float x = matrixX;
    227.         float y = matrixY;
    228.  
    229.         //Adjust by variable offset
    230.         x *= 0.66f;
    231.         y *= 0.66f;
    232.  
    233.         //Add constants (pos 0,0)
    234.         x += -2.3f;
    235.         y += -2.3f;
    236.  
    237.         //Set actual unity values
    238.         GameObject mp = Instantiate(movePlate, new Vector3(x, y, -3.0f), Quaternion.identity);
    239.  
    240.         MovePlate mpScript = mp.GetComponent<MovePlate>();
    241.         mpScript.SetReference(gameObject);
    242.         mpScript.SetCoords(matrixX, matrixY);
    243.     }
    244.  
    245.     public void MovePlateAttackSpawn(int matrixX, int matrixY)
    246.     {
    247.         //Get the board value in order to convert to xy coords
    248.         float x = matrixX;
    249.         float y = matrixY;
    250.  
    251.         //Adjust by variable offset
    252.         x *= 0.66f;
    253.         y *= 0.66f;
    254.  
    255.         //Add constants (pos 0,0)
    256.         x += -2.3f;
    257.         y += -2.3f;
    258.  
    259.         //Set actual unity values
    260.         GameObject mp = Instantiate(movePlate, new Vector3(x, y, -3.0f), Quaternion.identity);
    261.  
    262.         MovePlate mpScript = mp.GetComponent<MovePlate>();
    263.         mpScript.attack = true;
    264.         mpScript.SetReference(gameObject);
    265.         mpScript.SetCoords(matrixX, matrixY);
    266.     }
    267. }
    268.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using UnityEngine.UI;
    6.  
    7. public class Game : MonoBehaviour
    8. {
    9.     public GameObject chesspiece;
    10.  
    11.     private GameObject[,] positions = new GameObject[8,8];
    12.     private GameObject [] playerBlack = new GameObject[16];
    13.     private GameObject [] playerWhite = new GameObject[16];
    14.  
    15.     private string currentPlayer = "white";
    16.  
    17.     private bool gameOver = false;
    18.  
    19.     // Start is called before the first frame update
    20.     void Start()
    21.     {
    22.         playerWhite = new GameObject[]{
    23.             Create("white_rookG",0,0), Create("white_knightG",1,0), Create("white_bishopG",2,0), Create("white_queenG",3,0), Create("white_kingG",4,0), Create("white_bishopG",5,0), Create("white_knightG",6,0), Create("white_rookG",7,0),
    24.             Create("white_pawnG",0,1), Create("white_pawnG",1,1), Create("white_pawnG",2,1), Create("white_pawnG",3,1), Create("white_pawnG",4,1), Create("white_pawnG",5,1), Create("white_pawnG",6,1), Create("white_pawnG",7,1)
    25.         };
    26.  
    27.          playerBlack = new GameObject[]{
    28.             Create("black_rookG",0,7), Create("BKGroot",1,7), Create("BBG",2,7), Create("black_queenG",3,7), Create("black_kingG",4,7), Create("BBG",5,7), Create("BKGroot",6,7), Create("black_rookG",7,7),
    29.             Create("black_pawnG",0,6), Create("black_pawnG",1,6), Create("black_pawnG",2,6), Create("black_pawnG",3,6), Create("black_pawnG",4,6), Create("black_pawnG",5,6), Create("black_pawnG",6,6), Create("black_pawnG",7,6)
    30.         };
    31.  
    32.  
    33.          for (int i = 0; i < playerBlack.Length; i++)
    34.         {
    35.             SetPosition(playerBlack[i]);
    36.             SetPosition(playerWhite[i]);
    37.         }
    38.     }
    39.  
    40.     public GameObject Create(string name, int x, int y)
    41.     {
    42.         GameObject obj = Instantiate(chesspiece, new Vector3(0, 0, -1), Quaternion.identity);
    43.         Chessman cm = obj.GetComponent<Chessman>(); //We have access to the GameObject, we need the script
    44.         cm.name = name; //This is a built in variable that Unity has, so we did not have to declare it before
    45.         cm.SetXBoard(x);
    46.         cm.SetYBoard(y);
    47.         cm.Activate(); //It has everything set up so it can now Activate()
    48.         return obj;
    49.     }
    50.  
    51.     public void SetPosition(GameObject obj)
    52.     {
    53.         Chessman cm = obj.GetComponent<Chessman>();
    54.  
    55.         //Overwrites either empty space or whatever was there
    56.         positions[cm.GetXBoard(), cm.GetYBoard()] = obj;
    57.     }
    58.  
    59.     public void SetPositionEmpty(int x, int y)
    60.     {
    61.         positions[x, y] = null;
    62.     }
    63.  
    64.     public GameObject GetPosition(int x, int y)
    65.     {
    66.         return positions[x, y];
    67.     }
    68.  
    69.     public bool PositionOnBoard(int x, int y)
    70.     {
    71.         if (x < 0 || y < 0 || x >= positions.GetLength(0) || y >= positions.GetLength(1)) return false;
    72.         return true;
    73.     }
    74.  
    75.     public string GetCurrentPlayer()
    76.     {
    77.         return currentPlayer;
    78.     }
    79.  
    80.     public bool IsGameOver()
    81.     {
    82.         return gameOver;
    83.     }
    84.  
    85.     public void NextTurn()
    86.     {
    87.         if (currentPlayer == "white")
    88.         {
    89.             currentPlayer = "black";
    90.         }
    91.         else
    92.         {
    93.             currentPlayer = "white";
    94.         }
    95.     }
    96.  
    97.     public void Update()
    98.     {
    99.         if (gameOver == true && Input.GetMouseButtonDown(0))
    100.         {
    101.             gameOver = false;
    102.  
    103.             //Using UnityEngine.SceneManagement is needed here
    104.             SceneManager.LoadScene("Game"); //Restarts the game by loading the scene over again
    105.         }
    106.     }
    107.    
    108.     public void Winner(string playerWinner)
    109.     {
    110.         gameOver = true;
    111.  
    112.         //Using UnityEngine.UI is needed here
    113.         GameObject.FindGameObjectWithTag("WinnerText").GetComponent<Text>().enabled = true;
    114.         GameObject.FindGameObjectWithTag("WinnerText").GetComponent<Text>().text = playerWinner + " is the winner";
    115.  
    116.        GameObject.FindGameObjectWithTag("RestartText").GetComponent<Text>().enabled = true;
    117.     }
    118. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class MovePlate : MonoBehaviour
    7. {
    8.   public GameObject controller;
    9.  
    10.   GameObject reference = null;
    11.  
    12.   int matrixX;
    13.   int matrixY;
    14.  
    15.   public bool attack = false;
    16.  
    17.   public void Start()
    18.   {
    19.     if (attack){
    20.         gameObject.GetComponent<SpriteRenderer>().color = new Color(1.0f, 0.0f, 0.0F, 1.0f);
    21.     }
    22.   }
    23.  
    24.   public void OnMouseUp()
    25.   {
    26.     controller = GameObject.FindGameObjectWithTag("GameController");
    27.  
    28.     if (attack)
    29.     {
    30.            GameObject cp = controller.GetComponent<Game>().GetPosition(matrixX, matrixY);
    31.             if (cp.name == "white_kingG")controller.GetComponent<Game>().Winner("black") ;
    32.             if (cp.name == "black_kingG")controller.GetComponent<Game>().Winner("white");
    33.  
    34.             Destroy(cp);
    35.     }
    36.  
    37.     controller.GetComponent<Game>().SetPositionEmpty(reference.GetComponent<Chessman>().GetXBoard(),
    38.     reference.GetComponent<Chessman>().GetYBoard());
    39.  
    40.     reference.GetComponent<Chessman>().SetXBoard(matrixX);
    41.     reference.GetComponent<Chessman>().SetYBoard(matrixY);
    42.     reference.GetComponent<Chessman>().SetCoords();
    43.  
    44.     controller.GetComponent<Game>().SetPosition(reference);
    45.  
    46.     controller.GetComponent<Game>().NextTurn();
    47.  
    48.     reference.GetComponent<Chessman>().DestroyMovePlates();
    49.   }
    50.  
    51.   public void SetCoords(int x, int y){
    52.     matrixX = x;
    53.     matrixY = y;
    54.   }
    55.  
    56.     public void SetReference(GameObject obj)
    57.     {
    58.         reference = obj;
    59.     }
    60.  
    61.     public GameObject GetReference(){
    62.         return reference;
    63.     }
    64. }
    65.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,949
  3. AnnNyn1

    AnnNyn1

    Joined:
    Oct 25, 2022
    Posts:
    2
    Thank you!
    I found the problem. I needed to refer to
    <TMPro.TextMeshProUGUI> instead of <text>
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,949
    Also, just for the record, this sort of thing is NOT a good idea, especially for a beginner:

    If anyone on my team submitted code like that it would be rejected in a professional production environment and they would need to rewrite it correctly. Code like the above is extremely fragile and prone to failure at any point in the future if anything changes shape within your game.

    Use public references, drag them in. It's The Unity Way.

    Also, if you have more than one or two dots (.) in a single statement, you're just being mean to yourself.

    How to break down hairy lines of code:

    http://plbm.com/?p=248

    Break it up, practice social distancing in your code, one thing per line please.

    "Programming is hard enough without making it harder for ourselves." - angrypenguin on Unity3D forums

    "Combining a bunch of stuff into one line always feels satisfying, but it's always a PITA to debug." - StarManta on the Unity3D forums

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066