I am a very new and not very smart user in Unity. I am making a Flappy Bird type game as my first project following some YouTube tutorials. The scripts I have a problem in are made for increasing the score in the game when you go through the pipes.
Here is the code for the script and a code for one of the other script I used because they are connected.
The first script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeMiddleScript : MonoBehaviour
{
public LogicScript logic;
// Start is called before the first frame update
void Start()
{
GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
logic.addScore();
}
}
the second script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
}
[ContextMenu("Decrease Score")]
public void removeScore()
{
playerScore = playerScore - 1;
scoreText.text = playerScore.ToString();
}
}
I tried using some of Unity’s autofixes but none worked. i also tried to google the error but nothing makes sense.
The closest I got was I didn’t get any error in visual studio but I still have one in unity
2
Answers
Have a look at your
addScore
function:Do you notice the
int scoreToAdd
part of your function’s definition? That means that the function you wrote is expecting you to pass anint
into it as an argument. In yourOnTriggerEnter2D
function, you don’t pass an integer to it. You just calllogic.addScore()
without any arguments, which is what the error is trying to tell you.In this case, you need to pass an integer along to your
addScore
function. This would make yourOnTriggerEnter2D
function look like this:Alternatively, you could remove the
scoreToAdd
argument and just add a constant to the player’s score:There are two bugs here so make sure you understand why you wrote every part of your code.
When you call addscore in the pipemiddle script you need to pass a parameter. Replace it with:
Assuming you want to increase the score by one.
You will get another error though. you cannot just run getcomponent and assume it assigns to the variable, you need to replace:
What you did was the same as making an int foo and just writing 4 + 5.
woo will not be 9, you need to write foo = 4 + 5;
I know that little errors like this are really annoying. When you misspell something or forget something but the most important thing is that you learn. If you have more problems in this script please respond.