#💻┃code-beginner
1 messages · Page 404 of 1
hello, does anyone know how I can fix the camera on my character without having my background completely stretched? as you see I am in isometric, I am trying to add a character in 3d but I want it to be in isometric view in my 2D decor, I searched a little on the internet I saw that it was necessary put a camera on it with a rotating parameter of X:30 Y:45, the problem is that afterwards... my background is completely disfigured and stretched lol. But my character is displayed well, it is in isometric there
Rotate the background so it faces the camera
whenever the autoBtn() is being run, at the second for loop, it sets all the issongsource to true instead of setting them one by one every time each audo source is done playing (the goal of the code is to play 4 audio sources one after another automatically, and possibly looped)
actually it works but then it breaks my tilemap 😦 nothing is proportional anymore, it makes my brain go crazy lol, I tried to base myself on this video and do like it but I can't get the same result https://youtu.be/v4S1ClQJg2E?si=j6yqE99iALrqR84p&t=119
In this episode I added a 3D model of a character into my 2D isometric game. This process was a bit tricky but at the end everything came together nicely. I learned a lot of new things such as handling Animations in Unity (state machine), implementing a simple AI for my character and pathfinding on an isometric grid.
Support me on Patreon - ht...
ok so one thing i wondered about, if big blocks of ifs are bad and instead setting index of x is more optimal
if i have many different paths of code is it good store various functions in array and run them by index?
Not a code question. But fix the ppu
the PPU determines how many pixels there are per unit (hence the name)
the default of 100 means that a 16 pixel image winds up taking up 0.16 units in the world
It's probably because you use i in the lambda expression =>. The compiler has to do extra work in order to be able to refer to the variable from inside the lambda, this causes your issue. By the time the lambda executes, the for loop will already have finished running, so i does not contain the number you think it is.
To solve that, create a copy of that variable inside the loop and see if that fixes it:
for (int i = 0; i < 4; i++)
{
int ii = i;
yield return new WaitWhile(() => thing[ii].isPlaying)
// ^^ NOTICE USE OF LOCAL
}
This is so vague, "setting index of x" doesnt even make sense in relation to if statements. If you need an if statement, there isnt a way around having one.
Just use the profiler and see for yourself if you even have a performance issue
yea i did, works now 😛
So then another one. In my 2d game as usual you can farm stuff and chop trees. So i would make another grid and just put it over the other one for such objects as stones, ore or trees?
or how is that done code wise
did it like so, no luck though
No you just make more methods and call them. This is the standard practice when you need to split code by area of features
Do you mean procedural generation? If not, it would not be done with code
You can do layers with the tilemaps, and just place it
well i want my char to be able to run within the 2d world on grass, chopping down trees, stone and such
so i guess procedural would be good here, yea
Expand the lambda expression into a block so you can put multiple statements in them: () => { }
That way you can add logs in it
Ok, that is something completely different than procedural generation. I am not sure which part you want. Are you just talking about collision handling? Or generating the world? Or what?
so first i would love to have grass blocks as my background and then some stones appear on it that can be mined
randomly generated would be a bonus ofc
Hello i have the following two pieces of code:
void Start()
{
timer = FindObjectOfType<Timer>();
scoreKeeper = FindObjectOfType<ScoreKeeper>();
}
and
scoreKeeper.IncrementSeenQuestions();
When i try to call the method "IncrementSeenQuestions" i get the error "NullReferenceException: Object reference not set to an instance of an object'
Ok, well google procedural generation.
And look up layers.
Which line is the error on?
Probably scoreKeeper?
The error is on the line where i try to call the method
Do you HAVE an object wjth ScoreKeeper in the scene?
Omg dumb me, i forgot to attach the script
i aplogize i dont get it, im getting an error
Thank you
yield return new WaitWhile(() =>
{
// other stuff can go here
return songSource[ii].isPlaying;
});
It's like a method body
oh i see thank you
how do I call a function from a click? I know how to do it in the inspector but I need help with the code
wdym by "a click"? A click on what?
Buttons have an gnClick you assign in the inspector
yea ik
assign that to the function you want to call
but all I get is this
you dragged the wrong thing into the slot
you need to drag a GameObject with the script attached to it into the slot
you dragged the script itself
very common mistake
all it does is print 4 tuimes in a row
That would mean isPlaying is false, so it does not wait (or maybe just a frame)
oh yes let me explain how it works one second
in order to run autoBtn() you press a button and after you press the button you press the play button in order to run the song itself
oh so i should check if the button is clicked with a bool and if yes run it inside the play buton script?
right?
Nah I think what's happening is that it doesn't start playing until the next frame, so if you call Play() then immediately check if it's playing it'll say that it's not.
A hack would be to wait until it's playing before waiting that it has finished
yield return new WaitUntil(() => songSource[ii].isPlaying);
yield return new WaitWhile(() => songSource[ii].isPlaying);
Try that
Or yield return null; as a replacement to the first one
yeah it works thank you so muchhhh
why can i not assign the text? when i drag the text on it nothing happens
Is the text element TextMeshPro or legacy text? The field is for legacy text
TextMeshPro, thanks, i'll modify the code
In code that would be TMP_Text
can someone help me with this error heres the code ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PauseMenu : MonoBehaviour
{
public GameObject pauseMenu;
public static bool isPaused;
// Start is called before the first frame update
void Start()
{
pauseMenu.SetActive(false);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
if(isPaused)
{
ResumeGame();
}
else
{
PauseGame();
}
}
}
public void PauseGame()
{
pauseMenu.SetActive(true);
Time.timeScale = 0f;
isPaused = true;
}
public void ResumeGame()
{
pauseMenu.SetActive(false);
Time.timeScale = 1f;
isPaused = false;
}
}```
in your script the variable 'pauseMenu' is null. You need to assign it in the inspector.
it works, thanks.. i started Unity today
what about the error message do you not understand?
ohh ok i forgot about that
ty
keep in mind that Update() doesn't run on disabled objects. So if pauseMenu is the same gameObject as the gameObject with this script it won't work once it's disabled.
i made the pausemenu object in the code the pausecanvas for the inspector would it work then?
well, try it out and see
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
im really not sure what could be messing up my determinism anymore
i've
- got everything running on a fixed timestep
- used seeded random functions, and save the seed for replay
probably is just hierarchy, it works now 😄 thanks
what else could i have missed?
well i mean i have now a procedural generating world
but it should be big so people can explore. Now i have created width and height of 10000
thats a giant map and takes time to load. How to fix this?
how do publishers fix this? only generate more when player is moving in that direction? and then a bit by time like minecraft? instead of generating it all?
how do publishers fix this? only generate more when player is moving in that direction? and then a bit by time like minecraft? instead of generating it all?
Yes this is one option.
If it's procedurally generated, it's a good option.
none of my buttons are working heres the script and inspector ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public GameObject pauseMenu;
public static bool isPaused;
// Start is called before the first frame update
void Start()
{
pauseMenu.SetActive(false);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
if(isPaused)
{
ResumeGame();
}
else
{
PauseGame();
}
}
}
public void PauseGame()
{
pauseMenu.SetActive(true);
Time.timeScale = 0f;
isPaused = true;
}
public void ResumeGame()
{
pauseMenu.SetActive(false);
Time.timeScale = 1f;
isPaused = false;
}
public void GoToMenu()
{
Time.timeScale = 1f;
SceneManager.LoadScene("Menu");
}
public void ExitGame()
{
Application.Quit();
}
}```
another option would be to create a new 200x200 map for example when leaving the current one. But i guess its harder to do
Have you built a development build so you can see possible errors in the dev console?
its not an error in the logs
How do you know?
i think its position weird
that sounds functionally the same as incrementally generating the map
how would I even make a dev build\
You said its not playing at all
i did 10000x10000 on height/width in unity on my procedural gen map
Now whole unity froze. any idea?
like the editor its fine
What did google say?
Have you assigned those methods in your buttons' OnClick() UnityActions or some such?
yes
for example heres the resume
I think you may have dragged the game script from your Assets window instead of the GO which uses that script from the scene hierarchy
the script is called PauseMenu and i dragged it into the "game" GameObject that holds everything in the game
everything shows up and the esc key works but the buttons dont
Oh I see. Are the buttons visually reacting to hover/click events? Have you sprinkled in some Debug.Log()s to see if the methods are getting called?
they dont react to the hover or click events it might be because my game is in first person so whenever i press esc when the game is running the camera still moves and the walking sound plays if i were to presd wasd
didnt see this, will probably have a look at that
they arent getting called
ill get a screen recording and show you
damn it man why the hell does it work in editor but not build
It may be possible that you have a later Canvas drawing over the pause menu canvas and intercepting the events... Are you using the newer Input System?
idk what the newer input system is and i do have another canvas
the "rawimage" is basically the camera since i technically got rid of it to make my game look pixelated
I get the following error: ObjectDisposedException: SerializedProperty questions.Array.data[4] has disappeared! Can someone explain please what is this error? Because i expected to get a NullReference error since it seems like im trying to acces an object that doesn't exist
just realised there's no point in doing this
can you show the code?
what's the context? Do you have a custom editor?
And the full stack trace?
open the sprite settings and for pixel art use point filter
For giggles, you might try moving that canvas up in the hierarchy before the pause menu canvas...
Unity provides two methods for handling input - the older Input Manager, where you generally just ask it for the current state of an input device like Input.GetAxis("horizontal"), and the newer Input System in which you generally configure "InputActions" and have a number of different options to hook them up to your code... Edit > Project Settings > Player > Other Settings should have an "Active Input Handling" dropdown to select which one you're using
thanks! how to make this the basic import option for all future imports?
I don't even know what is a cutom editor, but i guess i dont use since I dont know anything about it
yes
i switched it to new what do i do now
i cant move now
Maybe switch back 😅. The newer system is definitely more robust and worth learning, but for the moment, you should sort out the issue at hand first before doing anything that might complicate matters
how do i fix my problem tho
Np , you can check this forum https://discussions.unity.com/t/how-to-change-default-import-settings/157318/6
probably some other "invisible" object blocking your buttons, try disabling everything else and then see if it works.
use online paste bin so i can see full script and can you tell me where the error coming from
the raw image could be it but if i disable it i cant see anything
and when i disabled it nothing changed
I did solve it. I had a SerializeField array with scriptable objects and I removed all the items from the inspector and put them back again. I guess it was a bug or smth
What about disabling that Canvas, out of curiosity?
still cant see and nothing changes
Select the EventSystem in your hierarchy, in the inspector at the top right click the 3 dots and switch to "Debug Mode". Now Your Standalone Input Module should have a field called "Current Focused Game Object". Hover over the buttons and see if it changes to something that is not 'None'
good to hear
i get the debug part but idk what you mean by the rest
Do you have a gameObject called "EventSystem" in your hierarchy?
i put it to debug
does it have a component called "Standalone Input Module"?
And you see the "Current Focused Game Object" field? If yes, when you hover over an object it should be set to that, like so:
How should I handle SoundEffects for my game? Make an event that a SoundFX script listens to and plays when event fires off?
it still says none
mhh, you might have "bugged" your game by doing the changes to your camera, since mouse events rely on the camera to calculate the position.
is there a way to fix it
thanks
hello?
Probably, but I can't really help you over discord.
how could you help tho
You have to figure it out yourself. Try Making a new Scene with nothing but a button and see it if works, then one by one add stuff from your main scene until it no longer works.
im just not gunna add a pause menu
i assigned the sound but it says i didn't
lock rotation in rigidbody
i could make him static i guess, but i feel like this will block features later on
oh
constraints
yup that worked, freezed Z, ty 😄
np
okay so now i want to give the stones a collider aswell that i can adjust
the problem is just: is it bad for performance when giving each tile a collider or is there a performance issue later on?
otherwise i could just give the stone texture a collider and rigidbody
so you want an exact hitbox?
why classes can have list[i].int++ edited directly but structs cant
Hello, I am new to C# and was just wondering if there is a built in way to generate a random integer between a certain range?
Sure, see the Random class
UnityEngine.Random to be exact
There is also System.Random but it works a bit differently (instance instesd of static)
where can i ask for graphic stuff?
Since this is messed up at import for some reason (hands and foot)
Thank you
Been trying to steer clear of tutorials, and couldn't find anything on google, or I just wasn't searching the right things.
Hello everyone, I have a problem. While testing my game in the Unity editor, my recording system in json format works very well, but when I install it on my Android mobile phone, it does not save some places. For example, while the transform values of a character are recorded properly in one script, the animals I catch in a different script are not recorded. How can I solve this problem?
Hi, I'm using Mirror's networking solution in my project. Does anyone know what these errors are at all about? They show up everytime I launch my game. I believe they've only showed up after changing my scene via LoadScene()
This is my animal code
Well, just googling "unity random" or "unity random int" would've given you the docs page
how can i make things invisible during gameplay?
disable their renderers
it's like telling a baby to jump
reference the renderer:
public Renderer myRenderer; // drag and drop in the inspector
and disable it when desired:
myRenderer.enabled = false;```
cool
Once you know the basics of referencing stuff in Unity you can use it for everything
okay so i have a collider for the whole second layer at all objects. So when the player runs at a stone, he will collide. But the collider is of course not custom sized for each object. Stones need another collider size than trees and so on.
How can i now assign a box collider/custom collider to just the stone tiles within this tilemap?
you can set a custom physics shape for every sprite from the sprite editor
thats what i looks right now
ah okay, ill try it
Does anyone know the reason?
just a heads up this is a coding channel
Hello, here i have a game manager script. I get the error NullReferenceException: Object reference not set to an instance of an object
EndScript.ShowFinalScore () (at Assets/Scripts/EndScreen.cs:18)
GameManager.Update () (at Assets/Scripts/GameManager.cs:23)
Here is the GameManager script:
"'cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
Quiz quiz;
EndScript endScreen;
void Start()
{
quiz = FindObjectOfType<Quiz>();
endScreen = FindObjectOfType<EndScript>();
quiz.gameObject.SetActive(true);
endScreen.gameObject.SetActive(false);
}
void Update()
{
if(quiz.isComplete == true)
{
quiz.gameObject.SetActive(false);
endScreen.gameObject.SetActive(true);
endScreen.ShowFinalScore();
}
}
public void OnReplayLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
"'
And here is the function ShowFInalScore:
public void ShowFinalScore()
{
finalScoreText.text = "Congrats! \n You got a score of "
+ scoreKeeper.CalculateScore() + "%";
}
I have to mention that i assured that every SerializeField is properly assigned
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
reference on line 18 on EndScreen.cs is null
You mean this endScreen.ShowFinalScore();?
if you don't post the code properly how am I supposed to know which one is line 18 ?
How do i post it properly
if thats whats on line 18 then endScreen is null
did you not read this
#💻┃code-beginner message
I tried to add cs in my message but it didnt work
that doesn't show lines either because its not meant for entire classes..
oh ok
i think i know what it is, thnaks
if endScreen is ony line 18 then its endScreen is null
but thats not in the other script is it
the null ref is coming from EndScreen line 18
the second line tells you wich script started the call
yes
its possible you might have a copy of script on another object, with it unassigned
Ok, i will track it down, thanks!
you can type t:EndScript in the hierarchy searchbar
it's only assigned to one object
try log, you can click it after it prints
public void ShowFinalScore()
{
Debug.Log($"Changing score text on {finalScoreText} using {scoreKeeper}", this);
finalScoreText.text = $"Congrats! \n You got a score of {scoreKeeper.CalculateScore}%"
}```
where did you put log, copy mine. then click on the log
This finds all objects that have that script?
correct, in that scene yes
Ahh thats useful thanks
interesting its running twice
click the first one
which object it brings you to
huh..can you screenshot this object's inspector
also
when do you set quiz.isComplete = true
anyway it looks like the one missing here is scoreKeeper
you can see "using ___" is blank on the first line debug
But i do FIndObjectOFType<ScoreKeeper>
and you have one in the scene ?
also try moving it to void Awake()
at least by the time you call method on scoreKeeper its not there
i do
are you somehow calling ShowFinalScore before Start ?
I think Update can do that sometimes before start
yes I asked where you set quiz.isComplete to true
Well, i have a timer, when the timer runs down on the last question thats when i make quiziscomplete to true
but i guess i can debug.log quiz is complete
did you try this real quick #💻┃code-beginner message
Yes, the problem was with when I set quiz.iscomplete to true
I solved this
Thank you so much!
Yea :))
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Assets\Scripts\drops\BreakableTile.cs(9,13): error CS0246: The type or namespace name 'Dictionary<,>' could not be found (are you missing a using directive or an assembly reference?)
why?
@queen adder you are missing using System.Collections.Generic; - if your IDE is configured, it should be annotating Dictionary with an error, and providing an option to import relevant namespaces
Hello guys, I'm very new to Unity. So how can I fix this?
well you cannot directly use Transform position like that as its not static
you must call it on an instance of Transform
unity has a nice property of transform in MonoBehaviour script, referring to this object's transform
(capitalization matters)
this code is ment to wait until one song is finished and then it passes to the next song automatically, and it works, however when you pause the song while its playing the code thinks that its done so it skips to the next one and when you resume its a different song, i tried to make a bool in order to check when the song is paused but had no luck. any other suggestions?
you have nested methods
why does it matter
you can see autoBtn is inside annother method
because it can't compile if it has an error?
no
This
ok wait
You've got a compile error
Does anyone know why 'velocity' isn't being filled in my intellisence? I can't figure this out for the life of me, and it's hard to learn when VSC isn't working right
try close vsc, did you try regen project files ?
Oh, thank you. I was too silly to notice that Transform is a class.
indeed transform lowercase, is a property they have for easy access to that class the object has
instead of doing GetComponent<Transform>()
I can't figure out how. I keep being told to go to Preferences > External Tools but it's not there for me :/
yeah then you're missing half the stuff
!vscode
make sure you check the Package Manager stuff
remove the Visual Studio Code Editor package, make sure the Visual Studio Editor one is Update to 2.0.20+
i have vscode! as well as the plugin loaded
will do. sorry, new to all this
i cant find the issue bro it was fine 2 seconds ago i must have deleted smt by accident
if you're not seeing VSCode in the dropdown of External Tools , you need to follow the Package Manager part especially
got it. thank you
you probably deleted a bracket somewhere
or added ?
followed the steps through one more time. visual studio editor is already installed and in the project, but there's no external tools tab
Visual Studio Editor package is installed but is it at least version 2.0.20 ?
yep
yep
can you show what your external tools page looks like in unity
You want Edit > Preferences, not Project Settings
I'm not sure, but I would assume so. It's here on Windows:
it won't show up for me on mac, that's the issue
so you didnt follow link i sent you did you
its right here
What a strange thing to vary based on platform 🤔
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
should i send the whole script or just thepart i think is relevant?
use the links send the whole class its easier
alr ty
seriously, it's so needlessley confusing. thanks navarone
its because you're not using your isPaused condition
i removed it it didnt work
why would you remove it if you need it
because it didnt work
show how you tried to use the bool
and then tell me what i did wrong
sure. you can also check things like the cliplength vs how far in the clip you are playing rn
tbf the Mac convention is that Preferences is in the [app name] menu. That's where it is in all apps. It's not something that Unity came up with
yeah very true. I commonly look there for app preferences in general
the shortcut key is usually the same too command + ,
in fact, that's the standard shortcut for user preferences
it always works. it's very nice
this code is ment to wait until one song is finished and then it passes to the next song automatically, and it works, however when you pause the song while its playing the code thinks that its done so it skips to the next one and when you resume its a different song, i tried to make a bool in order to check when the song is paused but had no luck. any other suggestions? https://hastebin.com/share/ideduboyez.csharp ( no error in console )
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The more I think about it, the more logical it seems to group conventional application stuff like that. I find myself mildly disturbed by this touch of Mac envy 👀
their hardware is overpriced af. But I cannot stomach windows.
macos is superior, but prob bias from loving linux so the UNIX thing just "feels right"
except in Blender! Blender doesn't put it there (or really put anything else there)
but cmd-, still works
You might also be able to wait for .time to approach .clip.length
thank you alot of very muchness i am going to try that rn
I feel that. For my part, I find their hardware really nice but detest their OS 😁. I do definitely prefer NIX conventions for filesystem organization and the like though
hah yeah. The had the best laptops for sure for a while. I find my unity runs wayyy better on my 2014 macos than my 2022 pc..Something is wrong lol and its not the hardware
same hardware runs just as smooth on Mint, linux
yo how do i write that code wise
approach
oh equals
don't == floats
bigger than then?
yeah always use those with floats
No, use Mathf.Approximately
thats also an option
where do i put that in the code
Whenever you need to compare the floats
eg
isItClose = Mathf.Approximately(float1, float2)
yield return new WaitUntil(() => songsource[ii].time == songsource[ii].clip.length);
this is the line
like where do i insert it
is just a regular bool
Put the floats on both sides of the == operator as the parameters of the Mathf.Approximately method
the return is result of , if they are approx the same number
though for a clip/time I would use if(as.time < clip.length) // not done with song
(don't copy exact just example)
Unity has small mistakes when calculating floats, so it's rarely that 2 floats can be equal, when compared with the == operator
so in the big scheme of the things of stuff
does it really matter
approx or bigger
both reliable right
if you need more "precise" check approx is better
meh
in most cases < and > work perfectly fine
When willing to use the >= operator, consider
if (f1 > f2 || Mathf.Approximately(f1, f2))
The same goes for <=
You can also create your own methods
MathExtension.ApproximatelyGreater(float, float)
MathExtension.ApproximatelySmaller(float, float)
nah those stuff are way too smart for me for now but thanks ill remember that if i ever get good at ts
it workssss
thank you very much guys
all of you
if you want approximation, just check if the (absolute) difference is less than a tolerance value. that way, you can determine the range of error . . .
You can put this somewhere in your project if you want
namespace UnityEngine
{
public static class MathExtension
{
#region Approximately
public static bool Approximately(this float f1, float f2) =>
Mathf.Approximately(f1, f2);
public static bool ApproximatelyGreater(this float f1, float f2) =>
f1 > f2 || f1.Approximately(f2);
public static bool ApproximatelySmaller(this float f1, float f2) =>
f1 < f2 || f1.Approximately(f2);
#endregion
}
}
something like this ?
public static bool Approximately(float a, float b, float margin)
{
return Mathf.Abs(a - b) <= margin;
}```
Comparing floats with the == operator won't work too well
close. you'd use (a - b) < margin. if it's below the margin then it's considered even . . .
ahhh
basically, margin is the error of precision . . .
I see the original is return Mathf.Abs(b - a) < Mathf.Max(1E-06f * Mathf.Max(Mathf.Abs(a), Mathf.Abs(b)), Mathf.Epsilon * 8f);
Although this should be done with Epsilon
yeah thats what source does
Mathf.Approximately uses Epsilon . . .
you can just change 1E-06f to increase the margin
I know, I'm saying my code should be rewritten using Epsilon
oh, i was just typing that in general. i didn't see your message about Epsilon . . .
i have a button that skips 5 seconds ahead of the sound clip thing if its relevant
I don't think .time will ever naturally exceed the length of the clip(?)
oh ye
print the numbers to know for sure what the values are
that makes sense
will => fix everything
Not sure how the current time of the clip can be greater than its full length
It can just be equal when finished
im wiser than the machine bro what can i say
shoulda moved this to code-advanced ngl
alrrr it workss
thanks once again
private IEnumerator waitForClickPress()
{
bool done = false;
while (!done)
{
if (Input.click)
{
done = true;
}
yield return null;
}
}
How can I check if a click event happened?
waitUntil could be handy here
Cool
actually not even needed the extra alloc
isnt what u have already working ?
Input.click is nonsense though
so put the correct one
Then how do i make sure The mouse has been clicked after a starting moment/Event?
void Update()
{
if(Input.GetMouseButtonDown(0))
{
clickMouseButtonEvent = true;
}
}
I did this but I'm not sure it's concurrency proof
Oh wait, I think I just gotta set clickMouseButtonEvent to false right after the event occurs
yea
Are the links pinned the best way for me to start to learn scripting
My player sprite looks fine in scene view but is all pixelated in game mode, any idea why?
Make sure the slider at the top of your game view is all the way to the left
Hello, I have a question. I have a list that conains elements that are null. When I try to change them I get a null reference exception. Is this normal behaviour of unity?
Change them how? This isnt unity stuff, this is c#
Does anyone know why my rigidbody addforce wouldnt work if I collide straight on but does at an angle?
Thing is I want to keep an index of gameobjects (transforms actually) and at some point I set some empty indexed to null
like
List<Transform> Transforms = new List<Transform>();
Transforms.Add(null);
that is not a problem at this point but when I try to
Transforms[0] = gameObject.transform;
I get a null exception
I can post the full code
screenshot error and send code via link
Ok I get it it was calling the code before list was set up at the awake I belive
Thanks you for your help !
animator.SetFloat("Speed") = CatBody.GetComponent.velocity.x;
Why's this invalid? I'm trying to set an animation parameter to the object's current velocity
why would that be valid? you cannot assign to the return value of a method. look at the docs for the Animator.SetFloat method
mkay, will do
there are...a lot of problems with this
yeah, i'm not very good at coding. quite new too
start with the beginner c# courses pinned in this channel
i've got the basics, no worries
with all due respect
just confused with this one part
no you do not
not according to this you do not
this line is really wrong
i'm well aware lmao
it needs to be (id, value)
should i attach the current speed to a variable and then use that in place of the value?
"public void SetFloat(string name, float value);"
that is the signature of Animator.SetFloat, yes
you need to give it a string and a float
CatBody.GetComponent.velocity.x; Certainly not grabbing it this way lol
the string that i'm naming is the string of the animation parameter, isn't it
i am painfully aware
if CatBody is rigidbody no need to do GetComponent
maybe i'm confused. i thought the function of Animator.SetFloat is to name an animation parameter and then give it a float value
good point
It sets a float parameter.
The float parameter is identified by the string.
I would agree with this description, though. It's just not how I'd word it.
i see
so i'm trying to update an animation parameter with the current speed of my game object. how should i go about doing that?
i was going to have it update it each frame with said command
Pass it in as an argument
i would start by adding a field to your class that holds a Rigidbody
e.g.
public Rigidbody rb;
Drag the Rigidbody component into this field.
what is the type of the CatBody field?
you mean in-engine?
public Rigidbody2D CatBody;
Okay, so just do CatBody.velocity.x .
You don't need to use GetComponent here. You already have the component.
yeah, i got rid of that a bit ago. however, SetFloat is underscored with red
GetComponent<Rigidbody2D>() would be necessary if you didn't already have a reference to that component
Components are the big boxes in the inspector window
"no overload for method"
well, show us what you have
then you didn't provide the correct parameters
animator.SetFloat("Speed")
You are invoking the method with one argument.
It wants two arguments.
1 is not 2
parameters go in the parentheses
you are then trying to assign CatBody.velocity.x to the return value from the method
you don't pass parameters with =
the method returns void so this is especially bogus
You said you have a basic understanding of C#, but you're trying to pass an argument with the = operator
this is Very Wrong(tm)
i have a basic understanding of coding, enough that i was able to code the thing to move myself. i'm still becoming aquianted with C#, i know i'm far from a software engineer
Literally look at the link I sent to see how ot use the function. You don't need to guess.
so i need to preface it with public void, rather then "animator."?
bear with me guys. there's a learning curve to this stuff, i learn by doing it
Looking at examples is better than guessing
i am looking at it, no worries
in the documentation it's shown as "public void SetFloat(string name, float value);"
that's the signature yes
but look at the EXAMPLE
there is example code when you scroll down
ohh, i see. i'll give that a try
The signature does tell you how to use it exactly though
you can probably just clear them and ignore, if it comes back restart the editor
is it a random error?
if its UnityEditor could be something just went wrong for a second within tabs or separate window
If it's an editor bug, then usually yes
It occurs again and again
It has to do with this code
could even be a bad asset
with the _itemsInTable.Clear() method
this would be something that would be inspector or something on the gui
did you restart unity?
yeah
because if I comment it the error doesn´t occur
you're removing or deleting an instance somewhere . . .
an Instance of what exactly?
did you comment out the entire method or just the Clear line?
just the Clear line
_itemsInTable is your inventory?
its the items in the crafting station
are those items instances that are created/instantiated or prefabs?
it is an array of a class called ItemAmount
you mean a List<T>? array doesn't have the Clear method . . .
yeah sorry
hmmm, you don't have a custom inspector for this, do you?
I have that slider thing for the quantity
it seems that the problem is that I have to minimize the _itemsInInventory Serialized list
could be a bug
and now the error doesn´t occur
may be
it's a problem when the size of the list is changed . . .
yeah, some items are removed when the size of the list changes and it's attempting to access it somewhere . . .
so it is an editor problem
are there usually a lot of items in the list?
Not really
try creating a new list instead of clearing it. see if happens . . .
This error occured with 3 items in the list
should I try to create a new List?
yeah . . .
Same problem
I´ll just keep it minimized for now
anyway, thanks a lot for your help
the other option is using an array with a fixed-size. if you know the max amount of items needed to craft anything, use that as the size. then you create a method that manually nullifies each element . . .
Hi, i'm beginner and i try to implement perlin noise but i have some problems
i used a gameobjects and put a worldgeneration script on it
procedural generating chunks when player moves to edges (well with a bit distance so it does not look ugly)
but how to center it
as you see in the preview, its more "top-righted" lol
fixed it but its not equally
bottom left is missing LOL
(2D Game) im having trouble with parent/child objects atm, i have a rigidbody attached to an object (a circle) that just rolls done a hill, i want to set a child to it that doesnt actually "roll" but still follows the parent, anyone know how i can achieve this?
guys i made a simpy script for 2d car movement... but i have issues with basically infinite acceleration speed
so im a beginner, learning fundamentals. I want a procedural generation for my world and now seeing that with hard working, good descriptions and some time chatGPT gave me 400 lines of code for just 3 blocks, patches, generation, trees and stone... i could never write that within next time by myself. Never ever lol. I can maybe try to read and understand, but thats it and probably adjust a bit.
Should i stop doing that?
You'll need to controll the applied torque based on the current velocity.
Probably yes.
Chat GPT might be able to write a quick prototype, but it wouldn't be able to scale it to a working mechanic. And you not being able to understand it prevents you from spotting any potential issues and extend the code properly.
i have 2 objects in my scene with a PlayerInput component. how can i do FindObjectsofType<PlayerInput> and only get the one that i want?
you dont, just directly reference the one you want since its in your scene.
thats not possible bc the code is on a prefab
you must spawn the prefab at one point, instantiate returns the spawned object. you directly have a reference either way
hmmm, maybe that ll work
well i could define the public classes but i wouldnt even have an idea of how to code/write the tilemap generation around the player lol
that's the point of learning. don't just give up on attempting to learn because you found a tool that approximates intermediate knowledge
but whom even to ask if chatgpt is bad xd
like who would teach me now procedural gen
start by worrying about understanding the fundamentals. then when you actually understand that you can start learning more interesting topics. you'll also actually have a better chance at actually understanding the learning resources available like the documentation
i did the c# microsoft course and the unity one
But yea i guess it wont make a beginner into a pro that quick
😦 rip
I'm very new to programming, and am currently following a unity tutorial for making a platformer that tells me to use "Vector3.one" when the character moves. Is there any way to set the scale to 2 on all axes instead of one?
multiply Vector3.one by 2 or create a new Vector3 with 2 on every axis
thank you!
You yourself. There are plenty of learning materials online that you can use or research existing projects/samples.
storing a generated tile/chunk of a tileset (within a chunk) sounds specific to me
hmm
The specific implementation might be specific to your specific case, but with experience you'll find out that it's probably very similar to what other people do with slight variation and different names.
If you're doing procedural generation, there are plenty of games and tutorials to reference. Take minecraft for example.
please help i can't find loadnextlevel() and I also did everything like create a event and my script is also correct . I Followed the brackeys tutotial
wait
i mean i can understand what steps are used to make whatever
But translating it into code is hte harder part
like i know it uses chunks, i could define an int for chunks
i know it generates more chunks when the player gets to the edge/into the direction, could define an int for this aswell
But then how to actually generate more or let a tile be in a chunk etc. thats the hard part 😦
You should configure your !ide first. This is not valid code.
Also, double check with the tutorial. There's no way this code is the same as in the tutorial.
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
• Other/None
i am getting error but he is not getting error and he also got loadnextlevel() in the dropbox
What's "it"?
There're no chunks or procedural generation functionality in unity by default. It's either your own code, or you're using a library. In the first case you should have the answer, since you wrote it. In the second, you'll need to read the docs of the library.
Then his code must be correct and your is not, as I said. Double check it.
Share the tutorial link.
ok wait
Let's make a way to reach new levels!
● Download the Project Files: http://devassets.com/assets/how-to-make-a-video-game/
❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU
····················································································
This video is part of a mini-series on making your first game i...
watch from 8:33
Spot the difference?
ohh
Or a few steps back:
ok
This is valid, but it's not the same as your code
thanks
Pay more attention
thanks
from what i understand i would need to set an int for chunks
int chunks = 10;
so that one chunk is 10 blocks
now i would want that chunk to contain grass and sand tiles, but randomly assigned.
hmm i might just watch a video on this idk, cant think of it
This tells me absolutely nothing. That variable is something that only makes sense in the context of your code. Without knowing the context it's literally gibberish to me.
i might have overcomplicated my problem. is there a way to enable/disable only one Input action map in code? i dont want my player to use any input exept the pause action map when the game is paused
Is it good idea to change Scriptable Objects at runtime?
I know that sometimes yes, sometimes no, but rn idk.
I made SO for characters, and i wamted to do skins for them, can i add skins in SO trough script when game init? and dont touch it? Until pkayer relaunch game ofc.
like, having Dictionary<string, SkinClass> in SO
Why would it need to be in an SO though?
like, when i create character, i get data from SO, not just an script
That doesn't really explain much. But if I were to put that dictionary anywhere, that would probably be in some kind of manager, like SkinManager or something, which would be either a MonoBehaviour or a plain class.
That is assuming that the dictionary is constructed at runtime.
Maybe when creating character, ask SkinManager for prefab instead of getting it from SO?
I still didnt started making skin system
Hello, I am working on 2D game. I got some enemies and a player. I wrote a script to make the enemies follow the player, to make the player take damage and to display the health level in a health bar. But the enemies can't find the player Health script when they collide with the player. (I am instantiating the enemies when the game starts.) Can someone help pls?
Scripts,
Health Script: https://pastecode.io/s/kahq3pgi (attched to the player)
Damage Script: https://pastecode.io/s/gx2ftpmy (attched to the enemy asset)
Enemy Spawner Script: https://pastecode.io/s/4zz4c47r (attached to an empty game object)
If your skins are defined at editing time, it's fine to put them in an SO for convenience. If not, then there's no point to put them in the SO and would just cause more confusion.
In editing time? you mean in editor? they will be done only in editor, not in builds, so, its ok?
but i also dont want to flood editor with bunch of lists, so, id rather do everything in code
Wdym by "can't find"? Do you get an actual error or is that an assumption?
The whole point of an SO is that you can assign data in the inspector. If you don't do that, there's no point in using the SO really.
oh... i think i get it, then i mostly likely do like you said, make an skin manager to store everything, thanks for helping.
I would make Static Instance for Health script, so, there will be no need to use GetComponent or asign it in inspector
but it doesn't effect the task I am tring to do right?
I'd avoid doing that. It's what we call an inappropriate use case for singletons
In my unity multiplayer project, I have character animations which work fine. But when I disable my character's body for my local player, everything works except I can't see the animation of the enemy player, it just slides around.
(Using photon and for disabling the character I made a public game object then referenced my character there)
I would first of all use CompareTag instead of .tag ==
Then I would put a debug BEFORE that if, and after
Well, ok..? i used Static Instances a lot, is it that bad?
Generally yes
Why?
what if you wanted two things to have health
Why force an inappropriate use of static when it is unnecessary. It constrains you and often will cause worse issues down the line if you want to expand your code
i am trying to disable just one action map, but now i dont even get an error in the unity console, it just crashes
I would have named it "playerHealth" and "enemyHealth" and make static instance only for one
- im not doing multiplayer game
i used to have and script called "Core" that have references and methods related to all important stuff like game Saving and etc stuff, it has Static Instance. Is that bad?
Well, something like a SaveManager DOES make sense as a singleton
Or even just a static class
so you make your code not reusable meaning you have to do more work to copy/paste the bits that you want to reuse. you introduce the opportunity for any object at any point in time to potentially change the state of your game leading to nightmare debugging, and you avoid learning how to do things the right way because you've got a hammer, so every problem must be a nail, right?
Or having static instance for script that move between scenes?
you don't need a singleton for an object to be available across scenes
i kinda know
But I am usning the same script for all the enemies. Which I ment was that there is a separate game object named enemy as an asset which contains the needed scripts to function with the box collider component and rigidbody2d. And when the game starts the enemy spawner spawns the enemy asset in random places.
Have you considered additive scene loading?
but is it better to use FindObjectOfTime?
no..
why do i need that for game with 2 scenes
To keep data in memory and avoid an unnecessary singleton
Best to use a serialized reference
Bad practices is more about making habits.
It might work for your simple use case and project and that's fine, but as a beginner, you're getting used to it and missing an opportunity to learn the correct way of doing it.
Then when you finally have a case of where the "easy way" doesn't work, you're gonna get stumped, because you never learned the correct way.
i DO keep data in memory, in script that move between scenes
Or even worse, your project becomes so messed up, that you can't continue without rewriting a big chunk of it. Simply because you chose the easy road.
And I'm saying you could do the same by just keeping the things you want to move IN a scene, without the script for just data
What if i make build system and i have to use TryGetComponent?
What about it? Then do that
Can anyone tell me about it?
We are not talking about one script/class(that is fine and correct actually). We're talking about singleton being a bad practice for stuff like player health.
Either #archived-networking or #🏃┃animation
more likely photon server
and provide details about the setup/code
Can anyone tell me how to access a script in another game object without accessing it using a public variable?
I mean, that is a choice sure. Not necessary though
It works perfectly fine when I do not disable my character for my local player so I'm kinda confused what could it be
GetComponent should work. Make sure that the object that you're calling it on has the component.
Ok thanks
Did you see my response to your first question?
#💻┃code-beginner message
what component? You mean the method TakeDamage() ?
alr, ill try to use Static Instance less..
The GetComponent call you have in your code
I mean this method in your code:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (playerHealth == null)
{
playerHealth = collision.gameObject.GetComponent<Health>();
}
playerHealth.TakeDamage(damageLevel);
}
}
Add the debugs I mentioned.
Then come back
You mean like this?
Sorry, I do not download files. But if you have two debug.logs, one before the tag check and one after, then yes
yes. I do.
The goal is to find where the issue is.
Is OnCollisionEnter called? Is the tag on the object it is called for?
Next time, follow the !code sharing guidelines
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
I don't see how that's different from your previous code...
What the function here is supposed to do is to recognize if any pieces are a different group than the rest. If there are any, we delete the current piece that's executing the function, and just before that we create a new piece for each group recognized. Problem is Unity crashes when roomManager runs the function.
SplitHandler function -> https://gdl.space/sazefuvero.cs (I asked gpt for comments to clarify what's going on, just in case)
Entire Piece class -> https://gdl.space/oxivikegam.cs
Entire RoomManager class -> https://gdl.space/xekefuhobi.cs
(Unity crashed at the end)
crashed as in closed to desktop. or do you mean the editor froze
I suspected that this happens because new pieces are created before they are broken, resulting in infinite pieces, but they are first removed, then split. I have no idea how this happens now.
as in I can't enter the unity app and need to close it via task manager
I'd check the console but nothing logs since it crashes immediatelly
that would be the editor freezing. which means you have an infinite loop somewhere in your code preventing the frame from ever ending
When the enemies collide with the player nothing debugs. Which I think it does not detect any collision.
the problem is I don't know where it could be situated in the code
attach the debugger, enter play mode and cause the code to enter its infinite loop, then break all using the debugger and you'll be able to inspect what the main thread is doing
wdym attach the debugger
please learn how to use the tools available to you https://unity.huh.how/debugging/debugger
idk what attach means in this case
then you didn't bother clicking the link i sent so i'm not going to help you further
@slender nymph ||Kinematic Rigidbody Body Type set to Kinematic. Is Trigger is off.|| so this means if my rigidbody is keynematic the collider is off?
no
It does not mean tbat.
However, with a kinematic rb, OnCollisionEnter will not be sent, unless the OTHER object has a dynamic rigidbody
this line is simply explaining what "Kinematic Rigidbody" is referring to in the matrix. it refers to a rigidbody set to the Kinematic body type with a non-trigger collider
bro is this the right button
Does it say attach?
says attach but looks different from the example, is this what was supposed to happen?
Yes
so now if there's an infinite loop we'll still be able to see it?
so now break all as boxfriend said
anyone?
I get this
after clicking view a doohickey appears on the bottom.
what do I do next
this isn't helping
what do I do with this
If anyone has an idea on what might be causing the error/infinite loop, I'd really appreciate it
what do you mean it crashes? is the editor freezing, is it crashing to desktop? or (more likely) is there an error in the console causing play mode to pause?
it behaves like there would be an error, but the console is clean
so play mode is being paused?
yes
Is that when you connect to process? Can you show the parallel callstacks?
can you unpause it?
yes, but then the inputs dont work
now just to be clear, i am referring to the pause of play mode, and not an in-game pause functionality. but you are disabling your inputs there
This doesn't look like it's frozen.
At what timing did you break?
yes, if i unpause the play mode no inputs work
cause this to happen again then screenshot the entire unity window with both the game view and console windows visible before you unpause it
I'm not exactly sure what a timing is in this context, but I pressed break all about 3 seconds after unity froze/crashed
now i restarted my project and am now getting an error but its about baked global illumination, though i have no baking enabled at all
Hmm. Well, perhaps breaking at that point wouldn't provide any clues. Did you try looking at the logs after the crash?
please just reproduce the issue and screenshot the editor like i asked. this error is unrelated
i cant anymore, now i just get this error
after the crash unity just cannot be open. When I preview it by hovering my mouse on the app I see the last log was Fragment(clone), which is most likely logged by this line.
that means something has the new created fragment in it's group
What I mean is looking in the !logs files
I opened the file. What should I look for?
The last logs and wether there are any errors.
Also, try commenting out the code that you added last and see if that fixes the freeze.
are they top to bottom or reverse?
top to bottom
crash (closed by your os) is not freeze (not responding)
this is the bottom of the file
yeah I tend to mistake the two
your case is more like freeze (you close it by task manager)
Looks like it's repeating. Unless that's expected, I'd assume that you have a recursion somewhere. Did you try commenting out that code and seeing if it freezes?
This is what I commented out. It's not freezing, but now it's not even breaking the walls, which is strange. I see only the regular fragments in the hierarchy and there are no other pieces in the room (not even clones created by that function)
I fixed the not breaking walls part by commenting out this line also
now hte SPlitHandler thing just logs all groups found within a piece and the group's fragments
the error in the play mode seemed to be a weird unity bug where it wants me to bake global illumination even though all my lights are realtime, i somehow resolved that and now playmode works, however now i cant access my pause menu, is there any issues here?
what do you mean by you "can't access" your pause menu?
Make sure none of the instantiated objects runs the commented code. That would cause a recursion and freeze the game.
like the pause input doesnt register
am i supposed to know what input you are referring to?
its this input, it worked before i added the first if statement in SetPausedStatus
how could we do that? I thought of adding a condition whether a fragment was preplaced or generated, but a piece can always have more than 2 groups and such
do you have anything actually enabling and using this input anywhere?
wdym? isnt it enabled from the start?
that depends entirely on how you are using that input
Well, first of all, I don't understand why instantiation of new pieces is handled by pieces themselves. That should be called from some kind of manager.
I could do that in the room manager, you're right
the only time i use it in a script is in this one, i just need it to access the pause menu while being able to disable the player map
so should I just run the commented out part in the roomManager or the entire function?
I don't think it's as simple as that. You need to figure out why a recursion happens. Stepping through the code, when the freeze is about to happen, might provide some clues.
i dont see anything special in the Awake() of class Piece....
I'm confused as to why the instantiated pieces run the function. It's initiated by the roomManager on all pieces inside the current room, but the function itself creates new ones, so that's what confuses me
It doesn't have to be in awake. If the issue is due to infinite object instantiation, it could be in wherever.
I'm backtracking what it could be
Maybe they don't.
Maybe it's purely the number of instantiations growing each update.
Try printing the number of room.children
before that for loop
foreach (GameObject child in room.children) {
if (child && child.TryGetComponent(out Piece piece)) {
piece.SplitHandler();
}
}
should I keep that instantiation part commented before I run this?
No. Keep it in the state where it freezes
You can then look at the log file.
Another thing you can try is placing a breakpoint in the RoomManager LateUpdate after the freeze
now something different happened
I heard the wall breaking noise, flash and saw the aprticles play like 30 times in one second before unity froze
(still bottom of the file)
I don't see you printing what I suggested
it didn't freeze
just got so laggy it's at like 0.01 FPS
Make your logs more verbose. Just printing a number is very confusing.
ok
If it's not freezing, you can use the profiler to see what the issue is.
my player sprite looks normal in scene view but it all choppy in game view, any idea why?
Just to be safe, I'd also add the current object name to the log.
you mean gameObject.name?
where was the profiler?
Yes.
Window-Analysis
again, heard a bunch of noises and then unity froze
you meant unity, right?
I have to restart it now, it froze completely once again
damn why is this so problematic
wait no
it's just ultralagged
but I can't interact with anything in unity now
Yes. Unity. If it's freezing, you won't be able to profile. But the added logs should provide some clues.
how many pieces and fragments in your world
@magic panther Create a thread, please.
why doesnt my code allow me to move at crouchspeed while in crouch state
but it allows me to move at sprintspeed in sprint state?
- large blocks of !code should be posted using a bin site 👇
- if you are grounded and not sprinting your move speed is going to be assigned to walkSpeed because of your if/else if chain
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
what do you reccommend i do @slender nymph
Think real hard about your conditions and then look at your if/else chain that is completely separate from that first if statement
hi guys i am new to this server, and i wanted to know were to start with learning how to program. so uhh id love to know if you have any suggestions
There are some excellent beginner courses pinned in this channel
oh i didnt think to check the pinned messages, thank you!
I have a set of objects I need to switch between with numerical keys. I am unsure of how to do it other than something like this:
if(key1) inventoryObject = 1
if(key2) inventoryObject = 2
if(key3) inventoryObject = 3
Any idea you can share?
The numerical keys are called Alpha0, Alpha1, Alpha2 etc.
The KeyCode is an enum, which can be converted to int
The KeyCode.Alpha0's integer is 48
Start a loop with i = 0 and check for the KeyCode being Alpha0 + i
for (int i = 0; i <= 9; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha0 + i))
{
// ...
}
}
Enumerable.Range(0, 10)
.Where(i => Input.GetKeyDown(KeyCode.Alpha0 + i))
.ToList().ForEach(i =>
{
// ...
});
So it's going to be
inventoryObject = Enumerable.Range(0, 10)
.First(i => Input.GetKeyDown(KeyCode.Alpha0 + i));
public class newPlayerScript : MonoBehaviour
{
[SerializeField] Transform cameraT;
Vector2 look;
void Start()
{
}
void Update()
{
//mouseLook with Vector2 look
look.x += Input.GetAxis("Mouse X");
look.y += Input.GetAxis("Mouse Y");
cameraT.localRotation = Quaternion.Euler(-look.y, 0, 0);
transform.localRotation = Quaternion.Euler(0, look.x, 0);
}
}
``` why is this simple line of code not allowing my camera took look up and down, only left and right
dont know if this is the right channel but does anyone know how i can stop a double image from showing on a object https://i.imgur.com/DhMRK4l.png there is only one image made but for some reason it shows 2 images on the object. if i dont use a image with a transparant back its fine but as soon as i make it transparent i see the image twice
someone please help, i dont understand this, its so simple
Hey I have a difficulty with Newtonsoft.Json JsonConvert.DeserializeObject<T>(File.ReadAllText(path)
I can serialize classes just fine when some props are customer enum ("bla": 1 serialized to MyEnum.First)
but if the prop is nullable custom enum I get string value of the enum instead of enum ("bla": 1 serialized to "First")
i tried to use StringEnumConverter and while debugging it did convert it to enum, but the final result of the the load function was strings
do anyone know how to handle this?
Did you properly reference the camera?
Your vertical changes with the mouse will only have an effect on whatever camera T is.
Other than that if it's got a rigid body component, check the constraints.
hey i want to make a script for a stamina bar and as long as i press the shift key the stamina will drop. However when i press the shift key it decresses once and not as long as i press it?
You probably have something like GetKeyDown or GetKeyUp instead of GetKey. Without seeing the code we can't tell what is wrong
i have tried all of them
if (Input.GetKeyDown(KeyCode.LeftShift))
{
playerMoveSpeed *= playerSprintMutiplier;
isRunning = true;
currentStamina -= runStamina * Time.deltaTime;
if (currentStamina <= 0)
{
currentStamina = 0;
}
staminaBar.fillAmount = currentStamina / maxStamina;
}
maybe im an idiot and cant see the problem
GetKeyDown is true only the first frame where key is pressed. Use GetKey
Remove Down
thanks it works
if (currentStamina <= 0)
{
currentStamina = 0;
}
currentStamina = Mathf.Max(currentStamina, 0f);
now it just crashs my unity
probably an infinite loop somewhere
gives me an error that says overflow in memory allocator
Show the whole error message
Not sure why you make it seem like the code I've sent chashes your Unity
You'll have to show the entire code, which may cause this
no its not your code as soon as i changed it from down to input.getkey and play unity
i havent even changed that part
So you'll have to change the other code
You may
i changed it back so it wont crash anymore
This code isn't what causes the crash. Show the whole thing
how do i share the whole code?
"I changed it back so that it doesn't work, because I have no intention in trying to fix the part of the code, which is causing the right way to accomplish my objective to not work"
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
''cs
That's the reason the sites are mentioned above
what? im sorry i didnt understand
meaning try paste it into one of the sites
what sites?
these
i did
Some of them are mentioned by the bot #💻┃code-beginner message
This is not a site
is coroutines really the most common way to add intervals to stuff
yes
awesome thanks
Yes, you can also use Update with Time.deltatime or async Tasks, but Coroutines are more comfortable and commonly used in Unity
The only issue I see is playerMoveSpeed *= playerSprintMutiplier; because it is called every Update it will skyrocket really fast. But I'm not sure if it will cause this crash
Depends on use case
yea im just starting
Coroutines are an easy way to have intervals, but you can also use Tasks, or Unity Awaitables if you want somewhat asynchronous support
There's also timers, and the Invoke and InvokeRepeating method. These work much better as an interval over writing a Coroutine, for example
collision detecting with Inactive object somehow:
{
if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "Enemy2" || collision.gameObject.tag == "Enemy3" || collision.gameObject.tag == "Enemy4" ||
collision.gameObject.tag == "Enemy5" || collision.gameObject.tag == "Enemy6" || collision.gameObject.tag == "Enemy7" || collision.gameObject.tag == "Enemy8" || collision.gameObject.tag == "Enemy9")
{
if (!hasShield)
{
if(collision.gameObject.activeInHierarchy)
{
hasCrashed = true;
crashCount++;
audioSource.PlayOneShot(carCollide);
}
}
else
{
StartCoroutine(ActivateShield());
}
op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
}
}```
The method should not fire at all if the other object was inactive since the beginning of this frame
so whats happening?
It likely wasn't inactive since the beginning of the frame
im using object pooling, so the object remains inactive for a while till its required to spawn
also sometimes when i collide with a car, collision happens but my player doesnt die, happens occasionaly
Folks would need more information to help you with the second issue. Your first is likely due to the other object not actually being inactive since the beginning of the frame.
shall I share a video?
and for the 2nd issue, what shall i do to fix it?
You should probably share the code, inspector images and whatnot for the player and the object that isn't behaving appropriately.
this is the code for the collision of other cars with player
around 7 seconds before the end you click on the active green car and it has no visuals. Odds are the car you hit was the same and became inactive when you hit it
would it be due to object pooling?
if it did hit it the 1st time, it becomes inactive as per rule
then become active only if the pool is empty
I also checked the car's order in layer which is perfect
don't think so, the active car has everything right but is not visible. the only reason I have for it is order in layer
make it active from the inspector and see if it will become visible, if not try to change some parameters to make it visible and find what is it exactly
oh wait it was the sorting layer
i set it to 'player' and it got fixed
also if u look at 0:16 seconds, the collision was detected but the life didnt get affected, this issue is very rare
try to debug it. You probably have a bug somewhere in your code
Why do you have so many inactive cars on your track?
those are the pooled cars
extra cars which arent needed rn so they are inactive
that makes sense although I would put them under a seperate parent object so as not to pollute the hiearchy
yeah i will do that as well
also what do u think about my game? does it play good? atleast from visual pov
this is my 2nd original game, yes imma beginner
yeah, it looks OK
Yuppp
Obviously the RigidBody2D is on your player, can you screenshot that
In order to call GetTransformInfoExpectUpToDate, RendererUpdateManager.UpdateAll must be called first.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
when i tried to change a tree from 16x16 to 16x32 size
doesnt work like that i guess?
I've seen that one while working on a 2D project.
I don't think I ever worked out what was causing it.
btw
if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "Enemy2" || collision.gameObject.tag == "Enemy3" || collision.gameObject.tag == "Enemy4" ||
collision.gameObject.tag == "Enemy5" || collision.gameObject.tag == "Enemy6" || collision.gameObject.tag == "Enemy7" || collision.gameObject.tag == "Enemy8" || collision.gameObject.tag == "Enemy9")
can be replaced with
if (collision.gameObject.tag.subString(0,5) == "Enemy") {
}
oh, okay i wil do that
or even
if (collision.gameObject.tag.StartsWith("Enemy")) {
}
Yes
Also, collision will always occur on inactive objects.so you might want to add an isActiveSelf test in your code
yes already added
this is not true. Inactive colliders are always ignored
A deactivated game object cannot experience collisions. All of its colliders are disabled.
On the other hand, a disabled Behaviour can receive collision and trigger messages
i want to ask for your opinion since its haunting me
So i have watched a lot courses and learned the c# microsoft program, but i still cant imagine how to write a procedural generated world for my game. So i tried chatGPT, but i was told this is bad to use. And since i have not idea how to write that from scratch i would need to watch tutorials/resources then. But this is also "not done by myself" stuff. I feel like a coding loser lol.
chatgpt or tutorial feel like cheating
"Unity How to Detect Mouse Click"