add a int value to another int value - c#

im making a game where you basically eat stuff and gain its mass and add it to your own.
im trying to set a new value and i havnt been able to figure out how and im not finding a working code
its basically this part thats the main issue:
void setNewMass()
{
currentMass + enemyMass
}
both are int values
i just cant find what i need for that logic.
im attaching the whole script as well below.
i am new to coding. it was never a subject in school so im self teaching. sorry in advance
i am also having issues with "die" and "setNewMass" coming up as errors in the if statement.
gives error :
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement [Assembly-CSharp]csharp(CS0201)
i have searched the error but i genuinely struggled to understand what it meant.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class massLogic : MonoBehaviour
{
private bool collision;
private int currentMass;
public int enemyMass;
public Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
currentMass = 1;
}
// Update is called once per frame
void Update()
{
if(collision)
{
if(currentMass <= enemyMass)
{
die;
}
if(currentMass > enemyMass)
{
setNewMass;
}
}
if(!collision)
{
return;
}
}
void die()
{
SceneManager.LoadScene("total mass");
}
void setNewMass()
{
currentMass + enemyMass;
}
}
ive tried looking online but im not even sure how to search what i need. i have tried its just when you find info if your new its still 70% gibberish. ive tried searching "c# addint int together" "c# adding 2 values2 ive tried a few i honestly need a lil help

Your issue with die is that you're not calling die(). To call a function, you need to write the functions name with the parameters at the end in brackets. If there are no parameters, then you just put ().
So on line 27 you need to put die();, not die;.
Same issue with setNewMass(). Make sure to include parenthesis.

Related

Getting an error in unity Assets/scripts/LearningHowToProgram.cs(7,13): error CS1001: Identifier expected

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LearningHowToProgram : MonoBehaviour
{
int c = 12 + 13;
sum_of_2_numbers(c);
void sum_of_2_numbers(int a)
{
print( a );
}
}
I was trying to get into game development and I learnt about functions recently and when I tried to use them I got an error saying this:
Assets/scripts/LearningHowToProgram.cs(7,13): error CS1001: Identifier expected
I don't know what triggered to show this but it was coming up on console in Unity.
The console error pretty clearly states the line the issue is coming from and your IDE will give you a hint what is wrong here.
This is fundamental to understanding your own code.
In this instance it is your line:
sum_of_2_numbers(c);
You cannot call methods like this from the body of you class.
In a Unity context you would call them from one of the Unity events like Start()
Therefore it is interpreted as you defining something which is incomplete.
Also as others have mentioned your method would not actually sum 2 number only print the value of c.
using UnityEngine;
public class LearningHowToProgram : MonoBehaviour
{
private void Start()
{
sum_of_2_numbers(12, 13);
}
private void sum_of_2_numbers(int a, int b)
{
int mySum = a + b;
print(mySum);
}
}
The name of your method sum_of_2_numbers also does not follow C# naming conventions and should probably be renamed to "SummarizeTwoNumbers"

error CS0106: The modifier 'private' is not valid for this item C# error in Unity

I keep getting this error ( CS0106: The modifier 'private' is not valid for this item) and could use some help. I'm trying to make a random object generator for my game but since I am still a newbie coder I cannot seem to figure out how to fix this. Any help would be nice
Here is the code im using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class deployAsteroids : MonoBehaviour
{
public GameObject asteroidPrefab;
public float respawnTime = 1.0f;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(screenBounds.x, screenBounds.y, Camera.main.transform.position.z));
StartCorountine(asteroidWave());
private void spawnEnemy()
{
GameObject a = Instantiate(asteroidPrefab) as GameObject;
a.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), screenBounds.y * -2);
}
IEnumerator astroidWave()
{
while (true)
{
yield return new WaitForSeconds(respawnTime);
spawnEnemy();
}
}
}
Anytime you get a compiler error the first thing you should consider is to lookup up the error code in a search engine. From CS0106 the rules are provided. The forth bullet point is clear on this.
Access modifiers are not allowed on a local function. Local functions are always private.
You have two options:
Move the method outside of the parent method (Start()). This is the typical scenario if it will be used in more than one place.
Remove the modifier private.
Try using the static modifier, and reading this. That could work, it worked for me when I got the same error in unity for a public void.
Also, consider moving your method out of Start(), like others have said.

Unity OnTriggerEnter2d() Not working | Trying to switch between Scenes

I'm pretty new to unity and I've been trying to get this scene switch to work however the trigger doesn't seem to be activating when the player hits it. The debug.Log is doing nothing so I'm stumped. I know my terminology may make no sense so let me show some pictures. If youre able to help it would be extremely helpful. Thank you!
This is the inspector panel for the object I want to trigger
This is the inspector the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneChangeScript : MonoBehaviour
{
public int iLevelToLoad;
public string sLevelToLoad;
public bool useIntegerToLoadLevel = false;
void start()
{
}
void update()
{
}
private void onTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
Debug.Log("Somethings Being Triggered!");
LoadScene();
}
}
void LoadScene()
{
if(useIntegerToLoadLevel)
{
SceneManager.LoadScene(iLevelToLoad);
}
else
{
SceneManager.LoadScene(sLevelToLoad);
}
}
}
Unity Monobehavior Lifecycle methods start with a capital and C# methods are case-sensitive. Therefore, the following methods need to be corrected to be used by Unity:
start => Start
update => Update
onTriggerEnter2D => OnTriggerEnter2D
Since the C# convention is that methods start with uppercase you'll less likely encounter this issue if you assume it starts with an uppercase letter rather than lower case. But it is better to confirm! Also if you are using Visual Studio, you can avoid much of these pains by investing the time to learn some shortcuts.
Hey I just spotted that you initiated the bool useIntegerToLoadLevel to be false and you are using this condition to load the scene in the if statement and the bool is never being set to true.
Try setting this bool to true when you enter the trigger, that is in the OnTriggerEnter2D method, should definitely work. It is a minor bug that anyone can make.

