#💻┃code-beginner
1 messages · Page 638 of 1
Ok got it, thanks for the help
its funny, every time I have to convert a set of materials, I ask the same question "why cant this be automatic"
the wizard finds them all at once for you
it does!?
Haha, it's good that I asked
lmao.. we all been there in some form or fashion
its kinda confusing how they have two different variants of it in two different Menus
Hi Guys. So i have a problem, it shows that i didn't assign a groundCheck to my Character even tho i did. What should i do?
you have another copy of your PlayerMovement script in the scene
on that other copy, you didn't assign the variable
to fix it - find and remove the extra copy
There error says that a PlayerMovement has no ground check. It does not say every PlayerMovement has no ground check. The one in your screenshot having it assigned simply means the error isn't talking about this PlayerMovement
isn't that what we been saying for like ever ?
glad you got it tho lol
@rich adder I debugged scene.buildIndex and it's always at 0
which one are you grabbing, you gotta give me more context here..
show code
Yeah Srh
Can I reverse the process of checking a dictionary for a value? I have a dictionary of morse code character with ascii char as the key and a string of dits and dahs for the value, and I can search a string to see if it contains the key, can I do the reverse for translating back?
You can have a second dictionary that does it the other way around
I have a question about IronSource, where should I ask it?
Yeah, I figured that'd work, it'd just be a pain to redo and reverse everything
You can automatically populate the second dictionary from the first dictionary if you want to
so thats the scene 0?
where is the log ?
foreach(var kvp in dict1) dict2.Add(kvp.Value, kvp.Key);```
what is the question?
I have completed the implementation, released my game but I still get test ads on my game. I want to know how to switch them to live ads intead of test ads.
I AM SO DUMB. I had a copy of the Script in my Chracter and i dont know why
@rich adder Fixed it, it's working now
I'm so confused on how to do this in the player movement script should I first add the mouse Input.GetAxis("Mouse X") & Input.GetAxis("Mouse Y")? or is that not needed? theres hardly any good sources online can't find a damn thing
Do you want to get the Mouse X or Mouse Y input values?
I have no clue what's needed and what's not? I'm using cinemachine I can already move the camera without a camera look script. Its just that I don't know how to rotate the players rigidbody when looking around and making the movement camera relative so where ever direction I am looking at I can go in that direction.
All Input.GetAxis does is get you the amount of movement on that axis this frame. If your player movement script does things based on the mouse movement, you'll probably need to get the mouse movement
I found a better solution Nav
yup arrays are 0 index so its good to do that
lol.. another day another dolla
Hey I am making a driving motorcycle, imported an asset of the bike. I saw someone on youtube making a controller by having a sphere in the middle and programming it. Is that the easiest/optimal way or is there another better way to do that? If anyone did it before or knows anything about that?
the sphere method is a solid "arcade" type setup
but its up to you ultimately.. depends on how arcade <- -> realistic ur going for
Is that good or no? What would be the pros and cons if you know?
One way to get your camera's horizontal rotation is Quaternion.Euler(0, myCamera.transform.eulerAngles.y, 0);
Now you have a quaternion that represents the side-to-side rotation of your character. You can then multiply a movement vector with that to make it align to the camera.
its pretty simple not sure how well it'd work with a motorbike tho..
@hollow dawn It's really better if you just look up a tutorial, otherwise we'd probably need to just type out everything for you.
I think I did it well it works and does indeed rotate the player/rigidbody . https://paste.ofcode.org/AEKYrpwzDymhmH4sMG5dJV
the sphere is rolling and being pushed in the forward direction of the model... when u turn u rotate the car model.. and the whole time the car model is just tracking the rigidbodies position..
so everythings working together..
Yes, the "orientation transform" is another common way to do it
so did I do it right?
Does it work like you need it to?
I mean I have to make a motorcycle, plane and a boat, so now I am just doing research on what to do and what is best
I don't know how you are rotating orientation
well yes it rotates the player/rigidboy
We weren't talking about rotating the rigidbody. You wanted to move relative to the camera
when im in situations like that I like to go to the Unity Asset store.. find some things related to what i want.. import them and then i go in and try to reverse engineer them
to see how they all work
everything u mentioned theres an asset on the store already
car u gotta deal with friction, plane u gotta deal with gravity, boat u gotta deal with bouyancy
@hollow dawn Oh you mentioned rotation too, but yeah anyway my answer is about the relative movement only
I did say "Its just that I don't know how to rotate the players rigidbody when looking around and making the movement camera relative" now I can rotate the player I'll do the movement camera relative
I mean you already have this line:cs moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
Which will work if you rotate the orientation transform correctly, only on the y axis
But I have no idea if you are actually doing that
Orientation stores the direction your facing
I think I might have done the rotating the player wrong when looking around it feels weird
make sure you imported it as a sprite
in the import settings on the image
Yeah... I already imported the bike and got a prefab so I need to do research on that, but usually if I import a car or something they come with a controller?
lemme try
still not working
can u show the inspector/import settings of said sprite
im seeing people drag images directly to sprite
ya, b/c thats possible
you didnt set as sprite
thx
:( for some reason its still not working
im dragging but nothing happens
i saved
When I stand still and look around why does it look laggy? but when I move its goes back to being smooth?
I think you need to drag one of the "children" of the asset
Yeah, expand the asset from the arrow and drag its child sprite in
wait ill send a vid
can anyone reccomend a module or package for handling fancy text?
Thing kind of thing that handles each letter differently, so I can do things like change the colors of letters to fill them in, or make letters shake like in Slay the Spire
I put HandleRbRotation(); in update instead of fixed update and it fixed it. since I'm rotating the rigidbody it should stay in fixed update then the problem occurs again how do I fix it?
Show that bird texture's settings again?
Sprite Mode should probably be Single
is it just me or have i seen this exact same scene like 4 times
i swear, the same colors, same grid, same monolith in the middle
anyway.. i think the answer is:
- move ur camera in lateupdate
- or use cinemachine
lmao just confused BUT I used move rotation now it works but when looking around why does it feel weird?
https://paste.ofcode.org/N7iSzYeUkjPWk2wbteNn6c
whats "weird" about it?
Im using cinemachine
you can try changing the camera's update setting.. usually its already set on "Smart"
thats usually fine in my projects 🤔
I don't it just feels too smooth and when I am moving my mouse left to right it swings up and down idk just werid is there something wrong with my script?
mayb? do u have any smoothing in ur code?
it def shouldnt go up and down for lateral movement
it doesn't look like it...
maybe im just tripping
What is it called when a texture is split up like this so you can make squares with a center texture that tiles and the borders can extend so you can get a texture for any size
I'm aware of the concept but I can't for the life of me remember what it's called to look up how to implement it
9splice
thank you
9 slice*, but I think most search engines will know what you mean
when I try to look right or left really quickly it doesn't do it
this is me moving my mouse left and right quickly
its like too slow/smooth idk
how do I fix it?
can u share ur camera script?
im not using a camera script
just using cinemachine
this?
what doess null mean cus in my language it means zero
it means gone, not here.. poof.. non-existent
it basically means the same in english.
Hi, I have a question about LevelPlay and IronSource, where should I ask it?
how can I make it maintain integrity as pixel art instead of squashing wierdly? I made a 9-sliced object in the create gameobject menu
this is a code channel
crap sorry meant to swap
Does anyone have any tutorials for animations? I have it set so the sprites change when you press a key down to go a direction but not sure how to do the actual animations
I implemented an organic growth algorithm (l-system), but it is so slow it hogs up the cpu as early as 8th generation. I did some optimizations but feel like this should be 100 times faster than currently it is. Any insights what I can improve?
https://github.com/karaok1/BiggerTreeDev/blob/master/Assets/Scripts/TreeConstructor.cs
You are creating (instantiating) multiple game objects and C# classes every frame. You will greatly increase performance from using object pooling . . .
use the profiler and see which part specifically is taking the most time. you can set a custom sample too so it shows as a different label
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Profiling.Profiler.BeginSample.html
That whole _dna part using strings too definitely isnt optimal. You should pool if instantiating is a major problem but also you dont need to use GameObject as your type for instantiating. you should use the component you directly want to reference as the type, unity will pass back the reference of the component and still spawn the whole prefab
Within DrawTree you instantiate the line renderer prefab as a GameObject every loop, and within an inner loop, you instantiate a fruit object prefab. Instead of using the type you need as the prefab, you're using GetComponent every iteration and then every iteration of the inner loop . . .
That is definitely costly since DrawTree is called every frame . . .
Hi, how i can make that an object an enemy spawn to get yeeted into the oppositive side of a proyectile and meele damage?
the thing is, my enemies explode into shards and sometimes items, and i want them to fly to the side of the damage, so how i can do that?
For now i did that the proyectiles explode upon contact, and a material that has complete friction, but its very buggy and sometimes it moves the shards i dont want to, and also the meele "push" doesn't work using this method
How are you moving it?
- it is going to vary a bit due to fluctuations in deltaTime
- depending on how you actually move the object there's probably a better way to get the velocity
so you're randomizing the velocity each frame
moveSpeed2 = Random.Range
moveDir * moveSpeed2
moveSpeed2 is the velocity here
or rather, it's the speed not velocity. velocity is direction multiplied by speed so that second line i pasted is the velocity
Also you have the move speed variable right here there's no need to calculate anything
📃 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.
laser turret script https://paste.mod.gg/jujrxdxbrpub/0
A tool for sharing your source code with the world!
if (laserBeam == null) {
laserBeam = GetComponent<LineRenderer>();
}
You're saying if it is null then get the comp for it.. but that will just return null. If it's null you need to initialize it instead.
Otherwise, if it's not null, get the comp
i have the component assigned
So then yeah, change if (laserBeam == null) to if (laserBeam != null) or if (laserBeam is not null)
still not appearing
What's the material like for the line renderer? Is the line renderer thick enough and is it's color something other than totally transparent?
Hmm, well here's a few things I noticed though I'm not sure if any of them are the culprit(s)...
If the LineRenderer width is 0 or just not wide enough relative to the rest of your scene scale, it won’t be visible.
If firingPoint is null, laserBeam.SetPosition(0, firingPoint.position) will cause an error.
It also looks like you only update the LineRenderer positions when shooting begins, but the beam won’t move if the target moves. So you'll need to ensure SetPosition() updates every frame inside the while loop.
The laser could be rendering behind other objects as well, effectively being culled.
nah the beam isnt even appearing for the linerendere positions
the width is still 0 in this screenshot, i told you this the other time #💻┃code-beginner message
Well, damn near 0, by the looks of it
oh i see this time the top value was 1.0, last time you had it at 0.1 which made the width a lot smaller
I would honestly just start with a new line renderer and recreate the one you have. when you create a new one via the right click menu, it should be visible
Setup as much as you possibly can in the inspector as well, easier to keep track of it all. That or do everything in code. lol
Iirc your not meant to use is and is not null on unityengine objects since they aren’t operator overloadable and miss out on some destroy related stuff
You may be right, I can't remember exactly how that works here
Facts. Use !unityObject or unityObject != null for objects derived from UnityEngine.Object . . .
Nice 
Wanted to ask how can I make object movement be responsive to the camera, so where I am looking is where the object goes.
The issue is that you're using hardcoded directions in Translate. You should pass in directions that you want it to move in(presumably the camera forward).
Also, I'd recommend not moving an object via it's transform, if it also has a dynamic rigidbody(and you want physics to work correctly).
What would I use instead?
Setting velocity or adding force like you do with your jump.
Rb.MovePosition might also work
In this case I would be using Input.GetKeyDown ?
Depends on how you want it to work. You should check what GetKeyDown does in the documentation and what other input query methods are available
Also, I'd just recommend going over the beginner pathways on unity !learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yes, there might be several reasons why it's like that. Many of which could be caused by mixing up transform movement and physics.
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Why can I not put these in those fields?
Im 100% sure they're specified correctly as Text mesh Pro, and the auratypetext and auracount ARE TMP, and the button is just a button.
it works now
assets cant reference scene objects
oh nvm, thought that was an object in scene
all i did was close the prefab mode, and re open it and it worked so
yeah not sure why it didn't work
but the good old closing and redoing worked lol
it's a little buggy usually I use the + menu
Can a script with errors still be fully compiled? Because Unity stops compilation if errors found.
No
You need to fix the errors
It can't compile with errors
Not because of unity stopping it for no reason, its like what happens when you get an error in a function, the function stops if not handled
It can't compile anything if there's compile errors anywhere. Even in completely unrelated scripts.
Does anyone know why Impluse mode is not working as intended ?
Because you're using MovePosition as well
Can you explain ? I dont understand , I am a dummy.
What actually happening in there ? I dont find any clue on documentation ...
MovePosition is you saying "from here, try to go to this new position"
Prior to that, you're using AddForce which is you saying "I'm going to push you this hard in this direction"
You're overriding the physics engine trying to achieve that by immediately telling it to be somewhere right after
Which you can see in your FixedUpdate how you are calling ProcessMovement right after ProcessSprintMovement
If you're attempting to add sprinting, you need to increase the distance you're traveling in ProcessMovement's MovePosition by increasing your moveSpeed while sprinting or using a separate higher value sprintSpeed while sprinting.
I still dont get it . You are telling me addforce is pushing me in one direction. What is the point adjusting the moveSpeed to a higher value as well as sprintSpeed ? Since it is pushing into the same direction ...
I'm eluding to the fact you don't need your ProcessSprintMovement function at all
If you want to spring, just increase how fast you move in your ProcessMovement function.
Wait , it works. I just adjusted the moveSpeed to a higher value as well as sprintSpeed...
No, because the code above I have simplified , the main thing that I want is whenever the player press SHIFT button , it will dash a certain distance , so ... there will be something OnSprint() function and check whether it is pressed down ...
In that case, you need to use a state machine so you're tracking what "state" your character is in.
And then, in your update loop, depending on the current state of the player, handle it appropriately
So that you're running your dash logic without the movement, jumping, wall climbing, swimming, etc. not overlapping unnecessarily.
I will take it as advise and try , thanks for helping me out. Can I add you as friend ? Hehe , because there are still too many things I want to ask ... Can we ?
I don't do DMs, sorry
Feel free to ask questions here though, or share in #1180170818983051344
I've gone down that rabbit hole of making a character controller, so I know the pain you're about to face. 🙃
-# Which included a dash
OMG, this is so cool , I wonder one day I can be like you...
the controller is splendid ...
Can anyone help with this code? Im fresh in Unity and C# and just finished my first tutorial and now im about to do my first clicker game but this is not working for some reason and it says that the value is quote "assigned but it's value is never used" and even basic calculation like Money =+ 1; doesn't work. (Yes i know this could have been done better with FOR loop but i haven't learned that in C# yet so im doin the longer way)
!code in how to share code for the future.
your error is a basic c# misunderstanding, you are defining the variable again by using double variableName. you dont need to specify double everytime you refer to the global variable
📃 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.
You've made new variables in start that don't do anything. They exist until the function ends then vanish
If you want to use the variables you declared outside the function, don't create new ones
you'll gain a lot if you go through c# basics first, there is a intro to c# link pinned in the channel
oh bruh
i was used to it working normally as far as i remember from c++
thats not how c++ works either
i could have sworn it works normally that way- i guess my memory is just bad
but when i remove the double, the variable is not colored anymore, is that normal?
even if i fix the "double variableName" it still doesnt add up the number
oh wait
you should really do basics of c# first
your code doesnt add to Money, it simply reassigns it to the equation. if you wanna add to the current variable then its +=
=+ just means you're assigning it to a value and theres a positive sign
okay now it works, thanks, i will do the basics after this "game" im trying to make
but won't be general c# different from unity one? i mean in normal c# you don't have "objects" like buttons and all that
unity uses c#, its not a different language but it is on an old version. you probably wont be using the newer features in any beginner level guide
the idea of learning c# first is that you arent learning both unity and c# at the same time. it wont be fun when you have to learn new objects like a button in unity, yet also have no clue how to write the code that the documentation is telling you
how far should i go into basic c# so i don't overlearn c# code that i won't "need that much" in unity in general?
also, last question, where could i find some open source unity projects to look into to learn?
i mean, there's no harm in overlearning
my point was, at what point should i start doing more of unity than plain c#?
i usually say once u actually understand classes and instances of a class, any tutorial probably wouldve taught you loops, arrays etc. thats probably good enough to at least not get stuck on every line of code in unity.
I have another problem this time unity specific one (Atleast i think so). I put a gif as image source to a button, but the gif doesn't play it instead just stays as an image.
Unity doesn't play gifs
What am i supposed to do then
You either have to animate frames, or use a video player.
thanks, I investigated it and the main problem seems like the algorithm is simply too complex to simulate in real time. I will need to switch to another algorithm
how come the "Found command!" is still called when i type in giberish
i'll type in "ffsggfdsjjhhfdg" as the command, and it somehow still finds it
i didnt look so indepth at the time to the actual logic but the points we raised at the time would probably heavily speed up your processing. the overall code didnt seem complex at all
anyone know how to fix it
its honestly pissing me off now
how is it finding a command which doesnt exist
its the if(foundCommand.HasValue) that always has a value
Instead of just "Found command!", print some info about the found command and also print commandName
That's the first debug step i'd take here
(Also no need to use ToLower if your string comparison is ignoring the case anyway)
this is what it said
How about printing some identifying properties of the command instead of just whether it exists and what type it is
Whatever Command is it probably has a name or something
Yeah they seem to have a name and some name aliases too
I haven't worked enough with nullable structs to know if there's any quirks I'm missing, but I don't see anything wrong with the code right now
Debug.Log($"Found command! Name: {foundCommand.Value.Name}");
it doesnt even say the name
It's either null or empty
Okay, so the Command isn't null, it's probably just got null values
What is Command? Maybe it has some sort of "isValid" property or something
command is the struct
here is a screenshot
Ah, it's a struct. FirstOrDefault will return the thing it finds, or the literal default. Since Structs aren't nullable, it gives you a struct with its initial values
What happens in CheckDuplicateAliases?
it just checks if any of the commands use the same alias and warns me to change it
So the default value of a nullable struct actually "has value" (HasValue is true)?
oh alright
so whats my best option
just loop through them?
Ohh right it's not a List of Command?, it's a list of Command
Yep. That whole linq query evaluates to command = default
Makes sense now
Instead of doing FirstOrDefault, store the result of the query in a list. If the list is empty, set foundCommand to null. Otherwise, set it to the first thing in the list
So, foundCommand = resultList.Count > 0 ? resultList[0] : null
since the name is empty when it doesnt find it, couldnt i just add && !string.IsNullOrEmpty(foundCommand.Value.Name)?
Not quite this actually, the default value of Command? would have HasValue = false, but the Linq query doesn't know about nullability here
That could also work
Right. It's a list of a struct, that's getting cast into a nullable
And the default value of a struct is non-null
can someone help me rewrite my character movement code? theres alot to it so i dont really wanna start from scratch
post the code and clarify whats wrong with it currently, if someone can/want to they will
lol i barely know how to describe it, the speed variable doesnt seem to anything? and i wanna add some way to adjust friction and acceleration values
whats the value in the inspector set at. Also don't post code as screenshots 👇
📃 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.
okay,
how do i make it so that a number doesnt get shortened to exponents?
It won't, unless there is code specifically telling it to do so
well then how do i make it not have exponent? i understood it the way that i have "something" in my code that is telling the number to get shortened but i don't. it automatically gets shortened
can you clarify what you mean?
do you just mean the stringification of floats?
this: From lets say 123456836839696 to 123.45E+24 for example
If you're printing the float, don't format it
@eternal needle I got the pooling but don't understand the instantiating by component thing you mentioned. how would I do that?
It does get automatically formatted
specify a format
https://learn.microsoft.com/en-us/dotnet/api/system.single.tostring?view=net-9.0#system-single-tostring(system-string)
https://unity.huh.how/references/serializing-component-references#referencing-components-not-gameobjects
you just use the type you want to instantiate. this wouldnt really save you that much if you're using pooling since you wouldn't be calling GetComponent or Instantiate much anymore
it's always formatted to get into a string
if the output isn't what's desired, then specify a different format, that's all
Isn't the default format just going to give what you put in? I'll go fire up Unity and double check, I probably should have confirmed that first
"what you put in" as in the float, yes
but it's not always going to be just a decimal literal, it can have exponents
100f .ToString() and 1e2f .ToString() are gonna yield the same result
I don't think this works I get InvalidCastException
LineRenderer lr;
lr = Instantiate(lineRenderer, transform);
Did you recently change the type of lineRenderer field?
What type is your lineRenderer variable
Did you drag the prefab in again after changing the type?
It wouldn't compile if it wasn't the right type
idk might be a runtime issue, the game acutally started and then throw this error
Assign none to the variable and assign it again
let me try this
It might be serialized as a reference to the old type
Hence this question
ok ty, assignin again solved the problem
hello, i have a question, im pretty new to the "new" input system. my question is about whether i have to reference a InputAction in each script in which i need it, or can i make a one reference in scripts with static instance of it, and use that reference in all scripts where i need it?
for example i have a InputManager script where i calculate all the angle for rotating to face the mouse and stuff like that, which works cuz i can read the value and save it to a public vec2. but with a button value, where i either need to subscribe a function to it or use "triggered" value within it, im not sure, or rather it doesnt work, so is it possible or do i need to make a new reference to the Actions asset and all the input actions in it anew?
oops, sorry my bad, didnt notice
can anyone help? the raytracing wont detect the ground layer so my character doesn't get drag. the ground plate is set to the ground layer.
Show your !code and the inspectors of relevant objects
📃 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.
(Raycasting, not raytracing)
when I try to add my project to github, gitattributes come up empty, anyone else have this problem...?
can someone link me some sort of tutorial on grid systems..? Ive been looking for one but I havent been able to properly understand the ones that I watched I fear q.q
the best I could find was this one but Im... not exactly sure whats going on here...
https://www.youtube.com/watch?v=G7iPGJl37Xc
Utilizing this component dramatically simplifies the task of designing a grid. By defining the parameters such as tile size, gap, and type within the Grid Component, it automatically computes world positions based on the specified grid indices.
This reduces the complexity of placement, ensuring an efficient and streamlined grid creation process...
void DrawNormal()
{
Vector3 normalVector = -(planet.position - player.position) / (planet.position - player.position).magnitude;
Handles.DrawLine(player.position, player.position + normalVector * 10f);
SceneView.RepaintAll();
}
Why does this not show up in the editor?
It gets called by an editor button
did you verify the method was called with breakpoints/logging ?
because it's not public
or do you mean the Handles line doesn't show
if the latter, make sure you have gizmos enabled
Also:
Vector3 normalVector = -(planet.position - player.position) / (planet.position - player.position).magnitude;```
Is a super confusing way to write this:
```cs
Vector3 normalVector = (player.position - planet.position).normalized;```
well what about grids? Unity has a built in component for it
what do you want to learn/know about grids
definitely just use the built in component as mentioned
Well not just tilemaps, but Im working on a tile-based tower defense... Ive tried but I wasnt able to code stuff onto those tiles, they were just sprites
You can certainly use the Grid system for 3D as well (if thats what you meant)
I've done it myself, you can also place tiles with a Prefab brush that can use 3D objects
but yeah Tilemap would be only 2D.
nono I meant 2D ^^;
I wanna attach components to the grids Im using, and I guess use them kind of like prefabs? Does that make sense?
kinda. You can make prefabs out of them sure, it has helper functions for it as well V3 to Grid
basically if you ever tried to make your own grids with like multidimensional array , this cuts the work in half lol
Ill give this a read, thanks!! ^^
Stupid question but Is there a way i can pass csharp Item = ItemManager.instance.itemSO[selectedIndex]; into ```csharp
public Dictionary<ItemsScriptableObject, int> itemSO = new Dictionary<ItemsScriptableObject, int>();
Item is of type ItemsScriptableObject if that matters
I don't understand the question really. You haven't explained what itemSO or what you mean by passing something into a field
sorry I see itemSO is a Dictionary<ItemsScriptableObject, int>()
what do you mean by "passing it in"
passing what into what
with the goal of what
This is actually most confusing because we don't knwo what selectedIndex is
is selectedIndex an int?
yes
your dictionary is backwards
your dictionary is set up to look up an int by an ItemsScriptableObject key
If you want to do lookups in the other direction you need a Dictionary<int, ItemsScriptableObject>
or even just an array or list of ItemsScriptableObject
(if the indices are contiguous)
the thing is i have itemSO setup like this in ItemManager.cs so i dont think i can do lookups in another direction ```csharp
public void ListItems()
{
foreach (Transform child in ItemContent)
{
Destroy(child.gameObject);
}
foreach (var kvp in itemSO)
{
GameObject obj = Instantiate(InventoryItem, ItemContent);
var itemName = obj.transform.Find("ItemName").GetComponent<TextMeshProUGUI>();
var itemDescription = obj.transform.Find("itemDescription").GetComponent<TextMeshProUGUI>();
var TypeOfItem = obj.transform.Find("TypeOfItem").GetComponent<TextMeshProUGUI>();
var itemIcon = obj.transform.Find("itemIcon").GetComponent<Image>();
var stackSize = obj.transform.Find("stackSize").GetComponent<TextMeshProUGUI>();
itemName.text = kvp.Key.itemName;
itemDescription.text = kvp.Key.itemDescription;
TypeOfItem.text = kvp.Key.itemType.ToString();
itemIcon.sprite = kvp.Key.itemIcon;
stackSize.text = kvp.Value.ToString(); // Shows the correct count
}```
I don't see how this code is relevant to what we were just talking about tbh
you can do this code with an array or a list just as easily
or with a dictionary in the other direction, just as easily
for a dict in the other direction the Key and the Value in the KeyValuePair would just be reveresed
It's also possible to have two dicts, one in each direction, if you need to do lookups in both directions
You just need to make sure they're always in sync
Ive never really worked with these since im a beginner but how would i then search for stuff like csharp itemName.text = kvp.Key.itemName; Wouldnt that just create the same problem just bigger
As I mentioned the key and value would just be reversed
it would be kvp.Value.itemName
what's assuming you had a Dictionary<int, ItemScriptableObject>
if you had a list you would just be doing:
for (int i = 0; i < myList.Count; i++) {
String name = myList[i].itemName;
}```
i did everything you guys said and game runs 4x faster. algorithm itself is simple but the amount of calculations increase exponentially so it slows down pretty quickly in the next iterations. can't use l-systems efficiently i guess
youd wanna probably look into the job system if applicable but its definitely not beginner level. im not sure how far you intend to take this algorithm and i really know nothing about this system you mention. but yea at a certain point you could just be trying to run too many lines of code and thats all
what your video had initially didnt seem like it was doing all that much truthfully, so i assume this can still be pushed pretty far without advanced topics
if i have a dont destroy onload that stores settings of my game in the menu how do i make it so that the object doesnt duplicate every time i enter the menu scene
if applicable you really could even just precompute a ton of results and use that.
you can have a "bootloader" scene which is your entry point containing things like these. then that brings you to the main menu
like a intro scene
either that or a proper singleton implementation will destroy duplicates on awake
it just means a scene before your main menu. it exists for the purpose that itll only be loaded once, because nothing ever sends u back to the bootloader scene
bootloader itself doesnt actually mean that and the term isnt related to unity but you can think of your scene in the same sense https://en.wikipedia.org/wiki/Bootloader
i get what you mean
HOLY SHIT IT WORKS TYSM
anyone can help me for some reason my visual studio doesnt have autocorrection for unity i tried some stuff i saw on yt didnt help
!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
ill try this
I have discovered grid layout groups.
IT WAS A GIF-
"That link is not allowed" IT WAS A GIF 😭
lol
Yes that's intended
guessed so but its funny
This isn't a comedy channel, this is for getting things done
Prohibited content and behavior
...
• Using reaction gifs, memes, or overusing emojis, stickers, or reactions.
doesnt matter, its not allowed and its written clearly in the rules
fair enough. anyways... grid layout groups will probs solve my problem? Ill give it a try tomorrow, since its getting late.
gl with that dont know what the mean but gl
void Update()
{
for (int i = 0; i < hearts.Length; i++)
{
if (i < HP)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
}
}
i have this code, and I want to make it so if hearts are 6-10, the 5 hearts change from red to blue depending on the amount, do I have to make another for loop here which starts at i-5 if i is bigger than 5, or is there a more efficient way
You can still have 10 heart objects, just make the last 5 blue and in the same position as the first 5. If your health is above 5, they'll activate and draw over the red ones. If they're disabled, they'll be hidden and you'll look through them to see the red ones underneath
the more efficient way here also would not be doing this in update at all. do this logic anytime the HP changes, which should only be through a public method or property
umm, the heart system is in a different script than all my player related stuff
okay nevermind, the 2 scripts are still on the same object
Great time to learn about events and properties
I have this script that theoretically creates 52 playing cards and puts them into an array. The problem is that in the for loops when I check with a Debug.Log, everything seems to be working fine, but when I got and check after the for loops, I only get the last card that was added
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShooterScript : MonoBehaviour
{
public Card[] deck = new Card[52];
public Card[] hand = new Card[5];
Card tempcard = new Card();
int k = 0;
void Start()
{
//first we loop for all the suits (4)
for (int i = 0; i < 4; i++)
{
//then we loop for all the values (13)
for (int j = 1; j < 14; j++)
{
tempcard.value = j;
tempcard.suit = (Card.Suit)i;
deck[k] = tempcard;
Debug.Log(k.ToString() + ". The " + deck[k].value.ToString() + " of " + deck[k].suit.ToString());
k++;
}
}
for (int l = 0; l < 52; l++)
{
Debug.Log(l.ToString() + ". The " + deck[l].value.ToString() + " of " + deck[l].suit.ToString());
}
}
}
public class Card{
public int value;
public Suit suit;
public enum Suit {Clubs,Diamonds,Hearts,Spades};
}
The console looks something like this:
1. The 2 of Clubs
.
.
.
50. The 12 of Spades
51. The 13 of Spades
0. The 13 of Spades
1. The 13 of Spades
.
.
.
50. The 13 of Spades
51. The 13 of Spades
if Card is a class you are modifing 1 instance and adding many references to the arrays...
anyone know why visual studio not working for me i tried this
should i be making variables readonly if i don't plan on changing their value?
And what will I need to do, to have 52 instances?
yes
if you want 52 cards with their own properties then yes you need 52 instances
btw you can do your i to suit cast in the upper loop to convert only 4 times
Well I want an array that in each slot has a card that has a value property and a suit property. What will I need to do?
make a new card instance in your j loop
make new card instance, assign data (or define a constructor on Card), add to array, done.
int k = 0;
for (int i = 0; i < 4; i++)
{
var suit = (Card.Suit)i;
for (int j = 1; j < 14; j++)
{
Card card = new();
card.value = j;
card.suit = suit;
deck[k] = card;
k++;
}
}
//first we loop for all the suits (4)
for (int i = 0; i < 4; i++)
{
Card.Suit s = (Card.Suit)i;
//then we loop for all the values (13)
for (int j = 1; j < 14; j++)
{
Card tempcard = new Card();
tempcard.value = j;
tempcard.suit = s;
deck[k] = tempcard;
Debug.Log(k.ToString() + ". The " + deck[k].value.ToString() + " of " + deck[k].suit.ToString());
k++;
}
}
change K to not be a member var too
Done
should be good now I think
Ok it works as expected now, thanks a lot!
You can also do it like this:
for (var suit = Suit.Heart; suit <= Suit.Spade; suit++)
and directly iterate over the enum
np np. Very important to understand how references work and how it differes between a class and a struct (reference type vs value type)
Which would mean you couldn't accidentally use i in the place of j or vice-versa
Could anyone help me? Im really struggling to find a solution to my problem
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
void Update()
{
if (Input.GetMouseButtonDown(0));
{
Debug.Log("True");
}
}
why
this is still printint "True"
event if I'm not clicking
or holing
oooooooooooohhhhhhhhhhh
silly me
thanks
and also
how to Debug.log something, but in a new line even if it is repeating
Disable collapse
Im getting this error but i've checked and all the objects are there. Any ideas to help?
NullReferenceException: Object reference not set to an instance of an object
DeckManager.DiscardHand () (at Assets/Scripts/Managers/DeckManager.cs:59)
TurnManager.StartPlayerTurn () (at Assets/Scripts/Managers/TurnManager.cs:31)
TurnManager.Start () (at Assets/Scripts/Managers/TurnManager.cs:17)
where it is
Look at the line the error is on. Something on that line is null but you're trying to use it anyway
On the console
I've already had a look and i dont understand why it would be null
What is the line
59: discardPile.AddRange(handManager.cardsInHand.ConvertAll(cardObject => cardObject.GetComponent<Card>()));
31: deckManager.DiscardHand();
17: StartPlayerTurn(); // Begin with the player's turn
There's a lot on that line can be null
Start loggin'
on 59?
Yes that's the line the error is on
thank you! 🙏 I'll try and see if i can find out what it is
discardPile, handManager, handManager.cardsInHand, cardObject, and cardObject.GetComponent<Card>() could all be null and break that line.
didnt get anything back from this:
if (handManager == null)
{
Debug.LogError("HandManager not found");
return;
}
turnManager = FindFirstObjectByType<TurnManager>();
if (turnManager == null)
{
Debug.LogError("TurnManager not found");
return;
}
time to test the rest
would you recommend i go backwards until it works again?
and then I can just redo it
Debug.Log($"Discard pile: {discardPile}", this);
Debug.Log($"Hand Manager: {handManager}", this);
Debug.Log($"Card in hand: {handManager.cardsInHand}", this);
discardPile.AddRange(handManager.cardsInHand.ConvertAll(cardObject => cardObject.GetComponent<Card>()));
```Any of the references that print out *blank* would be null.
If you're still getting an nre when none of the above are null then likely a card object is null.
I managed to get rid of the error but thank you!
Does anyone know why my enemy sprite appears behind my canvas image despite being a higher layer?
that doesn't seem like a code question. but also i believe it depends on the canvas render mode whether it will sort sprites above UI (this could be incorrect as it has been a while since i've done much with sprites)
ah where should I ask then?
ty, also you were right, turn out that i just had to change the render mode to world space
i'm not 100% certain, but i think screen space camera can also sort world sprites above UI
@slender nymph can i dm you for help, if not i understant
!ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
okay
I am setting the rotation of an object like this:
characterModel.transform.rotation = Quaternion.Euler(0, 0, 0);
and for some reason it keeps setting the y value to -180. I don't understand what's happening here.
How did you check the y value?
In the inspector
The inspector shows the local rotation, the code sets the global rotation
oh snap i get you. I am setting the rotation on a child object so that may be why this is happening
I changed it to transform.localRotation and it's working as expected
Thank you!
this was working fine all day, why am i getting this error now?
not sure what im missing D:
i know 😄 the highlight in the picture is unintended
switching it to just TextMesh fixed it, maybe the name is different?
doesn't work, but either way im not using a canvas anyways, im using it with 3d world space so that wouldn't apply anyways
it seems like tmp might just not be installed lmfao somehow
or something
idek
oh sheesh, my whole project is blowing up
everything isn't working now when its suppose too
seems like its not recongnizing any of the libraries 0,o
no idea wy
Close VS, go to Edit -> Preferences -> External Tools -> Regenerate Project Files in Unity and reopen VS
i think.. it worked? thanks 😄
yeah it worked
- They are not libraries, they are namespace definitions
- The whole point is to be able to reference code from other namespaces. Randomly adding
System.Collections.Genericis not going to help them with TextMeshPro - They already had
UnityEngine.UIincluded, it just isn't being recognised. That's the whole problem
Can someone help me fix the gradlew.bat --no-daemon -b
i can temporarily fix it by downloading gradle.bat and pasting it into the temp file of the unity project but this dose not fix it forever.
You're saying it as if it's an error that everyone knows about and reads about it in the morning newspaper while seeping some coffee.
can you run a unity build in windowed mode? (non fullscreen) If so, can you detect OS level drag and drop into the unity program?
Unity might not implement those OS features for you, but you can access OS specific APIs like any other C# program.
After installing the .net sdk, vscode still shows it as missing. I have looked up solutions on reddit and tried it but it does not work.
I have the extension to install it as well
Did you try restarting the PC?
yes
Check the environment variables as the error suggests then.
Did you install the .net sdk or .net runtime?
the .net sdk
Then check the environment variables
Also try pinging it for info in the command line.
am i crazy or is this just
wrong
like that condition is objectively true but no matter what it will never read true in the log (and i have an if statement a little later using the same condition that also never activates)
in the condition? alright, thank you
i'll go try that
well the thing is i've just frozen the movement and manually moved it to -3.5 by typing into the inspector because i've been struggling with this for a minute
so i don't think it would be, but yeah i'll try approximating it
it doesnt matter
alright
also can you show the hierarchy
of the object you want to read transform for
it also might be that you are reading transform.position.y (world position)
and comparing it to local position in the inspector
it was local position, yeah
i just changed the check to be transform.localPosition.y instead and that's fixed it
thank you so much!
No excuse not to use Mathf.Approxmiately, even if you are sure the value is the exact same
yeah, i'm using it now- i've just never seen it before since i started with c# and apparently never ran into enough of an issue with floating point values to find out about it
It's pretty much an universal issue in programming
You might've been super lucky to not get it elsewhere
It's just how floating point values work, they're both accurate and inaccurate in a sense
i dunno what to say
i've just never come across mathf.approximately and i've made a solid few movement systems and whatnot
It's a good practice to keep in mind
yeah, i will from now on
There's a couple other handy best practices in the pins, take a look at those too
Especially the vector calculation
will this be the best way to make a "region" rendering?
so that it turns on the objects in the region when you go inside the trigger?
or would there be a better way than iterating trough each object?
That works, yep.
If these objects are always together, you could child them to a shared group container parent and just toggle that parent instead.
Or you can associate a container object with this trigger, and whenever a new object that has to be hidden/shown with it is added, child it to the container.
!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
oh my god I did it, solving the problem feels so amazing, I checked the output in vscode, it showed the path it used to try and find the dotnet sdk, and I found the word homebrew, so I tried installing it on homebrew and it worked
Homebrew? I assume we're not talking about windows..?
ohh, sorry, I didn't specify, my bad
I'm using a mac
it is always a bit weird with apps not specifically designed for it
where is the add button?
those are instructions for installing Unity itself
if you already have Unity installed you can skip it
anyone know how do i add so i could see my box collider outline box
like i want to see how to box collider looks
I'm not sure if it matters in this case 🤔 other than the potentially annoying warning
Assuming you aren't going to actually reach the depth limit of 10
yeah i aint
what command could possibly have 10 arguments
It would definitely be an issue if you had cs public struct A { public A nested; }
Because each struct would need to have a value for its nested struct, which would have a value for its nested struct and so on
But you have a list so I don't think it really matters?
I'd almost want someone from Unity to confirm if it's an issue or not
Logically, I don't think it is because the first empty list stops the recursion
hi! how to fix this script? my player after touch on left he keep move slowly. i just need just normal move. i trying find script for me. can some one help? ```CS
public float speed;
public VariableJoystick variableJoystick;
public Rigidbody rb;
public void FixedUpdate()
{
Vector3 direction = Vector3.forward * variableJoystick.Vertical + Vector3.right * variableJoystick.Horizontal;
rb.AddForce(direction * speed * Time.fixedDeltaTime, ForceMode.VelocityChange);
}
i know i need one line of code delete or change so
You mean it doesn't stop after you stop turning the stick?
The simplest fix is to add some linearDamping on your rigidbody component
Rigidbodies don't slow down automatically unless there is linear damping ("air resistance") or they collider with something and have friction
Do you need help finding linear damping here?
Sure you can do it in code, or just change it in the inspector
this is it?
It's right there
ok!
where add this for my script?
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void OpenParachute()
{
rb.linearDamping = 20;
}
void Update()
{
if (Input.GetButton("Space"))
OpenParachute();
}
OpenParachute(); is answer but where
Do you really have a parachute in the game or did you just copy this from somewhere?
i just found in official unity help web
You don't need code if you don't need it to change during gameplay
i just copy past and learn how i twok
If you want actual official unity tutorials, check !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hi all, I am new to unity and am really confused by some of the things that are happening when using the behavior scripts. Firstly, when I edit the X it's actually editing the Y, is this due to some rotation that I have set on the object I am trying to move? Also, if I don't start the object at exactly (0,0,0) then the object seems to grow a mind of its own and move all over the place. Finally, when I am editing this position (X), why are other coordinates (Y,Z) being affected when I never told them to move in the script?.. Some of this is very confusing to me could anyone help out?
{
void GetValue(string value)
{
if (float.TryParse(value, out float newPosition))
{
Vector3 beforePosition = transform.position;
transform.position = new Vector3(
newPosition,
transform.position.y,
transform.position.z);
// Debug.Log($"Y {beforePosition.y} -> {transform.position.y}");
}
}
}```
ended up doing this
i know its definitely not the best way
but im not getting the error
Are there record structs in unity?
Unity officially supports most of C# 9. Record structs were added in C# 10. So, no. There are some methods to force Unity to use a newer C# version. As long as the features you use don't require runtime support and are just a language feature, it's doable. I don't know if record structs require runtime support.
unity is getting coreCLR in a few years though, that will probably make unity support C# 10
I'm searching for a good inventory guide on youtube is there any recommendation from someone that has followed a guide?
how do i get the magnitude of the horizontal velocity from the rigidbody
Or do you mean on the X and Z axes?
Just ignoring Y?
so i just have to do Mathf.Abs(rb.velocity.x), there is no way to use .magnitude here?
2d game, there is no z axis on the rigidbody
A single axis does not have a "magnitude"
Magnitude is the length of a vector
i mean it can be positive and negative, magnitude ignores the sign, at least in mathematics
yeah that's what magnitude is, mathematically
unsigned value of a scalar, |x|
magnitude of a vector, |v|
distance from the origin of a complex number, |z|
cardinality of a set, |A|
kinda fun to think about
syntax voodoo
whats the best way to rotate an object on a local pivot to a min and max range..
many ways to do it.. and to work out the bugs i believe my code got convoluted.. just curious what other people do (use) in this situation
Clamp?
nah i mean i have a clamp
im talkin about the actual rotation..
u could movetowards a euler prop..
or u could slerp..
etc
ohhh yea.. I always used Slerp for rotations not sure if its fine
Slerp is fine if you don't care about which axes it rotates around to reach the target rotation
Since it takes the fastest route
there was this aweosme post I saw a while ago. Pretty cool visualizing
https://x.com/i/status/1176137498323501058
i have a particular model thats all whacked out in blender -> unity import.. when its oriented the correct direction (while having a container object [the collection obj in blender].. Z and Y both rotate it on the same global axis it appears.. lol.. it completely ignores the gizmo/pivot/local settings... after thorough searching i figured out that the collection is 1,1,1 as it should be w/ 0,0,0 rotation.. yet all the objects facing north and south come in with also local coords of 0 on the X but the ones facing west and east come in with a -90..
soo i can offset that in blender by also changing that 1 object to have a -90 rotation and not applying it.. but then the mesh faces the wrong way.. and i can fix that but its weird b/c the mesh is rotated weirdly in blender.. but the import to unity flips it the right way up..
this is a different issue but the reason i ask about rotation..
yes, ive encountered this with some range dummies that fall down.. and need to be raised again...
but let me note this is the same type of object.. but since its facing North and South its pivot works correctly
oh so its harder with that already "rotation" I think I get it
sorry for the book
it wigs out soo often.. and im trying to force accurate local rotations.. so i can use the script elsewhere
not sure wtf blender is doing to me
I don't follow what the actual issue is
All of these objects look like you'd want to rotate them on one axis only
yes locally.. but in the video i show.. ^ the first one
fine when its oriented with the axis directly..
but as soon as i rotate it downwards.. that same axis with the local transform rotates globally
sooo the scripts dont respect the local transform method im using
isnt the inspector transform a local transform?
affirm
i think the object is broken.. if its not aligned w/ the axis perfectly the transform rotation rotates it globally.. all the other axis' work.. so my script does work b/c it falls on the Z axis.. if it were the Y it wouldn't
should rotate like this..
but instead it rotates like this..
i mean i could leave it.. but it bugs me knowing that if i were to want to change the rotation of another different object that also imports w/ the -90 rotation (the ones facing west and east) the script isn't gonna work
i'll continue to get that weird issue where only 2 of the 3 axis's are actually axising in local space
ohh! heres a perfect example..
how should i find and delete everything in dontdestroyonload
keep references in a list somewhere and destroy them later using that
Here is my script https://paste.ofcode.org/3atNS2diNnxa3bL3vRZxPQ9 I have a issue where for the walk speed I have to put the speed value around 50+ to get the player moving when its at 2 it barely moves. Any ideas why?
@rugged beacon you may be able to get the Dontdestroyonload scene via scene manager and then get the scene root and destroy them that way? (not sure if this is possible though)
did you debug what the resulting vector of that AddForce is? if that vector is as expected, then it could be a setup with ur rigidbody. like friction, drag, or a heavy mass would make it move slower
When I'm using a Cinemachine camera, is it possible to keep the rotation the same when switching between cameras? I've noticed that if I face one way and then switch to another camera, it switches my view back to the way I was facing before.
It really depends on the details
and hoiw those cameras rotate
this is also a #🎥┃cinemachine question
How do i use the "TAB" button in unity, ive tried to use
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreBoard : MonoBehaviour
{
public GameObject scoreboardUI; // Assign in Inspector
void Start()
{
scoreboardUI.SetActive(false); // Start hidden
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
Debug.Log("Tabbed");
scoreboardUI.SetActive(true);
}
if (Input.GetKeyUp(KeyCode.Tab))
{
Debug.Log("UnTabbed");
scoreboardUI.SetActive(false);
}
}
}
but im having issue It wont show up
debug.log isnt logging either
oh and ive also tried a break-point in the code and that wont work either?
Is Update even running?
Put a log OUTSIDE the if statements
if the logs aren't printing the code isn't running, a breakpoint isn't going to tell you any different.
okok lemme try this
also make sure you're not ignoring any errors in console.
BTW:
void Start()
{
scoreboardUI.SetActive(false); // Start hidden
}```
does scoreboardUI happen to be this very same GameObject the script is on?
If so, you're about to facepalm so hard.
yeah it is, also your previous thing was right the update isnt running
how do i get it running 😭
well yeah you're deactivating the GameObject
make sure the code is on a GameObject that isn't being deactivated
create an empty game object?
If you want to make something hidden while running logic, hide the component not the gameobject
I don't care how you do it - you just need to separate this script from the object being deactivated
its on a "panel" since its UI
ahh okok thanks
you could put everything inside in child objects, you could use a tottally separate object
whatever you want
Thank You so much, it works now. I was being very stupid 😭
I was setting the cameras active and inactive to switch between them. It seems keeping them all active and switching them by raising the priority has the intended result.
Guys i know this isn't the correct channel for this but this is the most active channel and the one i get most of the help from,
I've posted about this problem since yesterday without receiving any real help, and i need help with it to keep up with my course
I've checked all types of unity tutorials of Unity Timeline and i've followed to the letter (ig) but none of them has worked out with me, like have this bug in my unity editor that i don't know how to fix
specifically in the first second, it's not even behaving as intended (like it isn't recording the first second at all)
At the very least ask in #💻┃unity-talk
Code is totally unrelated here...
To answer your question, the initial state is considered default, so there's nothing to record. You should research how the timeline works and what it records in the key frames. Is it delta positions or actual positions? If it's the latter, you can probably hit some button to record the key manually. If not, you'll need to make sure your object is at the starting point every time.
Read the manual for the timeline.
And don't ignore community rules or you're risking to get banned.
I really appreciate your help I did ask in unity talk but didn't receive that much help neither (this was since yesterday)
And I'll try your solution and delete this immediately
Thx btw
If no one answered, then no one knows anything about the topic. Or your question is not clear enough. Do your own research while waiting for a reply.
i really really did all of that i swear, i made my question as clear as possible and what problems i'm having and i did a research the entire day without a clear understanding of what i did wrong, but next time i'll ask in a more polite way i promise
ik this is a stupid question but how do i get the input field to start accepting input without the mouse? like normally you have to press on the input field with the mouse to get it to start accepting text, but i want a script that makes it start accepting input when you press enter
google is your friend
https://discussions.unity.com/t/automatic-selection-of-inputfield-ui/633738
thank you
doesnt work
doesn't what work? what did you try
private void Update()
{
if (Input.GetKeyDown(messageKey))
{
messageInput.Select();
}
}
put Debug.Log underneath .Select() , show a screenshot of the Log
its working fine, sending a log once per press of the button
its a tmp input field of that changes anything
show screenshot
i pressed the button 3 times in a row
never played with ragdolls but id assume the gravity on the rigidbodies is on
show where did you put the log in code
also dont crop the entire window for console
private void Update()
{
if (Input.GetKeyDown(messageKey))
{
LogMessage("Calling");
messageInput.Select();
}
}
why
because there could be hidden/collapsed NREs messages
since you put log Before not After as it was said
nre message?
Null Reference
there arent any
Okay but many times someone else was hidden so thats why its wise not to crop such things
where is messageInput assigned ? that UI method normally works fine
there is also another method mentioned in the thread
assigned in the inspector, its a child of the object with the script
is the gameobject enabled?
ActivateInputField, tried it too didnt work
yes
idk I was able to test it again, is working fine here 🤷♂️
are you pressing the correct key?
no idea if log its printing is fine ig
i am, evident by the logs
show me your hierarchy
I bet Event System is missing
THATS IT THAKNS
how do i deselect it when i press enter again
probably similiar function to Select
private void Update()
{
if (Input.GetKeyDown(messageKey))
{
if (inputSelected)
{
messageInput.DeactivateInputField();
inputSelected = false;
return;
}
messageInput.ActivateInputField();
messageInput.Select();
inputSelected = true;
}
}
its a little 🥴 but i can optimize from here, thanks 🫀
oh cool
I found this too undocumented but yeah Deactivate is probably better
https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/api/TMPro.TMP_InputField.html#TMPro_TMP_InputField_ReleaseSelection
The documentation frustrates me so much I find myself vibe coding just to see examples of what some of their functions do
I think it's pretty clear in most cases.
Is there anything specific you have issues understanding?
It's not the understanding issue, it's why does this even exist issue. Such as contactfilter2D
If it exists it has(or had in the past) some purpose. Focus on what you actually do need, rather than investigating everything.
Contact filter is probably corresponding to its name: a data structure that provides some filter parameters.
Yeah and that's the thing. There's no information on what it actually does specifically
that's why it's frustrating
We already have layermask why bloat it?
its filtering for the physics2d class
2dcontact has more filtering specific to 2d physics https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ContactFilter2D.html
who says its bloat? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ContactFilter2D.html
Use a contact filter to precisely control which contact results get returned. This removes the need to filter the results later, is faster, and more convenient.
Is literally the 3rd sentence on the docs and all you need to know
From the look at the docs, it seems to include many different filtering parameters, not just layermask.
The purpose is to filter collisions/cast results more efficiently. But you don't have to use it. You can filter them manually.
You can take that at face value but results shows in some cases it is NOT faster and I want to know why. I don't want the documentation telling me lies
I don't want the documentation telling me lies
I find myself vibe coding just to see examples of what some of their functions do
So the docs which tells you exactly what something does is lying, so you use a spam generator to teach you?
What kind of conversation are you expecting here? What kind of results was it not faster in? There is a lot more here to consider than just saying "results shows in some cases it is NOT faster and I want to know why". Which is something you've seemingly taken at face value because you dont know why!
Everything in programming is context relative. There might be some scenarios where your own implementation would be faster depending on the context.
It is enough to know that it would be faster in most scenarios though.
I wouldnt be surprised if the "not faster" comparison was a case where the filter did nothing.
my source is..that I made it the fuck up
even if it wasnt visibly faster in some cases, which is borderline obvious as to why that might be, the whole discussion is just incredibly silly. saying the documentation is telling you lies feels like tinfoil hat conspiracy.
Just say you don't know instead of pointing me to documentations and thinking you're helping.
If you cannot help someone, don't.
Thanks, I'll continue to help others as I have been 👍. I get you have frustrations with reading in general, which you pointed out in your first message. maybe try re-reading the conversation slowly and asking for more clarifying details in parts you're confused about
Know what? There wasn't even any specific question?
All we heard is that you're being suspicious of the docs.
the message above the one they replied to was my answer on a case where it wouldnt be faster even. its clear they just didn't understand the conversation
And while it's true that the docs can be misleading sometimes, it's generally correct and the only thing we can rely on, as the source code is not available. And the documentation is the next credible thing.
If there's a specific performance issue you're having, it would be so much more productive to use the profiler to analyze the problem and share the details here, instead of making ambiguous tests of the unity API.
Plus, when something says its faster, that doesn't mean it's a noticeable difference.
Talking about cases where it'd be the same speed (or negligibly worse) would imply the ContactFilter2D didn't find anything to filter out. It's going to be nothing in terms of performance for this to run.
For cases where it did filter something out, you have less results to filter through. Going through 4 results instead of 5 is faster. That might be an insignificant boost, yet its still faster and just less logic for you write manually
What are you even talking about? That's not what I'm doing.
I just said I have issues with the documentation not providing enough information to the point where asking AI is literally better than searching dead documents. That is ALL.
You, linking me to the docs, when my issue was the documentation is the most unhelpful response anyone could ask for.
Just say you don't know!
Well this just turned into a block, you clearly cant fucking read lol
they didnt even link you the docs!
Asking AI is definitely not better. It would just lead you into a rabbit hole of lies. While it can be useful, it doesn't have a way to know how unity works under the hood, so whatver it tells you about it is assumptions at best.
Okay you saying it's not better is just stupid and false. I have gotten the result I needed. That's what matters.
Again, don't know what??? You never asked a specific question
There has to be a language barrier here, or they're just trolling at this point. Either way I think it's better we just don't continue this since they clearly aren't looking for help anyways. Just looking to complain I guess
Okay since you're having so much trouble I'll answer for you.
"We already have layermask why bloat it?"
The answer is here:
#💻┃code-beginner message
If you don't know, do not answer. You don't have to provide a response thinking it may help when you're uncertain.
I provided a response based on my experience reading docs and working with different game engines and other programs. If that's not good enough for you, I'm sorry.
I don’t necessarily wanna stir the pot here but one of the biggest problems with using AI to help here is that it will do exactly what your asking this place to avoid
If you ask chatgpt for example “why might x not be faster” because it’s a storytelling engine and not a programmer it’s going to do its best in an attempt to give you the best answer to that question, even if it’s not necessarily true
You are stirring the pot. If you don't know how to use AI you won't get results you want. It's not a magic fix-it all tool, implications that it is just makes you a fool. Just like any other tool, it's how you use it.
I'm pretty much done with this topic.
you should take the AI evangelism to the containment thread https://discord.com/channels/489222168727519232/1352599815770341479
I just said I'm done discussing it so take your snarky replies elsewhere
(It wasn’t snarky whatsoever)
contactfilter exists because 2D and 3D rigidbodies use two different physic APIs
both my conditionals here seem to be firing at the exact same time, is that correct?
i paused playback in the editor & manually moved my player over a platform (which is always going to be on a river, i'm essentially just making regular frogger), stepped forward one frame, and onPlatform became true while simultaneously the player got a game over
ah actually i've just managed to make things work, but i didn't address the simultaneous firing at all so if anyone knows whats going on there i'd still be happy to know
Not simultaneously but both run after each other every time a trigger is entered
What probably happened is that first the river trigger ran which set onPlatform to false so the next check caused the game over, and then the platform trigger ran which set onPlatform to true
If the goal is to not get a game over when the player is on a platform then this logic doesn't do that
ahh yeah i see
thank you!
like i said the code itself works now because i swapped some things around with ontriggerstay & enter but i really appreciate the explanation behind the logic
I'd suggest just ditching tags all together and check a proximity around the player which will give you a list of colliders
this way you can filter out a list and iterate through them in one go
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider2D.Cast.html
Just an alternative way instead of using the OnTrigger methods
Ah actually you'd want to use overlap instead
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider2D.Overlap.html
how do i make scoll view automatically scroll to the newest item
I really don't understand why I can't access Scenes, I don't see any fix for my problem in youtube or google.
using UnityEngine.SceneManagement;
public class PlayLoadScene : MonoBehaviour
{
void LoadGameScene()
{
SceneManager.LoadScene("SampleScene", LoadSceneMode.Additive);
}
}
like, the function "LoadGameScene" should show in this list right
Might be because the function is private
ill try making it public because I think on the tutorial that I watched they didn't put public or private at all
most definitely was public
how do i make scroll view auto scroll to the bottom
thanks
yo, if i put
using UnityEngine.SceneManagement;
SceneManager should show up on my IDE when I am going to type it right?
If it does not, even when I have the suggestions on my IDE turned on, would that mean I do not access the SceneManagement?
because I already made the function of the button and the script but it is not working
it should if your IDE is configured
oh, it is working now when I tried it on void start,
But on button click it won't
You have event system?
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/EventSystem.html
show your hierarchy
I do, should I put the object with the script on the event system?
what showed up where ?
to be sure, i will put a debug on the script of loadscene
event
event system in the hierarchy, in its inspector at playmode
what about it
button name showed up on the inspector when I clicked it,
I mean, i thought you were asking me to test
did you put a log in that function to see if it prints too
I am about to do it
is there a chance that unity would crash when I don't have the scene on my builds and I pressed the button with the script to load that scene?
I seem to be having a lot of problem in my Unity itself, this is kinda overwhelming
different crashes are showing like
It looks like another Unity instance is running with this project open.
Multiple Unity instances cannot open the same project.
like total editor crash wdym by crash
and now it crashed again and a window showed up to Debug unity.exe
when does crash happen
eveytime I test the button
show the function you wrote
I will try one more, and I might do a screen record
using UnityEngine.SceneManagement;
public class PlayLoadScene : MonoBehaviour
{
public void LoadScene()
{
Debug.Log("Button clicked!");
}
}
heres for the debug
Share the logs, share the code.
There's no much point in a video at this point.
Check the !logs after the crash.
I really don't know how to read a crash log
there isn't even an error showing up to my console, along with the Debug.Log
ohhh, I found the problem,
it is the Debug.Log code.. Idk why but when it is present my Unity crashes
everytime I play
that is just weird...
nvm fixed it
How did you fix it?
well, I just removed the Debug.Log since it seems to be a problem to my Unity
now I am worried how I am gonna Debug.Log in the future
doesn´t sound like a solid soloution tbh
never heard of removing debug logs would solve problems
i know right, I feel like its my laptop that is having problems with Unity, like just how would my Unity crash like this when I only tried to stretch a UI in a canva using (Alt + Mouse Click).
have you tried updating to a later patch/minor version?
latest version?
well I'm currently working on 6000.0.26f1
but I'm updated at 6000.0.44f1
As I said, you'll need to look at the editor logs after a crash.
Avoiding using debug logs is not a solution
Btw, this also keeps showing on a different crash
This sounds like something that would appear after a crash when you open the project again.
I follow the code monkey tutorial and I'm facing this problem. Why the red blue and red landmark are not on the floor? Since floor position is (0,0,0) and player position is (0,0,0)
NB: Capsule position is at (x:0, y:1,z:0)
Press Z
Set these to Pivot - Local so the move tool is displayed relative to the selected object
Thanks guys, it worked
Hey, I have this issue where I have to use a high value for walk speed, If I put it around 4 the player barely moves any ideas why?
https://paste.ofcode.org/h94DabMXWuQFT78iuWpYfd
You can just multiply your walk speed variable in the code where it’s being called to amplify it’s value
Start with a smaller number
Because it's force. So the final movement amount is affected by the rb mass, friction, damping
If you reduce the linear damping value, you could probably reduce the force amount as well.
This is not a good practice. Magic numbers are bad.
If you really need to change the value range, make the multiplier a serialized field as well
One issue here is that "speed" is a misnomer for what that field actually does
Or a named constant in code.
Yes definitely create a field for speed multiplier especially if you are using the speed variable elsewhere in your code. Avoid magic numbers 👆
like this?
Yes
And what Praetore said. This value is not speed in any way
It's force
would it be a problem later on?
It would make your code confusing to read. It might even confuse you in the future
oh how would I be able to correct this?
Call it force or movement force or something.
Change this to movementForce?
The variable name, yes.
And the speedMultiplier would be force multiplier as well
Thanks 👍
i've read somewhere that using GameObject.Destroy() can be a bad idea sometimes, if I destroy the enemies using this and I have a prefab made for the enemies, will they come back when i load the scene again?
okay i tested it and it works, resolved
- GameObject.Destroy() doesn't exist it's UnityEngine.Object.Destroy()
- destroying objects in a scene won't affect any prefabs, nor will they affect another instance of the scene you load later
is that in newer versions or
See how it's greyed
You can "destroy" an asset but only with an argument given to allow it. And this only works in editor ofc.
GameObject is a subclass of UnityEngine.Object
that's why GameObject.Destroy works
but the function actually lives in UnityEngine.Object
it says to change it to just "Destroy(gameObject)"
You could have written Component.Destroy or MonoBehaviour.Destroy too
is there supposed to be close to none formatting on this page
no
Hey guys, can anyone help me, ive been doing the unity tutorial 2d adventure game and just made a healthbar but now when i go into the game panel the whole thing is just blue?
Post a screenshot
I'd probably help to show how it looks. That description doesn't help us understand anything . . .
repeat the tutorial...
if it's light/cyan blue it means shaders are still compiling.
Doesn't sound like a code question though
probably just missed 1 step or some config whatever... just go back and repeat the tutorial probably the mistake shows up..
I also have a problem since I use planets in my game I wanted to do a first person camera and the problem is with cameras horizontal movement because of it my player is just flying off the planet
public Transform player;
public float mouseSensitivity = 2f;
float cameraVerticalRotation = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float inputX = Input.GetAxis("Mouse X") * mouseSensitivity;
float inputY = Input.GetAxis("Mouse Y") * mouseSensitivity;
cameraVerticalRotation -= inputY;
cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation,-90f,90f);
transform.localEulerAngles = Vector3.right * cameraVerticalRotation;
player.Rotate(Vector3.up * inputX);
}
}
heres the code for the camera movement
Post !code following the bot . . .
📃 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.
whats the problem though
First solve posting your code
Hi, in a 2Dgame, how i can make that an enemy detects from where it attacks were? i mean the angle
my idea is that when it dies it technically shoots the shards and items to the oppositive side of the damage, so it can give the illusion the enemy exploded and the hit of the weapon sent the shards fly
the issue is, how i can make it detect the angle of the damage?
what are u using to hit
w'e it is u can probably get the normal
then u just reverse it -normal
two things
one are proyectiles that have a ontriggercollision that checks if the enemy has a damage method, and use it
the other is the player who has a (thinking on making it temporal and replace it) overlap that when if the enemy is inside her overlap, and the player clicks right-click, it triggers it damage method
A tool for sharing your source code with the world!
better this
idk, idk. the second if statement is just not working? I think glideForce gets overwritten somewhere? where, i do not know..
You could use some debug logs to see if it's ever running.
Make sure to put it in curly braces if you add another line to the condition body though
elaborate please ;-;
how are u detecting the hit in the first place?
how u know a collision tkes place.. depending on what type of function ur using theres ways to get the info from the contact/hit poin t
Using onTrigger and the other using Overlaps.
It mainly just makes the method of this enemy get on
thats the way i detect it
i think something went wrong with my message, holup
player
private void MeleeAttack()
{
// Cast a ray to detect if an enemy is in range
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, demons);
Collider2D hitProyectile = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, proyectile);
// If an enemy is detected, deal damage
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage, 0);
}
}
if (hitProyectile != null)
{
if (hitProyectile.TryGetComponent(out MortemRifleProyectile enemy))
{
enemy.Parry();
}
}
}```
bullet
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(riflebulletdamage, 1);
push();
}
}```
For OnTriggerEnter2D and OverlapBox you don't really get any kind of directional info
so you can try to approximate it with e.g. subtracting the hit object's position from the attacker's position
or you can switch to some kind of cast
e.g. boxcast or raycast
and that will give you a hit normal
I've played games where you can turn a wheel or crank by clicking a point on the edge or handle and spinning your mouse in a circular motion to emulate spinning it
How would I go about implementing something like that?
For my system I'd need to be able to spin the wheel multiple times, i.e. where the handle not teleporting back to the start position is important, but keeping track of how many times it's turned, and in which direction, is also important
basically:
- each frame track the direction the crank is facing.
- Calculate the angle difference from the previous frame's direction
- Add that difference to the cumulative number of degrees you have turned.
- When you reach the desired cumulative value, do something
it says error...
what erro
keep refreshing or clear cache
