#💻┃code-beginner
1 messages · Page 607 of 1
oh i didnt even think of this, then yeah thats def something very wrong if they are interacting with prefab still which I might suspect now
Anyway focus on 1 issue at a time. What about this ^ @acoustic belfry
And make balas private, not public
it displayed the log over and over,
bullets left five
five
five
and five...
How many mortem_rifle_scripts are there
one
i only have one mortem (name of the enemy) in the game, (wich is the owner of the script)
i followed the sebastian lague tutorial on procedural landmass generation but i did a finite instead of infinite, im trying to add biomes and i came across voronoi diagram but i dont know where to start.
I've used this https://github.com/nol1fe/delaunator-sharp
For delaunay triangulation and voronoi diagrams
Then something keeps resetting balas back to 5. If making it private worked without giving you any errors, then it looks like your Reload() function is running more than you expect
thats cool but i dont want the biomes to be so regular
Blend them with other noises
it didnt
ill try that thanks
now for make it worse...for an strange reason now the bullets dont move
this is getting worse and worse...
i dont know what im doing wrong
Q-Q
if u have a brick wall built on a broken brick and u remove that brick to replace it..
what happens to the rest of the wall?
So, since that means no other scripts are modifying balas, one of two things is happening:
- There's more than one
mortem_rifle_scriptand you're callingdispararon different ones Reload()is resettingbalasback to 5 in between each call ofdisparar
explodes, i get it
lol.. im just sharing the pain w/ ya
😄 been there done thta
oh, sorry, thanks ;-;
actual scrip, how fucked up im?
https://paste.mod.gg/eshpaolvpztc/0
A tool for sharing your source code with the world!
doesnt help that most are not native english variables so its hard to tell wth is what
Put a log in Reload after the wait
see when that logs
Hiya! I'm pretty new to Unity and I was wondering if I could get a quick hand with some code:
I have all of my Enemy Health, Projectile Damage, Enemy Movement code sorted, only issue isssss, the bullets collide with the Circle Collider 2D that's ONLY being used for player-detection (the enemy will only chase the player when they're spotted)
I've managed to make the bullets ignore the player character, but I'm not sure how to make that happen with component-specific stuff
How would I go about nullifying the detection-circle from being detected in the projectile code? I'd really appreciate any advice!
oh...sorry i forgot about that...
ok
o o h . . .
it...starts from the start...and keeps going......over over and over
wait, i think i did something wrong
animator.Play("Base Layer.MortemRifleReload");
reload = true;
StartCoroutine(Reload());
}```
that should be inside braces
w h a t
btw the enemy works the same, i dont know what went wrong, and also what that return means
this is what appeared, its on the PLAYER shooting script
{
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
GameObject shotgunbullet = Instantiate(shotgun_bullet, transform.position, Quaternion.identity);
shotgunbullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * shotgun_bulletspeed;
Vector3 leftDirection = Quaternion.Euler(0, 0, -10) * shootDirection; // Giro de -10 grados a la izquierda
GameObject leftBullet = Instantiate(shotgun_bullet, transform.position, Quaternion.identity);
leftBullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(leftDirection.x, leftDirection.y) * shotgun_bulletspeed;
Vector3 rightDirection = Quaternion.Euler(0, 0, 10) * shootDirection; // Giro de 10 grados a la derecha
GameObject rightBullet = Instantiate(shotgun_bullet, transform.position, Quaternion.identity);
rightBullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(rightDirection.x, rightDirection.y) * shotgun_bulletspeed;
}```
- you need to get your !IDE configured (see message below) 👇
- i'd recommend a physics query for your detection circle instead of relying on a trigger message. you can use a Physics2D.OverlapCircle to periodically check that area and it will also allow you to pass in a layermask to filter what layers are even detected
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Oh my gosh THANK YOU I've been trying to figure out for AGES why my VisualStudio wasn't VisualStudio-ing like everyone else's 
So would you say for a periodic check I should put it into a void Update()? Or would Physics2D.OverlapCircle be a void function in of itself?
OverlapCircle is a method you can call in Update (or where ever)
Awesome! Thank you for the help, you're the best :]
Hi, i have good news and bad news.
I managed to fix the issues, now the bullets decrease, and the bullets move, and when it empties it enters into the coroutine where it restarts the bullet amount...
My issue now is...the reloading animation doesnt work
why can't I reference my JoinBtn here?
you can't just have arbitrary code outside of a method
It needs to be in a function
ahhhh yea right
hey btw, why my animation doesn't triggers?
it should
{
animator.Play("Base Layer.MortemRifleReload");
reload = true;
StartCoroutine(Reload());
}
}```
this script works, cuz everything works but the animation
this doesnt make much sens
Put a debug log before the animator.Play line
if its true why are you setting it to true again
i set it to false for default
do you assign true anywhere else? because if not, then naturally that if statement can never evaluate to true
what am I doing incorrectly here?
What does the error say
oh no, i set it in shooting.
But the script its supossed to execute an animation and a coroutine, and well...the coroutine in theory works cuz it affects another value, but the animation doesnt
have you actually verified that line is running
im now gonna
but also, like nav pointed out, that assignment to reload is 100% pointless there
yep it works
huh
wdym "huh"? reload is already true there, it is pointless to assign true to reload there
If reload is true, you set it to true. What do you expect that to accomplish
ah, my bad, the coroutine sets it to false
listen, i checked the log, and it works, the whole bool works
the issue here is, the animation doesnt
nobody is saying that the bool doesn't work. we're pointing out that assigning true to it there is pointless.
you're literally doing if reload is true assign it to true
then pay attention to what people tell you
anyway, show your entire console window when you see the log that proves your animator.Play line is running
stop hiding your warnings
{
Debug.Log("reload scene");
animator.Play("Base Layer.MortemRifleReload");
StartCoroutine(Reload());
}
}```
that's a lot of clones...consider using pooling
the clones are bullets
object pooling is 100% above this person's pay grade at the moment
what do you mean using pooling?
im sorry im just trying to make a game in Unity for the first time
look for tutorial
not maybe, IT IS
okay now pay attention to what people tell you. #💻┃code-beginner message
i did now, there's nothing very important for now
show it
ok
also turn off collapse mode so that the logs are shown in the proper order
ok
oh now that I'm looking at it...unity 6 looks a lot diffrent huh
here is
I still haven't updated yet lol
it says there's an animation issue for the Tuetue (bird meele-based enemy)
nothing about the Mortem (proyectile-based enemy and the one highlater btw)
Well there's like 900 of them, did you consider maybe some of them are related to the one that isn't playing the animation
I think the controller in animator component is empty
i clicked all of them, 100 of them
unity does this to me too every now and then
there are 900 of them though
address that then try again
i meant, i clicked all of them, :<
originally where of the Mortem and the Tuetue, but then i fixed something, and the error faded away...but the reloading animation's still missing
Show this but with Collapse enabled
ok
or just fix that issue and try again with collapse disabled since we want to see when any warnings happen around that specific log that shows when you call animator.Play on the shooting object
oh, it was that i forgot to add it to the object
o - o
xd
But now i have another issue..................................................
the animation executes, but doesn't wait till it ends to return to shooting, and then gets in a loop of "reloading" and "shooting" at the same time
but hey, its an advancement
okay do you have any logic that prevents it from shooting during the reload animation?
ahh, you mean the logic of shooting
in theory
i mean, it needs bullets to do it, and thats earned in the coroutine, "wich says that it would give the bullets to the enemy after the animation ends"
but doesnt work
{
while (reloadAnimation)
{
yield return null;
}
reload = false;
balas = cantidadDeBalas;
//done reloading
}
}```
What changes reloadAnimation
i think i did a miscalculation, im fixing it now
its supossed to be the animation...looks like i did it wrong
if (reload == true)
{
Debug.Log("reload scene");
animator.Play("Base Layer.MortemRifleReload");
reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
StartCoroutine(Reload());
}```
You just set the animation to MortemRifelReload. You already know exactly what the current animation is. Why not just set reloadAnimation to true there?
Code runs, one line at a time, top to bottom
wat
You set the animation, then on the next line immediately check the animation
yeah
i dont get it
ah, im checking it
for make the coroutine also check it
and wait till it ends
Okay, let me ask you a question.
int x = 7
bool isXSeven = x == 7
Is there any universe in which isXSeven is false
no...
I think you misunderstand what this line of code does
reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
This does not perpetually check if the current animation is "MortemRifleReload", over and over
It checks if, at this moment in time, the current animation state name is "MortemRifleReload"
That's it.
It doesn't matter if the animation state changes sometime later
reloadAnimation will remain true
o h
then what i should do for acomplish what i need?
make that when bullets reach zero (reload becomes true) executes an animation, and waits until that animation ends for make bullets return to it original value
well, you currently have code that loops forever until reloadAnimation becomes false
perhaps you should do something to make reloadAnimation become false there
ooooooh, now i get it
but the issue is.........................what? specificly
sorry for my noobness
You already know how to check if the current animation state is named "MortemRifleReload"
you have explicitly written a line of code that does this
yeah, i know that, but i want to do the oppositive...
im getting pretty lost here
well, that's what the ! operator is for...
but in this case, I'm pretty sure you do just want
what does this? i thought it detected till the bool reloadAnimation, wich is the equivalent to the animation, ended
yield return null;
oooooooooooooooh, i forgot about em
while (condition) {
condition = ...
yield return null;
}
no, not at all
yield is a keyword used inside an enumerator method
it causes the enumerator to stop and either exit completely (yield break) or produce a value yield return)
with Coroutines, you generally just yield return nothing -- thus, yield return null
Unity resumes the method once every frame. When the method hits a yield, it stops again.
so for now i just wrote it just as a decoration
it is very important
while (true) {
}
This will freeze your game
It runs forever.
while(true) {
yield return null;
}
If you run this as a coroutine, it will run the loop once per frame
it hits yield return null and stops
then Unity resumes it one frame later
You should check if the animation is still running once per frame
Once it is no longer running, you can exit the loop
you already know exactly how to check if the animation is running
a while loop terminates when its condition becomes false
cuz it looks like, atleast when i try it, that doesnt ends, and the mortem is just there having a seizure trying to reload an infinitely empty rifle
you can update the variable you're using as its condition inside the loop
ooooooooooooooooooooooooooh
bool whatever = true;
while (whatever) {
whatever = Time.frameCount == 1000;
yield return null;
}
but i want that time to be the exact of the animation
this will run until the frame count is 1000, and then the loop will exit (one frame later, actually, due to the order I put things in)
yes, and again: you know how to check if the current animation state is "MortemRifleReload"
i'm trying to get you to put two and two together here
oh, ok
i think i did something wrong, it scapes the loop yey...But it doesnt wait till the anim ends
{
while (reloadAnimation)
{
reloadAnimation =! animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
StartCoroutine(Reload());
yield return null;
}
reload = false;
balas = cantidadDeBalas;
//done reloading
}
}```
this checks if the reload animation is not "MortemRifleReload"
then it...starts another coroutine
get rid of StartCoroutine entirely and don't negate the IsName check
Why are you starting another coroutine inside the coroutine
Like, what did you think adding that line would accomplish
eh, looks like i didnt realized
Read your code as your typing it
aaah, that thing came with the paste
every line does something
i copy pasted a thing from another
ok
cuz i wrote that in the wrong place and then i just chopped and put it on there.....but looks like with a friend
what you mean with the IsName check, but i deleted the extra coroutine...but still doesn't wait
What are you setting reloadAnimation to inside the loop?
wat
i've been re-reading some of my old Java code, turns out old me did NOT know about indenting or spaces. i legit typed stuff like this
if(posX-15<0){posX=16; xAccel=(1-xAccel)/2;}
if(posX+15>width){posX=width-16; xAccel=(1-xAccel)/2;}
if(xAccel>15){xAccel=15;}
if(xAccel<-15){xAccel=-15;}
if((abs(xAccel)<1)&&(!right)&&(!left)){xAccel=0;}
THIS PHYSICALLY HURTS TO READ WHAT
What are you setting reloadAnimation to inside the loop?
If it doesn't hurt you to read your old code you aren't improving fast enough
you know that's actually such a good motto
damn
yea im keeping that one lol
i mean, the anim
i feel like im doing something wrong
if you don't understand what any of the code you're writing is actually doing, then you seriously need to stop what you're doing and use something like !learn to get a handle on this
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Specifically, what are you setting the value to?
What value are you reading and setting that boolean to
{
Debug.Log("reload scene");
animator.Play("Base Layer.MortemRifleReload");
reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
StartCoroutine(Reload());
}```
In the coroutine
in the loop
what are you setting it to
aaah, same
{
while (reloadAnimation)
{
reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
yield return null;
}
reload = false;
balas = cantidadDeBalas;
//done reloading
}```
i feel like im doing something wrong
wrong af
Okay, and what does this mean:
animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload")
What is this checking?
if the state is reload
originally i set it to null in the corountine
the oppositive
but i decided right now to change it to positive
for test if that may help
it didnt help
im spanish and it took me like way too long to realize the bullet count was written in spanish, this bilingual stuff messing with me 😭
xdxdxd, piola pana :3
This looks reasonable to me.
It checks if the current animation state is named "MortemRifleReload" and stores the result in reloadAnimation
If that ever becomes false, the loop ends
The issue here might be that the animation state doesn't really change instantly when you call Play, but at the end of the frame or in the next frame instead
But your code expects that it does
if (playerRb.linearVelocity.y < 0)
{
isFalling = true;
}
else
{
isFalling = false;
}
Debug.Log(playerRb.linearVelocity.y);
I have a player's rigidbody that is affected by gravity, yet its linear velocity stays at 0 when it is moving downwards. What am I missing?
I expected the linear velocity to become negative
I was thinking about that a bit earlier...
Can you show the full script? Is it actually moving via physics?
Also you should log that value with a label so you know what you're looking at in the logs
Debug.Log($"Velocity is {playerRb.linearVelocity.y}");```
you mean that i need to change the animation in the shooting phase, and after that it would work?
i got lost
Well, the gravity is moving the game object via physics in the negative y direction.
And it's on in the rigidbody, let me go ahead and send you the script.
using System;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRb;
private BoxCollider boxCollider;
public GameObject propeller;
private float gravityModifier = 25.0f;
private float verticalSpeed = 10.0f;
private float horizontalSpeed = 5.0f;
private float propellerSpeed = 10.0f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Physics.gravity *= gravityModifier;
playerRb = GetComponent<Rigidbody>();
boxCollider = GetComponent<BoxCollider>();
}
// Update is called once per frame
void FixedUpdate()
{
// Gets player input
float horizontalInput = Input.GetAxis("Horizontal");
float jumpInput = Input.GetAxis("Jump");
// Applies force upwards
float verticalForce = jumpInput * verticalSpeed;
playerRb.linearVelocity = new Vector3(playerRb.linearVelocity.x, verticalForce, playerRb.linearVelocity.z);
// Applies forces horizontally
float horizontalForce = horizontalInput * horizontalSpeed;
playerRb.linearVelocity = new Vector3(horizontalForce, playerRb.linearVelocity.y, playerRb.linearVelocity.z);
// Spin the propeller respective to the player's vertical velocity
propeller.transform.Rotate(Vector3.up * verticalForce * propellerSpeed);
Debug.Log($"Velocity is {playerRb.linearVelocity.y}");
}
}
you seem to be resetting the vertical velocity to 0 every frame:
playerRb.linearVelocity = new Vector3(playerRb.linearVelocity.x, verticalForce, playerRb.linearVelocity.z);```
verticalForce is 0 if there's no input on the Jump axis
I see, makes sense.
You should be seeing this in the form of really unrealistically slow falling
Should I make an if statement to not change the linear velocity if the jump input is 0?
Seems reasonable.
that would be pretty normal yes, only jump if you're jumping
Hello, i have a little bit of problem. i made a settings in my game, a pretty simple one. and i dont really understand why for example ticking in the checkbox to change from windowed mode to full screen. works one way, but the other dont.
So only the set value is working which i set in the inspector
you'll have to show us what you're talking about - code and screenshots from the editor
Works a lot better when I only jumped when jumping, thanks for the help.
Here's a video, let me copy the code too
Oh
you'll need to record an MP4
ah
finally
public void SetFullscreen(bool isFullscreen)
{
Screen.fullScreenMode = isFullscreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed;
PlayerPrefs.SetInt("Fullscreen", isFullscreen ? 1 : 0);
PlayerPrefs.Save();
}
how you call SetFullscreen?
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
hi guys, i've been learning C# recently and i have a question, when / how much do i need to know before switching over to unity
i have a good concept of all the fundamentals, i am comftorable with OOP, etc.
is that all I need to start making games?
I would say most people start learning unity without even knowing the bare basics of C# so you're probably well ahead of the game
how though
cuz
i mean
surely you'd have to learn the syntax and basics on what you're looking at like, whats a class, whats a method, learn about inheritence, how to store data and what different data types are, etc.
or
i guess you could just learn it through unity but
if you look up a unity tutorial, they never teach you that stuff they just tell you what code to put you konw?
idk
do you think the part for me now is just learning the different classes/methods Unity uses and how to incoperate that into my game?
you can learn them both at the same time
what do you mean the reference isnt set to an instance of an object i clearly set it in the start() function....
capital P?
no i keep forgeting rigidbody 2d is different from standard rigidbody thats the reason why lol
i hate 2d!!!
why
im just used to the way 3d works so small errors like typing the wrong rigidbody makes the code break and i dont realize it lol
oh
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also make sure the numbers on the side are visible (if you do send a screenshot). we cant really figure out where the error is if we dont know what line its on
i mean i know how to paste code i just didnt think it'd be needed considering the tiny amount i wrote
i already solved it so its fine
Yeah its some pretty tiny amount i agree with anime person
"anime person" 
screenshots are fine, its just about making sure the code is as readable as possible. makes fixing the issue a lot easier
in the screenshot they sent, we cant see which line the error is on. we can take a guess, but its still a lot easier if we can just see the numbers on the side
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());```
What is the difference between these two?
I understand the first uses the old input system and the 2nd the new input system, but what does that actually mean?
I'm using the new input system for my player movement with the keyboard too, but I don't understand how this translates to the mouse? Since I haven't set up the mouse in my inputs?
There's a thing called an Event System on your scene where these input events are setup
Hmm, I remember that should be there, but it's not?
I'm using this, but haven't set up anything for the mouse, or is that just already included?
Uh, make a ew game object and add EventSystem and Input Module if it's not automatically added
But my game works without it?
Ah, thought you were saying it didnt work. Actually maybe you don't need it for coordinates now that I think about it
Ah no, it works, I just don't understand how lol
Input class is legacy, but it includes standard properties
I'm using this one now:
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
But from setting up the keyboard movement, I thought I had to catch a mousemove event or something
like for keyboard movement I'm doing:
{
_moveInput = inputValue.Get<Vector2>().normalized;
}```
Right, Mouse.Current is based on the newer input system, but you can still use the legacy too.
highly advice to go to the new one tho. and mxiing both sounds even worse
I just posted the first line as example, I'm trying to use the new system
I wonder why this line works, without me setting up the input in my input asset:
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
where does "Mouse" come from?
It's some standard property. Unity recognizes your device and input from your mouse
So would this work for controllers too?
That exact property? Doubtful
Kinda where the 'new' input system shines though where you can have multiple different controller profiles that map similar operations
So how do I set this up with the new input system?
Because I thought I was using the new input system with this
I don't really use it much, but if you have more questions you can ask in #🖱️┃input-system
How would you guys recommend coding a rolling barrel? I ahve a capsule collider and kinematic rigidbody on it? just manually add to the rotation and position in FixedUUpdate?
why not just use the built-in physics system?
it wouldn't have a consistent linear velocity, maybe they're going for that
that one
And at the same time, The text is a child of the barrel
So when i rotate the barrel, how should i go about keeping the text still?
I think you can fix the text by freezing it's position?
like i want it to move with the barrel but not rotate as the barrel does
shoould i just not have it as a child?
My text doesnt have a rigidbody
yeah just figured lol
this is.. maybe convoluted, but here's an idea
have the root barrel object be just an rb that you move linearly, and the barrel model as a child (it should be a child anyways) animated or rotated to spin, and the text also as a child of the root
I may try tht
"Can't add script Example.cs because class name cannot be found" error when trying to add the script to my object. How do I fix it?
And yes, the class name in the file and the file name matches
Why are you not posting this on #🖱️┃input-system ? These channels are there for a reason.
Then because of people like you, others see that these specific channels are dead and dont bother posting their question
or they act like you and post their questions in general thus creating a vicious cycle
<@&502884371011731486> I actually got silenced for a day yesterday because of this person (and others) and now they're right back at it
i am just showing you how to use the server...
@formal jungle You were already warned yesterday for starting disruptive discussions. They were directed to proper channel already, if they continue ignoring directions then alert moderators.
You can have the text not be a child and use this https://docs.unity3d.com/Manual/class-ParentConstraint.html to only follow the position of the barrel. As for moving the barrel it depends on what you need. Need physics ? Just add a force to the dynamic rb. Dont need physics, then write a small script that moves and rotates it
Is... is this the game from the ads?
so does my method where I save playerprefs need to be static in order to reference it in another script?
Nop
so why doesn't GetString work for me? Says key doesn't exist
just know that their values get reset after you build
that's good but it doesn't seem to work
show script
private void Awake()
{
PlayerPrefs.GetString(levelsPassed);
}
that's all lol
do you want the saving script?
its suppose to be PlayerPrefs.GetString("levelsPassed");
public int newH;
public GameObject[] hbar = new GameObject[5];
public void DrainHealth() {
health -= 10;
newH = health;
if (health <= 0) {
Destroy(gameObject);
}
}
public void Update()
{
GameObject[] hbar = GameObject.FindGameObjectsWithTag("h");
if (newH < health) {
Destroy(hbar[hbar.Length - 1]);
}
}``` whats wrong w this code?
there are 5 triangles in the scene w tag "h"
i want to destroy one as the health decreases
remember to post your !code correctly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public int health = 50;
public int newH;
public GameObject[] hbar = new GameObject[5];
public void DrainHealth()
{
health -= 10;
newH = health;
if (health <= 0)
{
Destroy(gameObject);
}
}
public void Update()
{
GameObject[] hbar = GameObject.FindGameObjectsWithTag("h");
if (newH < health)
{
Destroy(hbar[hbar.Length - 1]);
}
}
should look like this
alright
Winlevel.levelsPassed = PlayerPrefs.GetString("levelsComplete");
Is this how I'm supposed to get it when I open the game?
may be better off using an array set in the inspector. FindGameObjectsWithTag wont give you a consistent order
thats not my issue
no triangle is getting destroyed
a few things to note here:
- do not use Find methods in Update, that is a recipe for bad performance
- how can
newHever be less thanhealthif you assign it to the value of health immediately after changing the value of health?
This could depend on when your trying to access your pref, it sounds like you might be trying to access a key that doesnt exist in prefs yet, though without seeing the full error, my suggestion would be to try checking if the key exists first, PlayerPrefs has a function for that: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/PlayerPrefs.HasKey.html - if you are stil having issues, post the full error message your getting and your full script with where you are calling your sets and gets, and im sure someone can provide more info for you
why not do the destruction of those other objects in the DrainHealth method?
already fixed
i want to drain health everytime health gets reduced by 10
oh
i see what youre saying
let me try
please finish a thought before sending a message. we don't need you to spam a single thought across 5 different messages
Ah good to hear, though out of curiosity, what kind of data are you trying to save with PlayerPrefs? Is it just 1 or 2 simple values?
if i use the FindGameObjectsWithTag method in Update() , will it keep refreshing the array every frame?
this is the error i am getting
why do you need to do that, just use a List that you populate in the inspector. then just remove the objects from the list when you destroy them. using any of the Find methods in update is terrible
alright
show the stack trace for that exception
how to do that 😞
literally 1 value for my entire game, "levelsComplete" so that if the user quits and returns another day, he can continue
it's webgl anyway so I think I can only use playerprefs for it
click the error, show thing below
Systems.collections.comparer.compare
huh? show the full stack trace
i used Array.sort to sort , thats what was giving the error
the triangles are being destroyed, however the last one remaining isnt , ill work on it.
well if you do what i suggested instead of using Find then you won't need to sort the array
maybe show your code abot sorting. I guess, you are missing the actual sorting comparison
i will try that , thankyou.
Hi, I Can't find this where this error is, Unity is letting the game run and it runs perfectly fine so far no bugs or anything but i get this error about 200 times per second
You probably need to assign the root variable of the PlayerCharacter script in the inspector.
Oh wait i swear that root variable didnt exist there before 😭
i was looking for it for so long
Finally you found eachother 🍀
It was a long journey
Does anyone know why I can't place the script on the inspector ?
the script needs to be on an object
Because that script is not an instance of PlayerMovement, it's a text asset containing the code for PlayerMovement.
A blueprint of a house is not a house.
You need to drag in an object with the script on it. That object then becomes the PlayerMovement instance
The file you have open is called CollisionCheck, which just happens to contain a reference to PlayerMovement
okay got it, thank you very much
guys, i have this line of code, I wanted to make it so that the input field isnt empty, however, it always returns object reference not set to an instance of an object
public void PlayGameStart() {
if ( nameInput.text != null ) {
SceneManager.LoadScene(1);
} else {
}
}
that means nameInput is null https://unity.huh.how/runtime-exceptions/nullreferenceexception
This one has that set, so this isn't the one throwing the error. Look at the other instances of this script
DataManager is the only game object that has this script
how have you confirmed that
Go into play mode, get to when the error occurs, and search the hierarchy then
i just made this script and havent applied it to anything else
so this error happens when i play start
prove it by searching t:Singleton in the hierarchy while this error is appearing
So then search the hierarchy while you're in play mode after this error occurs
oh, this was applied on the canva 🤦♂️
this is why you should always verify your assumptions
i mustve applied it by mistake, im sorry guys
that is fair indeed
i ran into another problem that the game still starts even if the input field is not empty but i want to fix this by myself
thank you guys!!
just note that a string can be empty without being null
string.IsNullOrEmpty() can be used to easily check myStr != null && myStr != "" @compact stag
IsNullOrWhiteSpace is typically better
how come?
because it checks if the string is only whitespace too
depends on the source of the string. I would use Trim() any input and then check for empty state
string.IsNullOrEmpty(" "); is false
string.IsNullOrWhiteSpace(" "); is true
but why allocate unnecessarily when you can just check for it explicitly
better to Trim only after ensuring that the string isn't just empty, null, or whitespace. because you have to first ensure it isn't null before trimming anyway
meh i dont think its bad unless we are working with some massive string
Sure it's not bad, and neither is calling GetComponent every frame, it's just not necessary to trim before ensuring there actually is any input
public void PlayGameStart() {
if (!string.IsNullOrWhiteSpace(nameInput.text)) {
SceneManager.LoadScene(1);
Debug.Log("true");
} else {
Debug.Log("false");
}
}
}
final code!
actually
I wanted to ask a question, its gonna be a bit hard to explain but
i have two scenes, the menu that has a gameobject called datamanager and the other one scene is called game
I have a text called User in the game scene, I made a public variable in my singleton script thats attached to my datamanager, however, how do I instantiate the user text in my singleton script?
should I use .Find? I heard its not the best way to do stuff
It's not
I assume the user text is a UI component that you want to instantiate? I would just keep the UI ready without any extra instantiation if I were you
Keep references in a class close to the UI which holds the UI elements you want to access, then get a reference from that class so you can update the UI elements
This is an easy way to get everything together in one organized class and then you don't put it all in a manager that isn't just for UI
yeah, the problem is, its in another scene
You can use a Find method to get that UI class, but you can also just make that a singleton
Find is messy because it's slow and prone to cause issues so you should not use it
why is my anchor thing missing?
Why not just use a singleton?
Is it on a canvas?
nope that fixed it ty
I wonder if it'll work if you replaced i with j for 2nd loop
That's because you're rotating it whatever degrees in one direction but then move the same amount in the opposite direction in the update call, which means nothing actually changed
no
its playing the for loop 40 times before it moves onto the next
what are you trying to do here? This looks overcomplicated and yes the loop is actually pointless because it all happens in one frame
It all happens within a single frame. it won't be visible
Yeah say it does it by 5 degrees, then it results in 200 degrees clockwise and then the next loop will do the same in the opposite direction
you need a coroutine here or to just rotate once per frame in update and then reverse direction after a certain amount of time has elapsed or a certain number of degrees
alright thanks
Your !ide is not configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
im guessing this is not it
Loops run to completion. Literally nothing else in the entire program will run until the loop ends
i see
That includes drawing anything, updating any transforms, running other scripts
what should i use instead then
Code runs one line at a time, top to bottom
i tried to rotate a few times every 2 seconds
hey guys. I wanted to know how to make trigger sensitive input in unity?
also i dont need anything else in this script
to run
new Input System
Okay, so, you want the object to remain at exactly its current rotation?
like will it register 0.5?
like for now it only takes 0 and 1
no
more like something like this
float rotation;
float speed = 40;
float maxRotation = 40;
void Update() {
rotation = Mathf.MoveTowards(rotation, target, speed * Time.deltaTime);
transform.localEulerAngles = new(0, 0, rotation);
// reverse direction
if (Mathf.Abs(rotation, maxRotation) < 0.01f) {
maxRotation = -maxRotation;
}
}```
actually maybe.
havent fully tried triggers yet there tbh.. you want a smoothed value?
But you just said you don't want anything else to run
that would include updating the object's rotation visually
So that would mean you want the rotations to perfectly cancel out and achieve nothing
ah i see
yeah. Actually in a hackathon rn and they suggested me to add trigger sensitive things
thank you!
new input system Unity has built, probably have more flexibility you can also configure your own Inputs / hardware
The Update function is one frame. It is the definition of what a frame is. The frame is rendered after every object's Updates finish running. Until an object's Update finishes, the frame cannot finish. You can never see the "intermediate state" of an Update.
ah i see
If you rotate an object 10 degrees left in update, then rotate it 10 degrees right in the same update, those both happen in the same frame
meaning nothing happens
how can i configure my own inputs?
so the entire thing is happening in one frame
and here is my ass thinking it was just hyperbole for "really fast"
no it's literally "this runs once each frame"
That is, in fact, stated plainly on the default script template:
is there any way to go back to a certain line then?
no
Update is the frame
you cannot separate it across frames
It is the literal definition of what a frame is
i was asking how you did it
not what id need to do
With a coroutine, or one frame at a time by tracking time in update
Maybe you can rephrase,what you actually trying to do with going "back"
A coroutine lets you write a method that can pause itself and get resumed later.
i dont know how to make a coroutine
https://docs.unity3d.com/Manual/Coroutines.html
time to learn about them (:
yay......
someone stab me
if you hate learning new things, then you're in the wrong line of work
Coroutines are easy and powerful once you start using them! ^
if you need to run a method across many frames, coroutines are great
Awaitable has entered the chat *
I pass Awaitables to StartCoroutine 😛
I just hate that Coroutines cannot have return values for example
me and coroutine are gonna be great friends
Love them since Unity 6 🙂
Also the ability to jump back to mainthread
yeah swapping threads is cool when dealing with unity main loop only API
it's pretty nifty
I used Awaitable in one project to allow me to interleave game logic (e.g. moving a unit) with visuals (e.g. slowly moving the unit's sprite between the start and end positions)
Okay now I want to learn about awaitables - they sound a lot more useful than a coroutine 😆
If I was just calculating a new game state (and not actually showing the sequence to the player), I skipped over the visuals and instantly returned
It worked out really nicely
coroutines are fine for most usecase
but def do learn awaitable cause its great especially if you're stuck between coroutine and traditional async
unity has entry methods for both
IEnumerator Start()
async void Awake()
There's basically a power scale of delaying things,
Coroutines are like base form Goku, Awaitables are Super Saiyan, and async is Super Saiyan Blue. ||Invoke is Yamcha||
I based my entire state management on awaitables, calling other substates and so on. I did not even touch coroutines again since then 😄
how do you deal with Get/Post methods ? do you not use WebRequests at all ?
the grabbing directly into assets is kinda handy ngl
I heard unity is strange with HTTPClient idk if it still applies
I use them with awaitables without any issue so far. Any special case why you askin?
I'd say Update is base form, and Coroutine is Kaio-ken . . .
So what would be InvokeRepeating be? 😄
just curious , thats the only thing I haven't tried yet away from Coroutine, I'm so used to WebRequest. I never used anything else in unity since.
ofc in regular .net apps I use Async Task with dependency injected httpclient
So a Coroutine would use something like Wait X Seconds where an Awaitable is just like 'When I'm done I'll come back and we can carry on?'
Awaitable can use the Regular Task.Delay
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Awaitable.WaitForSecondsAsync.html
old code but with awaitable, working just fine:
wait
oh ok its still a unity webrequest just inside awaitable.
good enough 😄
can there be 2 yields in 1 coroutine
you can have as many yeilds you want
yep 😄 Nothing fancy there
as many as you want
oh my..yeah starting one every frame not good lol
thats a lot of swinging going on tho, sounds like a good party 😄
they will be fighting eachother setting values (dont ask me how I know)
also it's looking to me like your IDE is not configured @twin pivot
You should get it configured so you get autocomplete and error highlighting
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
you're probably missing a stepo
i'll do it after i finish this
you can also try close VS, regen project files
its working now
but only once
well i guess thats expected
it's doing exactly what your code is saying to do
rotate right
then rotate left
then it's over
like regular method it only runs once
yus
you can put a while loop inside
in coroutines they wont stop other lines from running
(as long as there is a yield inside the loop)
and it can ever exit 😉
unity will tell you otherwise by not telling you anything anymore 😄
Daddy went to store to get cigarettes...
i knew that
yea i definitely knew that
As far as you are concerned, a coroutine is a method that you can pause and resume
opens task manager
RAM usage 📈
i think i just corrupted my save file
the scene file?
what is "the project file"
in the unity hub
thats not a file
Ah well, just re add the folder
its just the root of your project folder
you can delete the entry without deleting the project
reminder to always hit save shortcut
Why are you starting the coroutine every frame
This is just a really really circuitous method for putting StartCoroutine in update again
all you needed to do was wrap all the swinging() code in that while loop. Not add a random while loop to start
ah i see
YES
MY BUTTON IS NOW WIGGLING
yk
what if you just make this animation with condition instead of all this code
how do i make an or in these onWall = Physics.CheckSphere(WallCheckLeft.position, WallDistance, Wallmask) || (WallCheckRight.position, WallDistance, Wallmask);
im making this to learn how to code so
And is &&
Or is ||
but it's not clear what you're trying to do
You have to call the function twice
why do you need an or ?
Just use the onWall ?
i dont know the normal way of doing this
you can't just or the parameters
iam trying to say if he's on the right wall or the left wall but it's giving me an error
You would need two CheckSphere calls
and to OR the results of them
I would just snap that line in half
bool leftWall = Physics.CheckSphere(WallCheckLeft.position, WallDistance, Wallmask);
bool rightWall = Physics.CheckSphere(WallCheckRight.position, WallDistance, Wallmask);
bool wall = leftWall || rightWall;
jinx
There's no reason it can't all go on one line
but it's too long. icky.
only thing about this is it's actually slightly less performant because now we don't get the short-circuit benefits 😢
true
but that's a micro optimization 😛
if only C# had lazily-evaluated expressions
like python
python does not have lazy evaluation
bool leftWall = Physics.CheckSphere(WallCheckLeft.position, WallDistance, Wallmask);
if (leftWall) return true;
bool rightWall = Physics.CheckSphere(WallCheckRight.position, WallDistance, Wallmask);
return rightWall;

then what does
Haskell delays evaluation until it's necessary, i believe
it's not super common (you usually have to do it explicitly, like by writing a zero-argument anonymous function that performs the calculation)
a "thunk"!
if it works it works
"my fps is 2 but it works!" ™️
niice
am i misunderstanding how "linear velocity" works?
public void FixedUpdate()
{
Debug.Log(_body.linearVelocityY);
// Bird rotation
// Idk why unity does this
_rotation = Mathf.MoveTowardsAngle(_rotation, _rotationAngle, _rotationSpeed);
transform.rotation = Quaternion.Euler(0, 0, _rotation);
if (_body.linearVelocity.y > _rotationSwitch)
{
_rotationAngle = _downwardAngle;
}
}
public void OnJumpPressed(InputAction.CallbackContext context)
{
// Apply jump force
// Only when the button is first pressed.
if (context.started)
{
_body.linearVelocityY = _jumpForce;
_rotationAngle = _upwardAngle;
}
}```
i have this player script, and i was checking linear velocity... and it NEVER reaches 0? it keeps on going into the minuses
i thought since i have gravity pulling the player down at all times, itll reset when i jump, but it doesnt..
uhh this is my rigidbody setup
pretty sure its literally the default 😭
You should probably not depend on it ever reaching exactly 0, since there's always a chance it goes from positives to negatives within a single frame or vice-versa
Don't depend on it ever reaching any specific number
i see
i was just confused as to why its always so low
-8.81 shouldnt be possible to reach
Why not? That's only about a second of gravity
since the player is constantly jumping and the velocity should be set to 3.35
and IVE never seen it be set to 3.35
...oh my god im working in FixedUpdate()