Controlling Light components C#

I have a game mechanic where the player can toggle the car headlights with the L keypress and the backlights witht he S key, which also controls backwards movement.
This is shown in the code below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class headLights : MonoBehaviour {
private Light frontLight;
private Light backLight;
// Use this for initialization
void Start () {
frontLight = GetComponent<Light>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
frontLight.enabled = !frontLight.enabled;
}
if (Input.GetKeyDown(KeyCode.S))
{
backLight = GetComponent<Light>();
backLight.enabled = !backLight.enabled;
}
}
}
The problem is when I press L or S, both the front and back lights turn on because which I assume, the GetComponent refers to all extra Light components in the Scene and generalizes them as one.
I want to get the S key to only turn on the "backLights" while it is pressed and the L key to only toggle the "frontLights".
METHODS I HAVE USED TO TRY FIX THE PROBLEM
frontLight = GameObject.Find("Player").GetComponent<Light>();
This code just gives me errors like "the gameobject player does not have any light components attached to it(although it clearly does) blah blah blah.
I have also tried using tags but they confuse me a lot and seem like the easy way out. I know in the future I will have to learn how to do object orientated syntax and coding so I would very much like to learn how to reference it!
Please help me if you can, it would make my day~~ :)
Please note, you do not have to solve the whole problem for me if you are short on time, just giving general syntax that I can just swap out would help me a great deal!
Its really easy to disambiguate the two lights. Just make the variables public and set them in the inspector. Be sure to null check them before you use them to make sure they are set.
I just realized that probably didn't make sense.
Lets say your hierarchy is set up like this with the light objects as children to the car:
car
+-FrontLight
+-RearLight
Instead of putting the custom behavior on the light gameobjects, you should put it on the car.
Then, the behavior would look like this:
public class headLights : MonoBehaviour {
public Light frontLight;
public Light backLight;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
if(frontLight != null) {
frontLight.enabled = !frontLight.enabled;
}
}
if (Input.GetKeyDown(KeyCode.S))
{
if(backLight != null) {
backLight.enabled = !backLight.enabled;
}
}
}
This is because the lights are not Components of the car, they are Children of it.

C# (Unity 4.3) Cannot implicitly convert type `ShotScript[]' to `ShotScript'

Thanks all! The issue was I was using GetComponents rather than GetComponent, thanks!
I am fairly new to programming and I am trying to make a 2D game in Unity. I have found a tutorial online which is really good, up until a point (Tut can be found here http://pixelnest.io/tutorials/2d-game-unity/shooting-1/). I've come across an error and can't figure out why. The error occurs when I try and use another script inside my current script (if that makes sense to anyone). The two scripts in question have the name ShotScript and HealthScript and they are below
ShotScript:
using UnityEngine;
using System.Collections;
public class ShotScript : MonoBehaviour {
public int damage = 1;
public bool isEnemyShot = false;
void Start () {
Destroy (gameObject, 20);
}
}
HealthScript:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public int hp = 2;
public bool isEnemy = true;
void OnTriggerEnter2D(Collider2D Collider) {
ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
if (shot != null) {
if (shot.isEnemyShot != isEnemy) {
hp -= shot.damage;
Destroy (shot.gameObject);
if (hp <= 0) {
Destroy(gameObject);
}
}
}
}
}
The error I get is:
"Assets/Scripts/HealthScript.cs(13,36): error CS0029: Cannot implicitly convert type ShotScript[]' toShotScript'"
I'm rather stuck and so if anyone could point me in the right direction, that'll be great =)
P.S I'm new to this asking questions thing, so if you need any extra info, I'll do my best to provide it
Well this is the problem:
ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
It sounds like GetComponents<ShotScript> is returning an array of ShotScript references, i.e. its return type is ShotScript.
Do you want to take the same action for each ShotScript? If so, you probably want to just use a foreach loop... although you probably only want to check for the hp going negative at the end. I would expect you to be able to remove the check for nullity, too, assuming that GetComponents will just return an empty array if there aren't any such components:
ShotScript[] shots = collider.gameObject.GetComponents<ShotScript>();
foreach (ShotScript shot in shots)
{
if (shot.isEnemyShot != isEnemy)
{
hp -= shot.damage;
Destroy(shot.gameObject);
}
}
if (hp <= 0)
{
Destroy(gameObject);
}
(I've reformatted that to be rather more conventional C#, but of course you can use whatever indentation you want.)
You're calling GetComponents (notice the plural) which returns an array (that is ShotScript[]) of all matching components of the type on that particular GameObject.
So this is attempting to assign a ShotScript[] array into a single ShotScript instance which is not possible.
If you wanted to retrieve only one ShotScript (because you intend to have only 1 on an object), use the GetComponent (notice the singular) method instead which will return only one instance or null if none are assigned.
So change the one line to this:
ShotScript shot = collider.gameObject.GetComponent<ShotScript>();
If your intent was to handle many ShotScript instances/components on the same GameObject, use the fix/code supplied in Jon Skeet's answer.
The error message says that line 13 is in error:
ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
It looks like the GetComponents method is returning an array ShotScript[], but you're trying to implicity cast it to just a single ShotScript instance. Try:
ShotScript[] shots = collider.gameObject.GetComponents<ShotScript>();

Categories