the issue is that i was trying to do something when the player is FALLING (usually meaning negative velocity) but that doesnt seem to work
🙂↕️
does anyone know why my camera goes a bit up when I crouch then immediately sprint?
https://paste.mod.gg/kedoezrfxrih/0
A tool for sharing your source code with the world!
is there a way to add force without having collisions
If you don't want collisions, don't have a collider
forces are for the Rigidbody
what don't you understand
i cant find an example prompt of it
hi, im starting to learn c# and is code monkey's tutorial good?
I don't recommend code monkey
he will teach you how to use and be dependent on his own libraries and such, not to learn C# and Unity in general
ok
i prefer a video format
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
rigidbody2D.AddForce(new Vector2(x force, y force), ForceMode2D.impulse/force);
i would say imo hes more intermediate
this is basically it right
i cant find it
i think sebastian league has the best/str8 forward unity crash course playlist
Welcome to this introduction to game development. We'll be starting from the beginning, so no prior knowledge of programming or the Unity game engine is required.
Unity can be downloaded here: http://unity3d.com/get-unity
Watch episode 01: https://youtu.be/9iCnjdXEfMA
If you'd like to support these videos, you can make a recurring monthly don...
ok
how would you rate vegetarian zombie
watch the couple of episodes of this.. (or all of it if u want)
alr thanks
whats ForceMode2D.impulse/force) ?
its a pretty good playlist
rb.AddForce(Vector2.up * forceAmount, ForceMode2D.Force); //gradual force
rb.AddForce(Vector2.up * forceAmount, ForceMode2D.Impulse); // Instant force
the two types of force isnt it?
yea
rb.velocity = new Vector2(moveX, moveY) * moveSpeed; u can also set velocity
theres other modes too but impulse and force are the two i use most often
its a great playlist..
nice simple..
straightforward..
no fluff or clickbait stuff..
it really helps break down the very first fundamentals u need to know
- variables
- methods
- classes
and so on
yeah, you recommended it to me too
watched all of it and it was pretty great
alot of the other game-type videos are like:
"so u wanna make a game?"
"let me show u how to throw crap together that u dont understand in less than 15 minutes to make a game!"
you wont understand it but it'll work! 😄
all of it?! very impressive..
heck ya, ur on a roll
🧡 anytime!
as long as i see ppl putting in some effort im always willing to help if i got time 🙂
im always lurking.. 🦈
in the shadows . . .
the depths of discord 🌊
what does this mean?
You can't create a new variable with the same name as an old one
you can't declared variable inside of condition (if)
You already have a variable of the same name outside the current scope . . .
oh i found the fix... i had the same code underneath that i forgot to delete before i left to do something else...
morning, is there any way i can get this bool in C#?
i want to deactivate a gameobject in the script
thanks friend
how can I clone this asset and put it in the same folder?
What do you mean "same folder"?
the characters folder
You're not gonna be putting anything in any folder at runtime
Sure, what have you tried or looked up?
you're better off just putting those objects into a list, but you could technically just foreach over the transform
its so over complicated for no reason jesus christ
it's really not
I wish I could just reference the object and do like foreach object in object:getchildren or something
since you're clearly ignoring everything that everyone is telling you and refusing to bother googling it, why are you even here?
It is, quite literally, even easier than that
The thing you wish it did instead is longer than the actual solution
did google it
perhaps im not smart enough for unity
{
Something(child.gameObject)
}```
its litterly this easy
considering you think it is incredibly difficult to do this, i sincerely doubt you actually put any effort into reading the information returned by any google search
how do I get gameobject tho
usually by dragging it in
do I have to manually drag an object into the component every single time
or by running this code on the object you want to use
You'll need to tell it which object you want to loop over somehow
it can't just divine that knowledge from the Spirit Realm
you gotta tell it
yea thats where I misunderstood
would be simpler if you could just reference any object that is in the scene
like in some other engines
then you should start by learning the absolute basics of how c# and unity work. there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good next step after you understand the fundamentals of the language
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
you can
by dragging it in
that's how that works
😔
learn the basics of c#
Neither Image or Canvas is a transform, and you can't just windmill slam a foreach loop in the middle of your class scope and expect it to work
A Canvas component is not a collection of objects . . .
also we went over this yesterday, you can't just have arbitrary code outside of a method
I have other ui elements inside of my canvas
!vscode
I'm just trying to loop through the buttons I have inside my canvas
isnt transform just position and rotation related?
srry needed the link
stop what you are doing and go learn the basics. #💻┃code-beginner message
Then why did you say you wanted to loop through child objects
That's a different thing
child being canvas, child objects being buttons
Button is not a GameObject. It's a component
parent* I mean
That doesn't matter. Your canvas—in the hierarchy—is just a GameObject with children, not a collection: array, list, etc . . .
Mabye you should see if there's a function that can get a specific set of components in an object's children
If I were to assign a button to a variable, I'd type public Button blabla; so I just assumed that the different objects like button and canvas were the type
Those are the types, of the components
The Transform component is what determines the parent/child relationships of GameObjects
I could use someones help with this issue I am having when turning my game into a multiplayer one.
My game a is 3d virtual art gallery and I use 2 gameobjects to determine the players camera/orientation/etc. Basically they communicate with each other to al;low the player to turn and move and see everything. The problem, is that I am using photon to make my game multiplayer, and I need to turn my player into a prefab and the gameobjects can no longer have the right reference needed.
For example, my CameraHOlder using a gameobject in my avatar called CameraPosition, but I dont know how to put the reference needed since im turning my avatar into a prefab.
- assign it at runtime
or - add the camera as part of the player prefab rig
note that you should really oinly have one camera anyway per client
So if you go with 2. you would destroy or disable any camera except the local player's
for the second option, would it be alright to just put my cameraHolder as child of my avatar?
wdym that the transform component determines parent/child relationships, isnt it just the hierarchy that does that? here I have Slot and Slot (1) inside of CharacterSelection, CharacterSelection is a canvas and the slots are Images
it's an option but you might have to have it deparent itself when it spawns
The hierarchy is a visualization of the child/parent relationships that are defined by the Transform component
Notice that if you look here: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.html
Transform defines the .parent and .GetChild methods and properties
because the child/parent relationship is defined in the Transform
CharacterSelection is a GameObejct which has a Canvas component attached to it.
Slot and Slot(1) are GameObjects that have Image components attached to them
I see
so if I wanted to loop through the children of CharacterSelection I'd have to use CharacterSelection.GetChild(index)
assuming CharacterSelection was a variable of type Transform then yes, that is one way to loop through the children of that object
Assuming CharacterSelection is a reference variable that holds a reference to the Transform of that object.
trying to add this so I can drag it but everything just turns red
not even doing anything with it its just there
Because you've got nonsense in Start
And the compiler has just given up
it works fine when I remove that one line public Transform lalala
Yes, when you remove the broken line, there is no longer a broken line
How do you expect to make a program if you have no idea whatsoever how to use the language required
None of this would be an issue if you spent some time on learning tha absolute basics
you said I have nonsense in start, that's why the one line turned red, I say nothing is red when I dont have the one line, you say everything is red even without it
Yes, when you remove the invalid line of C#, then all the red lines go away
Protip: This line is the problem
what im asking is why that line would cause a problem, because all I'm doing is declaring that variable??
You're attempting to declare a class variable inside a function
You cannot use access modifiers inside of a function
if you would bother learning how c# works you might have some understanding of why that was invalid
how did you decide it'd also be a good idea to do multiplayer..
oh sweet christmas it's multiplayer
not doing it of my own free will unfortunately
just have to do it
🤷♂️ you dont even have the fundamentals of c# down. How do you expect to do anything in unity, which uses c#
Perhaps if you spent as much time reading the documentation as you've spent wasting everyone's time on Discord you'd be done by now
or instead of lashing out and making a shitty attempt at insulting the people helping you like a whiny toddler, you could try learning the fundamentals
all I did was declaring a variable inside a function rather than inside the base class, not that big of a problem, I dont understand why you could just tell me that from the beginning
Do you know what public means or are you just slamming that in random places
I dont understand why you have to be so pretentious, I just declared it inside of a function which apparently doesnt work in c#, at least not when its a public variable, you couldve just told me that instead of displaying your superiority
At this point it's because you've spent zero effort trying to problem solve on your own and are expecting us to write it line by line
You've exceeded your patience quota for the day, but we have plenty of spite available
I'll let you get back to whatever you were doing then, I'm sorry if I'm having trouble figuring out the syntax
Why doesn't this work but only the first time around:
if (int.Parse(name)>int.Parse(Winlevel.levelsPassed) + 1)
{
button.interactable = false;
}
when I save it after completing a level into player prefs, it works
it gives me an error at the parse, which should be impossible
Try logging the values before the parse and see what the value is right before the error
Try using TryParse instead . . .
if you do not understand the syntax, then maybe take the advice that has been given to you half a dozen times now and go learn the fundamentals of the language because that includes learning the syntax
Why would it be impossible? Time to use Debug.Log and see what you're trying to parse.
Then that would mean that the thing it's printing is , which is, in fact, not an integer
An empty string is not an int
ahhhh I know why it happens
cause it's getting the value from the playerprefs
so it doesn't work unless I save
i.e. pass a level first
so can I do if null, then value is 0?
why are you saving an integer as a string in PlayerPrefs?
You know what good call
so how do I reference a failed parse?
I named the levels as 1, 2, 3, etc
trying to figure out which ones are locked, which unlocked
when for example level 3 is passed, the levelspassed variable is set to 3
so again, why are you saving an integer as a string in PlayerPrefs
then for all the other levels, int parse, if higher than 3, disable button for the level
I am saving a string, what
you already have it as an int, and you have the option to store an int in PlayerPrefs
so why are you instead saving it as a string
I'm not, I'm doing this
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if (int.Parse(SceneManager.GetActiveScene().name) > (int.Parse(levelsPassed)))
{
levelsPassed = SceneManager.GetActiveScene().name;
PlayerPrefs.SetString("levelsComplete", levelsPassed);
}
right so you have an int that you could use, but choose to use a string instead
ah yeah ok you have a point
Why are you trying to parse a string name into an int???
I explained it above
Ok, don't mind me then . . .
ok so how do I handle that first load where there's nothing in the player prefs? Add a bool called hasData = false.
If !hasData, then levelspassed = 0
else load levelspassed fomr playerprefs.
I would flip the bool once the first level is completed.
Does that sound about right?
Just store the last level completed in an int
if it's 0, then you've beaten none
if it's 1, you've beaten 1
and so on
yeah I do that
but on awake the menu scene loads that variable from playerprefs
And yet you're storing it in a string
what is the error
I mean, not error, it's an empty key from playerprefs
I only save it when I pass the first level
So you know what can't be empty string? An int
Oh because it defaults to 0?
nor can int be null
that would work then
yes yes good solution
it being 0 by default works in my case
thanks
almost like that's precisely why we have been continually saying to use an int instead
even if there wasn't somehow a default, you can specify a default if the key does not exist
I know man, but when I complete a level, if I make it an int I still have to parse it because (name of level completed) = that int
still have to parse the name of the level into an int so it's the same amount of work
Or you could use the build index
not that I'm not listening to you guys, I'm just trying to use my brain too
And even then, no it isn't. You're literally parsing half as many values
I didn't think about that other thing
Parsing one object is less than parsing two objects
you could also design your systems to not rely on the scene name and instead use some object in the scene or its build index or something
yeah I know, I could also be a good programmer, but I'm not 😄
I'll listen to you and make the playerprefs var an int
Has anyone had this issue before where, while using Photon, the person who creates the room can move around and turn their camera but anyone who joins the room is stuck in place and cant turn their camera?
Very common problem with a variety of causes. #archived-networking
alright thanks
Im setting up joystick and for some reason GetButtonDown wont work but GetButton does - what am i doing wrong
provide more context such as !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
{
ToggleInventory();
}``` not working ``` if (Input.GetButton("Menu"))
{
ToggleInventory();
}``` Will work but to many registers
that is not a helpful amount of code
A tool for sharing your source code with the world!
Are you doing this in FixedUpdate
heres my toggle class
no update
maybe thats where im going wrong - didnt think it was physics thought fixed up date was more for that
that is a single method, not a class. and not even where you are calling GetButtonDown
yh its in update
You seem to only be doing UpdateMenuStats in the first poart
not in the else
I'm assuming that's what modifies menuStatus?
oh nvm
yh so menuState resets each time
it works now, thanks guys
menuStatus
you sure you don't have those reversed?
Do you mean on another button?
Using getbutton does it every frame and i get this
I am also using the old input manager
if that helps
yeah exactly