#💻┃code-beginner
1 messages · Page 787 of 1
I am instantiating shop buttons at runtime using Instantiate.
Icon, subtitle and price are set correctly, but the title (TextMeshProUGUI) is empty in the instantiated object, even though:
the title text is assigned correctly in the prefab
the TextMeshProUGUI reference is set in the script
titleText.text = title; is called
debug logs confirm the text value is being set
The title shows correctly in the prefab, but not in the instantiated clone.
I am using LayoutGroup / ContentSizeFitter in the UI hierarchy.
Why is the TextMeshPro text not rendered or invisible after instantiating the prefab, even though the value is set?
is the title text already in the scene?
and are you setting a reference at runtime or by assigning a prefab
i found the misstake Insade of my Data where i store the diffrent buttons the can atteched i missed out giiving it a title waht cursed to have no title even when i was targeting a other title
But now i am facing a new issue the first buttan cant be clicked and bought and secned is possible
Hey Guys, trying to achieve some sort of enemy attack here. The attack would be. laser coming out of the eye of my 2D enemy. so I atttached a linerenderer component and through code I am trying to make it appear when the player is at the right distance. because the laser stay attached to the eye of the enemy and go forward. But now I have an issue. again on Vector direction. I have my spawnLaser empty that is properly rotation (left arrow going left). but when I start to define the index 1 of the linerenderer it's going in the wrong direction.
is your lr not a child object of your player, it should rotate with him
its a component attached to the ennemi. if it help. here is the function
void ShootLaser()
{
float laserLength = 5f;
Vector2 startPos = laserOrigin.transform.position;
Vector2 endPos = startPos + Vector2.right * laserLength;
laser.enabled = true;
laser.SetPosition(0,startPos);
laser.SetPosition(1,endPos);
The Vector2.right is probably the culprit. I am trying to get the direction of the red arrow
transform.right
tried that but then I have an issue because the transform is a vector 3
so I am trying to add a vector 2 to a vector 3, it doesn't work
you can cast one to the other
the issue isn't because you can't do the operation, but because there's 2 things it could be and it's ambiguous
either you could convert the vector2 into a vector3 and then add them, or vice versa
so you need to explicitly cast to specify one
it's a direction vector in worldspace, yes. this is the one you want, if im understanding your goal correctly
it's not because I rotated 180degrees
the laser spawn position.
but maybe I am wrong on the concept here 😄
how is it turning around?
just flipping the sprite, or rotating/scaling the gameobject?
and just enable and disable the gameobject ,you dont have to draw it at runtime, when inspecting your code i dont see anything that you are chaning there
@eager needle answer this
yes
I draw this turkey myself. but haven't thought about that
it sounds like your gameobject's "right" and your sprites visual "right" aren't the same
if you dont rotate the player but only flip the sprite you wont get the result you want
though, you could probably just use the laserOrigin's "right" to fix this for now. you should consider getting a more consistent system in the future though
Hey,
Is it possible to get the key of the found value (dictionary) please ?
I flip the character sprite. so it's good. but really what do you mean ? to always have the same orientation on everything.
it is easy, you are only visually flipping your sprite. you have to rotate it
seems like you might be using your dictionary backwards if you are trying to get a key from the value
I'm using it like this
that doesn't show how you are using the dictionary, that is simply how you are defined it.
where you are using it is where you actually use the variable. you know, like this place where you are trying to get a key from a value even though values are not unique so more than one key could have the same value. there is no built in way to get a key from a value because that's not how dictionaries are supposed to be used
For now the code above in the double for loop is the only place I'm using it in
right so you are using it backwards
why are you trying to get a enum member from a color anyways
and why do you have [SerializeField] on that? you can't serialize a Dictionary
yeah this whole setup seems odd
I'm building a CLUE (CLUEDO) game and I'm using an image where each square is a pixel and each pixel has a color and when I retrieve a color from a pixel, depending on that color I can build my level design (So it's like a Level Editor) and I can assign a tile if it's a room (the enums) or a corridor, etc... and also some colors are player(s) spawn position.
I can serialize the dictionary with Odin plugin
yeah so why not just store the data in the tiles
using colors just sounds like a more obscure version of magic strings to me
I'm but doing that 1 by 1 is painful knowing that I have other datas to add to each tile, so painting a level like this an process that image to spawn the tiles and give it data seems less painful
you don't have to configure every tile individually, no?
can't you basically use tiles as prefabs
how are you creating these maps in the first place? because if you're using something that uses actual tiles then you can just put the relevant data into the tiles you are using instead of attempting to do it "1 by 1"
you mean the image or the level in Unity ?
the image you just showed, how/where is it created
Aseprite
but why? that's objectively harder than just using a tilemap in unity or even Tiled since you're just using a bunch of squares
I can't use a tilemap as my game will be 3D
i didn't say "use a tilemap for the in-game map"
then I'm not sure to understand 🤔
i am referring only to this map mockup that you use to generate the actual map
you can create the mockup using a tilemap and then generate the actual map from that in the editor. and you can embed data in the tiles so that you aren't relying on sampling pixels to get their color
I had no clue that it was possible and don't know how to do that, do you have a tutorial please ?
which part of that are you unsure about
like how to use a tilemap and mainly how to make each tile have data 🤔
how to use a tilemap
unity learn should theoretically have a tutorial about that, but even if it doesn't the manual documentation can teach you about it
how to make each tile have data
inherit from TileBase and put whatever fields you want on it. Congrats, you have your own type of tile with configurable data, then just create the instances of the tiles you would like for mocking your map and throw those into a tile palette
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
read the info above and the error message (that explains it too)
Input class is old input
where r projest settings
Something you can easily Google no?
Thats something you hopefully learn on day 0
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello
I DID IT
Hello , if im trying to make 2D Rig should i make the rig in blender or unity.
ty
hi, i have a question on how to make an effect of haze in 2D and i have not idea how to make it. I haven't find any tuto on it or don't know where to find it
I'm currently working with UI elements and figuring how to drag them around. I'm noticing that I can't change the rect transform position during runtime, so do I have to be manipulating the pivot instead?
do you mean moving them like windows ?
windows?
like app window
nah, just prefabs
what do you mean prefabs ?
using the mouse position to drag them around
in the folder ?
its an instantiated prefab in the scene and im trying to move them around with the mouse via code during runtime
i think you can
i literally cant
have you watched this ?
https://www.youtube.com/watch?v=Mb2oua3FjZg
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=Mb2oua3FjZg
Let's write some code to easily Drag a UI Window and Send it to the Top.
Battle Royale Tycoon
https://store.steampowered.com/app/851930/Battle_Royale_Tycoon/
If you have any questions post them in the comments and I'll do my best to answer them.
...
something like that you want to do ?
i havent yet, ill check it out
okk
already doing what he has, and still not working
let me send the code
A tool for sharing your source code with the world!
the final debug outputs the accurate new local position, but the actual object doesnt move, nor has its position values changed despite the console stating otherwise
it is just a game object ? only with a rect transform ?
rect transform and the scripts, but the other script shouldnt be affecting anything
i think i am still to new to help debug it.
have you try to enable debug mode in the inspector to see if you get the right canvas and transform ?
otherwise another having more experience can help you haha
I am reitering my question if someone missed it.
how to make an effect of haze in 2D and i have not idea how to make it. I haven't find any tuto on it or don't know where to find it
found the issue, it was infact the other script interfering lol
does anyone have a WASD scrollable first to third person movement in unity??
script
ive been struggling to make one
combine the first and third person controllers by unity
No one is gonna have a specific script for these things you need to learn building yourself
thank you
is there such thing as an algorithm that can be run on a marching cubes generated mesh to reduce vertices on flat faces?
Yeah there is 👍
What you’re looking for is generally called mesh simplification / decimation, and it works well on marching-cubes meshes, especially for flat areas.
I have a test code testing raycast in ui gameobjects that looks like this
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit) && hit.collider == this)
{
Debug.Log("the gameobject" + this.gameObject.name + "have been hit");
}
}
} ``` but the raycast did not work on the ui gameobjects, why? (the ui gameobject is not a button)
inbox me
well, does the object in question have a collider? that's what the physics raycast is trying to hit
i don't think you'd want that though
why are you using a physics raycast instead of just doing this #💻┃code-beginner message
How to use eventtrigger component for ui gameobjects?
put an EventTrigger component on the object and it becomes fairly obvious
ok thanks.
I want to add a range showing mechanism wherein if I click on a tower in a tower defense game, I will be able to see the range of the tower in a circle . I want it to be such that, in the future I will be able to increase and decrease the size of the area based on upgrades and stuff.
I figured that I could just change the scale of a sprite attached to it, is there a better way?
is there an easy way to match collider bounds with a non-uniformly scaled gameobject
because when i scale for example a cylinder in the x direction the collider takes up much more space than is visually shown
Have you tried using multiple cubes, or a mesh collider (create a object to the shape you want and add mesh collider to form that shape)
well the issue is i want the collider to match the visual mesh continuously at runtime
Is there something wrong with using a mesh collider?
what are the fundamentals that I should learn first in unity
I had experience with python before
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Beginner pathways.
Hi
sounds like a nice solution, you could also use a decal projector or particle system. i like particle system more, it just looks much better visually
many people avoid using them but once you learn the basics of the particle system you will love them
!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**
I need a mob to decide what to do next and transition into new animator state after his attack animation ends (that mob have it's FSM running in Update outside of animator)
I only see two options:
A) I create Attack state transitions into all possible states (what a mess)
then I read a callback I get from OnStateExit to change it's internal FSM state
B) Attack state have no transitions out of it
then I get a callback from OnStateUpdate if stateInfo.normalizedTime == 1 and through code do a Animator.CrossFade inside internal FSM
So my questions:
Are there other better options? What is the way you d prefer?
Won't option B add one frame delay comapred to option A because of if I get it right A would instantly switch animation when it can and B would have to wait one frame? Can that be noticable? Can it be worked around?
If I think of it it can be worked around by tuning Crossfade normalizedTransitionTime and if it's too long outright doing Animator.Play for next animation
Switching the keys and values throws me this error 🤔
try remove attribute [SeralizedField] on dictionary
That shouldn’t change anything iirc
Commented that part, it works, uncommented it and it still works, wtf is going 🤔
regarding Audio.PlayScheduled(), is there a specific recommended number of minimum time from now to the scheduled time, or is it mostly dependent on lag, etc?
for example, setting PlayScheduled to play at the curret time obviously causes latency, and setting it to play approx. 1 second later makes it fine, but would there be an 'ideal' minimum wait time, if i wanted to play the audio as fast as possible?
(experimentally obtained values are also fine, if someone has already tested this before)
Why doesn't my dictionnary show properly in the inspector ? Like why does it display "None" and it attributes the color of the attic to it and why there are only 9 elements instead of 10 ? 🤔 Like I just added None and Corridor to the enum and it messed everything up 🤦♂️
Odin is what gives support to serialize dictionaries
Perhaps you need to reset the component to update the dictionary to the new default state
Thanks, yeah removing GameManager and putting it back fixes the issue, so is the issue a Unity bug or an Odin bug ?
Its normal
Unity serializes the state strait away. What you have defined in the class its only the "default".
Are you sure this needs to be serializable then? You can use [ShowInInspector, ReadOnly] so you can just see it
if I use those, does my dictionary still show up in the inspector as Unity doesn't support that by default if I understood correctly ?
Yes because those attributes are from Odin
go read their docs
Nice, thank you 👍
Not a coding question. Uses coding channel. 🤷♂️
You can remove packages from the package manager.
oh wow thanks i had no idea mesh colliders automatically changed their bounds when scaled even when the mesh is a sphere
or a cylinder
The collider uses the Transform of whatever object it's attached to
so if both the MeshRenderer and the MeshCollider are:
- on the same object
- using the same mesh
then they will match
In fact, they do a better job of matching the mesh than other collider types. If a parent transform has a non-uniform scale and you rotate the child object, the child gets skewed
but primitive colliders are not allowed to be skewed
(the entire point is that they are very easy to think about; they can't start bending and warping)
how to prevent navmesh from generating inside enclosed meshes? like cubes for example. and merging/masking meshes won't work because im using blockbench for building levels.
yeah mesh colliders are more intensive for this reason im assuming
They’re less efficient, and they’re also a bit less reliable
@zenith cypress you were just talking about this issue
Non-convex mesh colliders don’t really have an inside. They’re thin.
that makes sense because you cant garuntee a volume if vertices go into the volume
mesh colliders are allowed to have holes, intersecting faces, etc.
so there's no coherent way to define "inside" at all
Ah yeah that's the thing I solved for my Trenchbroom imports
it's remarkably annoying!
mobs in minecraft dont spawn inside blocks as far as i know, and i doubt unity is weaker than java 15 years ago
iirc you defined a set of "known-good" points and tried to navigate to them from every navmesh triangle
apples and oranges :p
minecraft just cares about the block under the mob that's trying to spawn
¯\(ツ)/¯
so i should just discard the idea of using navmesh for spawn points
sob..
one thing you can do is test if the mob can reach the player before you try to spawn it
just query the navmesh and see if it finds a path
this could get expensive if you want to try to spawn many mobs, though
That also can give false positives 
i love unity
computer hard
i do, thats the main reason i switched over to unity xd
A lot of paths result in a "partial" result, which can be from "can probably reach you through this gap" to "can't actually reach you because this property is too generalized"
I can probably show what mine does, although it will contain my game-specific stuff but you can probably see what it does and understand an approach that works for you.
thought "well a real game engine would definitely allow me to spawn 1 quadrillion enemies at the same time
"
i honestly just want to understand how to overcome this issue
my main idea is to allow random enemy spawn locations inside of a room
That's what my game does too yeah
i have yet to determine whether i want to store rooms as disabled objects or load them all at once (probably first one)
though the code rn just instantiates new prefabs which i learnt is perfomance heavy. ah yeah perfomance, a nightmare on its own
https://nombin.dev/oo653k4jqnpec57vwyhmzsml this is what mine does for the interior exclusion. Should be straightforward to follow from StartRebuild.
A website to host temporary code snippets.
not sure what im looking at
Interior/invalid location exclusion
well thanks for sharing it
based on the channel we are in - you can assume that i won't be able to use it nor understand how it works
so ig ill just try raycasting upwards to see if there is a ceiling in place and deal with that
you should take the time to read through it, it should be pretty obvious what they are doing even to a beginner
i took 40 minutes

from what i see they build the NavMesh twice.
First to get all triangles then it tests which ones are unreachable from valid points (doors, spawns, anchors)
and then overlays those with an "unwalkable" mesh before rebuilding effectively carving out isolated areas.
its a pretty nifty way of doing it
you can select triangles generated by navmesh?
but they are not selectable in editor
they are doing it through code.
its all in the code like i said
its pretty understandable you just have to read through it carefully
they use a for loop to test the triangles
i might read
but i wont understand
skill issue on my part, like i said
i barely understand what any of the methods used do because i never used them
the unity api is public, you can always look them up
its a good way to learn
analyzing other peoples code and understanding how it works
after you explained how it works, the code became less convoluted
its easier when i know what it should do, otherwise - it just looks like magic to me
!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**
<@&502884371011731486> scam/spam
these are bots
they also post about their artstations and what not
Was out for a bit due to work, but yeah true, I should have put a description with the link at least. Hopefully their help put you on the right path though :)
there are plenty of missing and unknown functions that c# doesnt recognize but im trying
can you clarify?
what do you mean missing and or unknown?
GetComponentsInChildren<InfoAnchorPoint> with DoorRefs() function
as an example
I saw you have prebuilt rooms, you can just use uhh anti-navmeshes (forgot the name)
Little zones you place to prevent navmesh from generating there
I had the same issue and just plopped those zones around, worked perfectly
oh i tried that - obstacles just get ignored
maybe i dont know how to put them correctly
they seem to be misunderstanding what the actual issue is. seems like the issue is the type being used, not the method. because the type is presumably from a package or other code from the same project
No its navmesh modifier
Obstacle just reduces the chance agents will use that area, like a fire or a box they climb
Modifier will prevent navmesh
yeah i do plan to work with pre-built rooms, since trying to go for an actual generation is a bit out of my skill level
Yeah, keep it simple for now, try navmesh modifier and adjust the values on it if needed
you can make a circle using particle system? i didn't know abt that
like im having issues with this xD and its "beginner" level, im feeling quite bad because of it
either way though, this is meant to be an example of how to do what they want, and not a drop in solution
yes of course
yep
so you understand that it is purely an example of the logic you should use, yet you're still trying to use it as a drop in solution?
Yeah it was an example of how to do it for rooms that are more "dynamic" (for my case they are made in Trenchbroom with zero unity authoring hence the need for it to work)
i understand the concept but its a bit out of my scope unfortunately. maybe in the future ill have enough experience to actually make something like that
If you are able to just author stuff on top of your rooms in the editor, then you probably don't need it and can just place your own blockers around (just requires more manual labor)
no? im trying to understand how it works.
then read through the logic that is actually there, and ignore the stuff that calls methods on types you don't have because that is likely not related to the logic you need
Just do this and be done in 5 min
it is against server rules to answer questions with unverified ai generated content
Well they could have just copy and modify the font to make it look like man-made. The real problem here is double checking
ai hallucinates most of the time
Err its a very simple thing lol. Let me rephrase
Add navmesh modifier component to any mesh/zone and set it to override. Rebuild navmesh. Done
I just didnt remember the correct naming
me, when my room is just one model: 
you do realize theres a big difference between what they want to do and what you are suggesting?
ask your ai it might tell you 😉
Add it the same way you added the navmesh. Its literally just a zone with a component
Yeah the same problem i had with navmesh generating inside solid meshes
I dont understand why everyone is acting like this extremely basic feature doesnt exist or is an ai hallucination?
life, if unity prefabs allowed storing navmesh: 
They allow storing the overrides
Anyway i solved this very easily in multiple game releases, so goodluck with the overengineering I guess.
that can work
how can i make the player squeeze when moving?
ahh really i forgot sorry
explain what you're trying to do! we don't know what "squeeze when moving" means
bro forgot
i meant like when dashing the player squeezes to add more game feel
2d platformer game
what is tweening?
lets you animate certain values at runtime through code
for you that means you get to animate your characters scale
to make them stretch
oh you mean the asset
tweening is just a general concept.
there are many libraries you can use for it
the most popular one being dotween
but theres also leantween
Libraries like DOTween make it really easy to do these kinds of effects.
When you dash, you'll briefly change the scale of your character
if i scaled the x or y value it might break my character logic
consider setting up your character like this
- Player <-- the collider and other scripts
- Visual <-- the SpriteRenderer
this lets you move/rotate/scale the visual without affecting anything else
how would I make this check all of the objects in the array all together instead of one at a time. it seems like the else statement is just changing the bool back immediately for each one of the game objects.
It would check every object in the array, one at a time.
You can fix this by setting the bool to true before the loop, then on first active self, set it to false and break.
You can use linq as you were doing before, but it does the same thing behind the scenes + a small mountain of overhead.
If this is in update, there isn't anything that would change the state of the if-statement. The same thing would happen every frame.
just trying to make it so the else isnt just instantly covering it up by something else in the array
you mean like swapping their places?\
Are you not able to show more code?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
No. Read my message again.
!IDE 👇 you need to get your IDE configured
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
You don't need else at all here.
This is very likely an x/y problem where you're getting a behavior that isn't wanted because of something else.
No, it's clearly a logic issue. They want to set the bool to true if any of the objects in the array are inactive.
yes
But yeah, configure your ide as well if you need further help.
but then how does it turn back off....
This is only going to care about the last object in the list
Whatever the last object is, that's what gun.shootingbuttonenabled is
well yeah.... thats why I asked for help
So what do you want to happen
as I said up here, id like to check them all at once
all together I mean
There is no "all at once" in programming. Code runs one line at a time. You'll need to rephrase your thinking. What should it be by default, and under what conditions should that change?
anybody know a simple way to draw a rectangle to the screen with given vertices in screen coordinates or something analogous with world coordinate projections?
thats why I had the else, with the idea that at the end of checking everything it would change based on that. not sure how to go about that
else runs if the previous if did not
any suggestions on what I could do to do it at the end of the whole array?
Pick a default state, then look for whatever condition makes it be the other, and check for that
"gun.shootingbuttonenabled should be true unless _____" or "gun.shootingbuttonenabled should be false unless _____"
fill in the blank, then check for that
You set it to false if the condition is right.
so if I just did an if statement right below with the opposite it should work? just another obj.activeself == true
bool = true
Loop
{
if condition is right
{
bool = false
break out of the loop
}
}
ah ok
Code runs, one line at a time, top to bottom. Whatever the last thing you set it to is what it is
So, pick one to start at, and only change it if you need to
but I do need to change it
They were using LINQ .All before, but incorrectly, so I assume they meant something like linq that checks a collection in one line of code.
Under what conditions do you need to change it
What exactly are you trying to do?
Are you wanting the state to be true if any of the objects were not active?
I tried swapping it just for the sake of it. I want the state to be false if any of the objects are active
So, set it to true, then, if any of the objects are active, set it to false
You don't re-set it back to true ever
Just once at the start
and set it to false if it should be false
shoot = true
foreach ...
if ...
... = false
break;```
hahaha mb
Think through that in your head. Step through it, line by line.
Let's say you have a list containing, in order, an inactive object, an active one, then an inactive one
What does your code do in that case?
couldn't we break without the bool at start ?
what the issue? how to find the first active object in the list ? ( maybe i missed something)
this
this is my sloppy solution. ill lyk when it breaks guys. thanks for the help
why this much space ?
ive been avoiding arrays for 4 years so this all really helps
they are shy
You would check every object, one at a time. The behavior you're aciuring isn't due to the first part.
Please just step through this. Line by line. Think it through one at a time.
bro it works
No, you just havent encountered a situation that breaks it yet
no
This is a pretty messy solution. I literally gave you the pseudocode that solves the issue neatly...
Why didn't you just implement it?
it work for only a specifique stuation
didnt really understand
Do you have any idea what this code is doing
yes
but it works because I wont ever have two objects turning off and on with that script involved
what ?
Then ask, goddammit.
Ignoring everything you don't understand in life is gonna get you into a lot of trouble...
I've explained this concept multiple times already
#💻┃code-beginner message
it goes through the array and checks if an object is active. depending on the result of each object, itll save the object into consideration for later to wait for it to be false technically
No
It will store the first active object
Then, if that active object is inactive it'll set the bool to false
An active object of course cannot be inactive
So what is the point of checking if the object you just confirmed is active is inactive
still doesnt really help me, it makes sense but it doesnt to me.
How about you fill in the blank
And then it will make sense
Either blank
One of them will be easier than the other but both work
but isnt that the whole point of this script and the loop?
are you suggesting I make it true before the loop in the update?
there a 2 ways to do it
Considering that at this point like six people have told you exactly that, yes
Or the opposite, whatever's easier
i like give answer but if that person don't understand it is better he find the anwser himself
What i get is you have a gun , with a list of gameobject (for what , idk)
each update (not the best idea but well)
you check if you have an actif object in the list, if yes then you can't shoot but otherwise, you can shoot ?
just like this?
Set it one way. Do the loop. If you find a condition that means it should be the other way, change it
yes
Where's the break?
oh miss the break
At this point it doesn't matter let them do extra loops it's at least better than whatever the fuck that last attempt was
lol
but the ideas is same
you have a lot of ways doing it, some faster, other more easly to understand but slwoer etc
break will not make the code after the loop not run, in fact it will immediately go to that code. so that // turn gun on bit is what will run immediately after the // turn gun off part
oh yeah my bad i write it to fast
haha
turn gun on should be upper
so the break would start it over before it turned the gun back on?
and not work is what hes saying
what? that is not what i said at all. break doesn't start anything over
Break ends the current loop
break = stop the loop
so it wouldnt run whats below it in the update?
Break ends the loop. That is it
That is all it does
it would, which is what i was saying. break only affects the loop and literally nothing else
like the words mean , your loop is a list of function doing almost the same thing then you break in middle
It ends the for each
Break would stop the loop.
It doesn't do anything else
I see
easier haha (but all type of loop like while, for, for each etc)
btw, switch for you is a loop or not ?
for me it a loop but maybe it isn't
you do realize that they were referring to this specific situation, right? they weren't saying that break only works with a foreach loop
The break statement terminates the closest enclosing iteration statement (that is, for, foreach, while, or do loop) or switch statement.
yeah but we never know if for him , it work only for an foreach
Does anyone know how i can perhaps project a sphere in world coordinates onto screen space coordinates
Converting world to screen point: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Camera.WorldToScreenPoint.html
Spherecast (assuming you're simply wanting a physics cast): https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.SphereCast.html
oh i mean like get from a sphere in world space to having a circle in screen space with a center and radius and stuff
also ive been trying to set it up, I just downloaded a more recent version of visual studio and its connected under prefrences in unity but now my variables arent suggesting. I also made sure to have the unity game development thing on visual studio too. not sure whats missing
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
thanks
Hey 🙂 I just wanted to make a Panel but it takes opver everything, why? and how can i fix it
this is a code channel. also, with it being a UI object, it lives on the canvas which is why it appears gigantic in the scene view, but normal size in the game.
read the documentation pinned in #📲┃ui-ux to learn how the canvas and UI work
Is there any easy way to detect if a world space object is within some screen space bounds?
Google has currently been failing me for a half hour now...
the answers are there
break down the problem further so you can find more
hmm i read it but i still ahve the iussue woith my file maybe u can help oout?
it generally helps to actually explain what your issue is
and in the right channel
You'll need to describe what specifically you're needing help with.
ahh the classic I have issue plz help, proceeds not to describe the issue
I imported a big map image (1920×1080) directly into the scene. Now when I add UI (Canvas/Text), everything feels off scale-wise.
The map is already scaled down a lot, and if I scale it more, the aspect ratios start breaking.
What’s the right way to handle this?
Should I resize the map via PPU instead of transform scale, or is this more of a camera / canvas setup issue?
this is a "you didn't actually read and understand the information about how the canvas works" issue
Sry 🙂
You need to better explain what you think is wrong. But in the right channel. #📲┃ui-ux if it's ui related or #💻┃unity-talk if it's not(if the issue is with a map that is using a sprite renderer for example).
I've got a question on this. It does work. But I've confused myself. Why doesn't it just always read that the shooting button is enabled? Because if it goes down the lines of code wouldn't it set it to true again before making it false?
Like does it keep on changing it every 0.00001th of a second. I'm just trying to understand it more
Since every update its made true
It sets it to true and then either keeps it true(if the condition is not met) or set to false until the next frame if the condition in the loop is true.
So what your saying is that the "set to true" part of it doesn't actually go through until the end of the update or frame?
No, it applies immediately, but it doesn't matter. Because if the condition is met, then false is assigned immediately after that.
Assuming your code is relative to what's been discussed before, it is set to true prior to testing then set to false if any objects were active that frame.
There's no randomness. When it enters update, it's always the value that was set in the last frame.
How does it currently look btw
It looks good. It does work. I just keep on trying to understand it. Like I get that it works like that. But I also just think it would be split 50/50 true and false. Simply because I have something always saying it's true on that update, but then something checking on that same update and changing it right after. But if it's changed that quick, wouldn't it also be changed back to true just as quick?
Just trying to make it make sense
For now it works and all I can say is "it's just unity" it's not wrong. But the timing doesn't make sense
keep in mind that nothing else is happening between the variable being set to true and it being set to false, but pretty much the rest of your game is happening outside of that update method
so basically it's true for "no time at all" on frames that it should be false, and will remain false until the next frame so the remainder of the frame it is still false. then the next frame, the exact same thing happens. until a frame where the loop never sets it to false
So.. think of it this way..
Before Update is ran, let's assume the bool is false. The first line would set it to true because we're wanting the default behavior set it to be true. Then, if and only if any object were active would we instead want it to be false before the end of the Update method. Your final result would be the state of the bool at the end of the Update method
Nothing trippy here. You pc executes code line by line. No code at all runs while this script update is executed(let's ignore threads for now) . So for the rest of the game, it's either the value before it's update or after.
So is nothing updated until the "end" of the update? Which would still be super small anyways
Yes.
that's still not quite it. the variable is changing. as has been said before.
but nothing else is checking the variable during this time because only one component is updated at a time
The confusion might be with the assumption that others are accessing and using the variable whilst it's changing. They likely aren't as nothing is running in parallel unless you've got multi threaded lines of code operating somewhere.
Only one line of code is ever running at a time. There are no lines of code between setting it to true and setting it to false that use the value. So, nothing will ever read the value as true before it has the chance to get set to false.
There that's it that makes sense
The entire Update method has to finish before anything or anyone else can do anything (rendering to the screen, physics etc)
Mmm ok
hello, i'm having a bit of trouble with my raycasts as they dont seem to be detecting stuff properly
this is what i've tried:
void Start() {
data = rock.GetComponent<RockTypeLinker>().data;
rocks.Add(rock);
for (var i = 0; i < data.iterations; i++) {
currentRocks = new List<GameObject>(rocks);
foreach (var useRock in currentRocks) {
var testUnityIgnore = false;
// right x
if (!Physics.Raycast(useRock.transform.position, useRock.transform.right, out var hit, 1f)) {
var newRock = Instantiate(rock);
newRock.transform.position = new Vector3(useRock.transform.position.x + useRock.transform.localScale.x, useRock.transform.position.y, useRock.transform.position.z);
rocks.Add(newRock);
}
}
}
}
basically what i want to happen is
iteration one: no cube detected so it creates one
iteration two: cube deteced, no cube is created
...
but what's happening is:
iteration one: no cube detected so it creates one
iteration two: no cube detected so it creates one
...
I've tested in other scripts and the cubes can detect each other just fine.
this is the result (looks expected) but actually there's cubes inside cubes
when I drag a unit, since the unit has two colliders one it's parent gameobject and child gameobject, I end up dragging the gameobject when my mouse is on the child collider. I want it o be such that I only drag it when it's on the parents collider.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
public class UnitRelocatorScript : MonoBehaviour, IDragHandler
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
Vector3 mouse_pos;
private Collider2D _collider;
void Start()
{
_collider = this.GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
}
public void OnClick()
{
Debug.Log("Object was clicked.");
}
public void OnDrag(PointerEventData eventData)
{
//6 = tower layer
if (_collider == eventData.pointerDrag.gameObject.GetComponent<BoxCollider2D>())
{
gameObject.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
Debug.Log("Object is being dragged.");
}
}
}
Try drawing the raycast
It might not be where you're thinking it is, how long you're thinking it is or something else
hello, i'm having a bit of trouble with my raycasts as they dont seem to be detecting stuff properly
this is what i've tried:
void Start() {
data = rock.GetComponent<RockTypeLinker>().data;
rocks.Add(rock);
for (var i = 0; i < data.iterations; i++) {
currentRocks = new List<GameObject>(rocks);
foreach (var useRock in currentRocks) {
var testUnityIgnore = false;
// right x
if (!Physics.Raycast(useRock.transform.position, useRock.transform.right, out var hit, 1f)) {
var newRock = Instantiate(rock);
newRock.transform.position = new Vector3(useRock.transform.position.x + useRock.transform.localScale.x, useRock.transform.position.y, useRock.transform.position.z);
rocks.Add(newRock);
}
}
}
}
basically what i want to happen is
iteration one: no cube detected so it creates one
iteration two: cube deteced, no cube is created
...
but what's happening is:
iteration one: no cube detected so it creates one
iteration two: no cube detected so it creates one
...
I've tested in other scripts and the cubes can detect each other just fine.
you just pasted my thing?
it seems to be in the right position and going in the right direction
when I print the value of hit (assuming not null) it prints nothing
so the raycast specifically in this script detects nothing
but when run from another script it detects just fine
Is it going far enough?
i tried with no limit and a really big limit, still didnt work
The max distance seems to be one relative to your code
the scale of my cube is 0.5,0.5,0.5 so 1f isn't short
especially since they're next to each other
but i have tried with no maxDistance and a really big maxDistance
made no difference
Can you show the raycast debug drawn?
hello guyz
Do the objects have colliders?
there's a raycast going through every cube (and the raycast is being fired in each cube too)
they all haev box colliders and rigidbodies (kinematic)
and i tested in another script it seems to have nothing to do with them being kinematic or anything wrong with their colliders
So.. how many rocks do you start with? Is this Start method in every rock?
What is currentRocks?
to prevent it from adding to the list it's currently iterating through i created a second list that isnt affected at the same time
whole snippet
using System;
using System.Collections.Generic;
using UnityEngine;
public class RockExpansion : MonoBehaviour {
[SerializeField] private GameObject rock;
private RockObject data;
private List<GameObject> rocks;
private List<GameObject> currentRocks;
private void Awake() {
rocks = new List<GameObject>();
}
void Start() {
data = rock.GetComponent<RockTypeLinker>().data;
rocks.Add(rock);
// create rocks whenever it cant detect something is there with a raycast
for (var i = 0; i < data.iterations; i++) {
currentRocks = new List<GameObject>(rocks);
foreach (var useRock in currentRocks) {
var testUnityIgnore = false;
// right x
if (!Physics.Raycast(useRock.transform.position, useRock.transform.right, out var hit, 1f)) {
var newRock = Instantiate(rock);
newRock.transform.position = new Vector3(useRock.transform.position.x + useRock.transform.localScale.x, useRock.transform.position.y, useRock.transform.position.z);
rocks.Add(newRock);
}
// left -x
// front z
// back -z
// top y
}
}
}
private void OnDrawGizmos() {
Gizmos.color = new Color(0,0,255);
foreach (var roc in rocks) {
Gizmos.DrawRay(roc.transform.position, rock.transform.right);
}
}
}
How are you creating more rocks after the first?
in the raycast part
if (!Physics.Raycast(useRock.transform.position, useRock.transform.right, out var hit, 1f)) {
var newRock = Instantiate(rock);
newRock.transform.position = new Vector3(useRock.transform.position.x + useRock.transform.localScale.x, useRock.transform.position.y, useRock.transform.position.z);
rocks.Add(newRock);
}
that's where my issue lies
it's creating cubes even if something is already there
But that would stop after the first.
How are you continuing to create more rocks (assuming this script isn't on the rock object)
in that same code there's a for loop and a foreach loop.
the for loop, i want it to run 3 times so that there's a good amoutn of cubes
the foreach loop is to create cubes around it (but i havent added that yet) so instead of hard tracking locations and positions and cubes im only making sure nothing's there and thne just going for creaintg it
this is the first part but it seems to be failing
You've said that you start with a single rock and that the rocks are not running this code. My assumption is that there isn't anything wrong with the above but that whatever (some manager) is the issue.
i dont see how something would be wrong with the manager
it's an empty gameobject at 0,0,0 with that script on i
and at no point have i accessed the raw transform without it being either rock or useRock
If you're doing this all instantaneously, the colliders will not have been updated until a sync has occurred
i see, it probably is instantaneous
Thus each and every ray cast would not detect any object where an object might be
You can use a physics sync after creating the rock if you're wanting this all to occur instantaneously
alright, i'll check that out
thank you!
if that fails i'll just add a manual delay
that did fix it
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Physics.SyncTransforms.html There's some cost (just a warning)
if anyone can help?
it's dragging both the parent and the child when you drag the child?
on what object is this script?
if it's on the parent then your gameObject.transform stuff will affect the parent
parent
try putting it on the child or accessing the child's gameObejct instead
Could probably check if the clicked or dragged object has any parents
you could also check what pointerDrag actually is
the gameObject is this:
- Parent:
- Has collider and if mouse is dragged, while on this collider, parent should move.
- Child:
- Has collider on it and should not be moved when mouse is dragged while on this collider.
i have attached this script to the parent
this part will only run on the parent
gameObject.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
because gameObject like that just accesses the gameObject that the script is on
you should instead be running the pointerDrag.transform.position or something like that
isn't that what you have?
with this when you move the child it only moves the child but when you move the parent it moves both
no more like, i want this to happen
so the child is not supposed to be draggable?
but its not happenning, instead, when i click and drag on the child collider, the whole thing gets dragged (parent and the child)
Yes the reason the whole thing gets dragged is because you're accessing the whole thing
what you suggested won't help then, cus it ends up moving the child only, not the parent or am i misunderstanding something?
So... you need to clarify something.. are you just wanting to parent to move without the child or?
if i click and drag on parent collider, the parent and child move, if i click on the child collider, nothing moves
nothing moves?
that was never stated before
before you said everything moved
unless that's the outcome you want?
yes
but everything moves right now, doesn't matter which collider i am dragging
oh okay

can you check which object pointerDrag is?
no like
in code
Debug.Log(eventData.pointerDrag)
i would imagine your function looking like this
public void OnDrag(PointerEventData eventData)
{
//6 = tower layer
if (_collider == eventData.pointerDrag.gameObject.GetComponent<BoxCollider2D>())
{
Debug.Log(eventData.pointerDrag.gameObject);
if (eventData.pointerPressRaycast.gameObject != gameObject) { return; } // if the object IS NOT the parent (which is the object with the script) then do NOT drag
gameObject.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
Debug.Log("Object is being dragged.");
}
}
sry its taking a lot of time potato pc
haha take your time
also i think part of the issue could be the parent's hitbox being above the child's
based on your image
its on the parent
both have hitboxes?
if the parent covers the child then the child cant be dragged, ooonly the parent
more like, its inside the child's hitbox
is the child the big one or the small one
big
Pointer drag is on Droplet(Clone) (UnitRelocatorScript) object.
UnityEngine.Debug:Log (object)
UnitRelocatorScript:Start () (at Assets/Scripts/Unit Relocation/UnitRelocatorScript.cs:13)
it is on the parent, not the child i guess
when you tried dragging on the child did it show Droplet (Clone)
yes
that must mean your child's collider is covering the parent's collider
yes
maybe try going innto 3d view and move your child back behind it on the z axis
wait no
if the bigger collider is on top of the smaller collider and preventing the smaller collider from being pressed then maybe try move the bigger collider back on the z axis
that's not the problem
oh
true
okay so when you printed it it acknowledged that you were dragging the parent?
even when you tried dragging the child?
okay
i could just make the BoxCollider2D a child and then put the script on that child
it's kinda working, the unit does get dragged the correct way at first, but the moment i try to drag it a second time, the event doesn't even get called
gamebar recording it dumb so there's a vertical offset, so even though i know i am clicking on the object, it appears as if i ain't clicking on the object
something i noticed was that in the Scene, if i change the collider a bit, then the next time i try to drag it on the game screen it does get dragged but then it becomes undraggable unless i change the collider in the game scene again
kill me pls, these bugs are so bloody hard to notice
i don't even know why i got the idea that the box colliders being on the same z axis somehow broke the thing, but apparently it's what was happening
the hell man?
you can't use the null-conditional operator (?.) with Unity objects . . .
Is it possible to have a single material that has a Color parameter that I can change through code and without having that same material applied to other GameObjects also change their color ?
By that I mean if it's possible to create a single material and I need to spawn alot of tiles and each tile will have different color, so modifying the color of a certain tile shouldn't change the colors of the other tiles and without me having to create 1 material per color that I want to use.
yes you can access the renderer's color property
it's Renderer.material.color
tried this but it doesn't work 😕
can you record or show what hpapens when you try to use this?
Is it because it does not work with Unity’s fake-null when objects are destroyed?
there might also be .SetColor() on that material (material.SetColor(pixelColor))
oh wait, it kinda work but it's messed up because the default color of my material is red, I need to switch that for white
ah okay
Let's go, thanks 👍
nice!
Why does it tell me it's redundant check ? 🤔
What makes you think it's not
Without the check or not, the field will still get the given value
Why do you need to check it before setting it
What is the difference between this code and one that doesn't have it
just to not repeat the assignement if the value is already the same ? 🤔
Why would that matter
The variable is that value either way
There is not a single difference between the code with the if and without
micro-optimization I guess 😄 Does that optimize something or it changes nothing ? 😄
Optimizing what?
assignation of value
No
You can't get any faster than zero time
no way assignation takes 0 time 😮
All it does is assign a name to a point in memory. The name is the same, the pointer is the same
Why would that take any time?
well each action a computer does technically take some time (milliseconds or microseconds but it's still time), isn't it ? Like lookin for that point in memory then assigning a name to it can't be free of time, isn't it ?
And an if statement somehow doesn't?
U are worrying about something that probably takes trillion or more of them at the same time to start affecting the system
yeah it does; that was my next question : which one would consume more time between an assignation and an if statement ? 😄
I agree, it's more out of curiosity and taking good practices 😛
If anything the comparison is slower since you now need some redundant ldarg instructions to do the comparison (even in release mode so the compiler doesn't optimize it it seems). But for this is doesn't really matter, only thing that does is the takeaway of why it isn't needed in this case.
The answer is who cares. This level of optimization would be overkill on a 1960s punch card computer the size of an apartment
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Program : MonoBehaviour
{
publicTransform vehicleTransform;
Vector3 dir;
private void Update()
{
dir.Z = vehicleTransform.eulerAngles.y;
transform.localEulerAngles = dir;
}
}
would this work for a magnetic fluid compass inside an aircraft cockpit?
if the compass is just a cylinder with a compass texture and its origin faces front
also how would i go about writing a script for textmeshpro to read the title of an mp3 file playing through an in-game media player
Did you try it and did it work? If so then the answer is yes. If not, the answer is no
mb i'm away from my unity-runnable computer so i just thought if anyone's ever worked on a compass they might be able to assert whether it looks right
Its not a good idea usually to read the euler angles from an object because its stored as a quaternion. When converted to euler angles, it can be many different values but all of them could still lead to the same rotation.
If it works in your case, good. Ideally you would swap away from reading the euler angles in some way
alright thank you
what other kinds of angle conversions are there?
just because eulers seemed like the match for aviation related orientation
Theres a few ways to construct a quaternion which you can see from the docs, but really if the car doesn't rotate on the x or z axis then this might be safe to use
it's an airplane so it does rotate...
or as far as i understand is able to rotate on all axes
then maybe you'd want to construct a quaternion based on the forward direction of the plane. Really im not sure what the intent is here or why you set the localEulerAngles so it's hard to give a complete answer
i guess i did that very wrong
hold on let me show you a picture of the kind of compass
it spins on one axis in relation to how much the aircraft deviates from the north on a Z axis (aka aircraft heading)
there's an in-game heading indicator already but it isn't analogue like this one
i should've probably thought about checking the kind of angles it uses before i left home...
first thing id think of would be using the forward direction of the plane, set Y to 0 because you dont care if its pointed up or down right?
Compare that vector to like vector3.forward to get the angle to set the Z value of this object
I was waiting for you to respond I found out the game I’m making this for does use eulers for orientation
Would I still change my code how you suggested?
your game doesnt use eulers for rotation, its always stored as quaternion no matter what
Well at least it’s understood as eulers by the indicator? I’m not sure how it’s possible
It's not a good idea to ask code questions when you don't have access to the project. But basically to keep the compass always pointing north this should do it:
Vector3 direction = Vector3.ProjectOnPlane(north, aircraft.transform.up);
transform.rotation = Quaternion.LookRotation(direction, aircraft.transform.up);
where north is the direction where you want it to point in world coordinates (e.g. Vector3.forward) and aircraft is a reference to the airplane object
Sorry I just want to get ahead during winter break😔
But thank you for the help
the indicator is just a texture on a model
you can think of it using euler angles, you can set it using euler angles, its stored as a quaternion
Oh okay
So even if the math will use eulers no matter what I want it to reference the quaternions instead
It doesn't matter what you use, Unity will end up using quaternions anyway
the conversion is automatic
Ohhhhh
yea but the problem is really just trying to read the euler angles because its stored not as euler
you can fully keep track of everything using eulers stored as your own values, thats no problem
This just gets more confusing
I guess I’ll have to watch a video for how eulers work in unity and maybe read up on linear algebra
id just start with this
Hey i've been trying to figure out how to run an if statement once in Unity and im just really confused how to stop the if statement after it runs once, because everytime I play test, when the player activates the function to spawn a new level it spawns infinite levels and crashes.
An if statement would only occur once. You're probably calling that line of code more often than once somehow.
could anyone explain how i can get a normal map to work or whatever its called? The thing that makes a material look more 3d
semicolon on the if statement + it's seemingly due to the bool you are checking
your using whats called a local variable, it exists exclusively in the context of when that function runs
and it's not doing anything either
like so your 100% clear these 4 lines (plus the bracket) are the only things doing anything
Maybe you can instead describe what's occurring in the scene and how the object relates to the scene
pretty much, for that script at least
and I dont think it could be due to anything else
Let me take a video recording it rq
OnTriggerEnter is only being called once when you enter the trigger, you you must be doing something wrong there. also make sure you check fof the right gameobject inbside the OnTriggerEnter
if (other.CompareTage("something"))
A video isn't necessary.
That trigger message is occurring multiple times. You've got to figure out why
(or ideally check for a component 😄)
Yo i just realised I made a stupid mistake and I didn't mean to put it in the on tirgger enter script
I gotta fix that rq
allright then if you want that code inside the Update you would simply use your "hasRun" boolean in the if statement too
so the condition is only met when your bool is false
Ok, so when I go ahead of a specific area on the map it makes it place an infinite amount of clones into the project and crashes the game, I am trying to figure out how to make the method only run once like flicking a lever you cant flip back on and off a ton.
Btw, this is the coding channel. You should probably move your message to #💻┃unity-talk or some other more appropriate channel to acquire proper support from the community #🔎┃find-a-channel
So, the trigger enter message only occurs once (on initial trigger entered). Are you teleporting the player? Are they being teleported back immediately? Something like this would crash the Editor.
I'm trying to make a simple infinite runner and if the player walks a small distance from a cube in the starting level it creates a new level, but my mistake is that I can't find a way to tell it to stop the if statement. It just keeps running the statement over and over because the condition is always met. The player doesn't teleport at all, it's just infinite levels are being created way too fast, and I need a way to stop the if statement from activating (even when the condition is met) once it runs once.
and i already told you how to do that
because the condition is always met.
You've kind of figured it out on your own here tbh!
Your not doing any code that would make it ever stop meeting that condition
if ( condition1 && !hasRun)
{
some code;
hasRun = true;
}
how do I make a code that stops it from meeting the condition
If statements! You already have 1 there
Ok so now what do I do with hasrun, ik I have to make an if statement that makes it stop running but im not fluent in C# and I don't know what will stop/negate the first if statement
you can check for multiple conditions by either nesting, eg.
if (thing)
{
if (otherThing)
{}
}
or you can do like
if ((firstThing) && (secondThing))
{
}
That's a misunderstanding. The if statement in that method only runs once. If you're wanting to reuse that trigger method you'll need to think about how to ignore or change the behavior (delegates etc)
Are you sure that's what they are running into here
he already mentionjed that he put the code accidentaslly into the OnTriggerEnter
he wants it in the Update
you were the first and only(?) person to bring up Update unless im missing something
Don't recall update being mentioned
i think homie is just new to if statements..
Naw it was in OnTriggerEnter, it is in update now
here Dalphat #💻┃code-beginner message
well it is the only place that makes sense if you lok at his code
he is making a runner game
so we have already provided you with all the code you need, please scroll up and read again
I'm assuming they've got an infinite runner where they're loading/cycling new tracks as they reach a certain point on the road. Where I'm assuming their character may be triggering the enter method repeatedly somehow
alr
yes but in the #🖱️┃input-system channel @stark helm
Are you referring to just debugging if an action has occurred?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/manual/Debugging.html
yeah but how do i stop or negate the code, would I do something like
if (hasrun == true)
{
//some code that would negate the first function somehow (I don't know any things that do that)
}
We're not entirely certain. Polling is least preferred if you're able to resolve the event when it's occurred instead
The video would be fine for illustrating what your issue is now since we're uncertain what's going on (no in game images, hierarchy, inspector data, other scripts, etc)
Sorry my internet cut out
Im trying to send the video rn
Sorry for it being short, I don't have nitro so I don't want to run the risk of it not posting, but the main problem is still the infinite levels but for some weird reason the script isn't registering the mole as a game object or something.
Mp4 or some other video format that's discord safe is preferred
And Murado if your still here Idk if im dumb or what but I still don't know how to negate the script, what you told me showed me how to create something that could hold code that would negate the script, but idk any ways to actually negate the script with code
public class PlayerController : MonoBehaviour
this is the public class
and i put it here
public class PlayerController : MonoBehaviour
private Rigidbody rb;
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
void OnMove (InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
public class PlayerController : MonoBehaviour
private Rigidbody rb;
private float movementX;
private float movementY;
void Start()
{
rb = GetComponent <Rigidbody>();
}
private void FixedUpdate()
{
Vector3 movement = new Vector3 (movementX, 0.0f, movementY);
rb.AddForce(movement);
rb.AddForce(movementVector);
}```
You're missing curly braces for your class
Hopefully that isn't exactly how the script looks
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thats what i'm using
ok this is looking better, now change the bool to private, i am assuming you are overriding it in the inspector. and get rid of the if statement with the return
You should probably go through the basic unity learn scripting tutorial
arlight i did all that, thanks for pointing that out, forgot it was public.
They've got quite a few basics I don't recall off the top of my mind
oh ok
What should I do next, how do I actually negate the if statement once it runs once.
you are already doing it correctly. please send the code as text so we might see how it looks now
'''cs
using UnityEngine;
public class LevelSpawner : MonoBehaviour
{
public GameObject CurrentLevel;
public GameObject[] LevelPrefabs;
public GameObject Mole;
private bool hasRun;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Mole.transform.position.x + 5 > CurrentLevel.transform.position.x && !hasRun) ;
{
int LevelIndex = Random.Range(0, LevelPrefabs.Length);
Vector3 SpawnPos = new Vector3(CurrentLevel.transform.position.x + 25, CurrentLevel.transform.position.y, CurrentLevel.transform.position.z);
Instantiate(LevelPrefabs[LevelIndex], SpawnPos, LevelPrefabs[LevelIndex].transform.rotation);
hasRun = true;
};
}
}
'''
this looks ok now for now, at least it should only run once
could it be that you have this script on your prefabs? because everytime you spawn a prefab then it runs this
yeah I have this script on my prefabs
there you have it
but also something else is entirely wrong
because for some reason the starting level wont pick up a game object I set as a mole as a mole
it shouldn´t be on your prefabs it doesnt make sense
you need that LevelManager one time only in your scene
yeah but if i dont apply it to the other scripts it will only spawn one level, because the next level needs to create another level at a specific distance away from the level it spawned from
how do I move my character towards the direction im facing
transform.forward is the direction you want
2d or 3d? Physics or no physics?
3d
physics
what if I want to move right while in the direction im facing
Rigid body add force direction multiplied by some scalar value
i gotta hop off cause I need to get sleep, but I'll be back on at probably 2 pm PST, I'm still confused on a bit of stuff, but thank you for all of your help
and thanks everyone else for their help
I progressed and actually learned a lot from this
you can move wherever you want, you simply need to use your transforms vector instead world space, transform.forward and transform.right for example
alright thanks
When I'm using Instantiate do the components sometimes not exist until a moment after the Instantiate method is used?
I'm getting a weird NPE which sometimes happens and sometimes doesn't happen relating to a component on an instantiated object (the component is already present on the prefab), even though the object is definitely instantiated before the component is retrieved and checked
Oh yeah NRE sorry
do you have some code to share, what you are describing should not be possible actually
Ah never mind, turns out I forgot a check to ensure the code should be executed (and when that check is false a different object is instantiated, not the one with the component)
so i want to calculate the shortest distance between one point to another. The problem is that these points are located in a maze with several paths. Every single path in the maze pre calculates how long it is. Im thinking that i should calculate every single possible path between one point to another, and then grab the path with the shortest distance. In order to calculate every possible path, I am thinking that i choose a direction, go down it, and then go down every path at the end of that path, avoiding duplicates. If i keep doing this, eventually i will reach the goal (its a pacman style maze, no dead ends). What would be the best way to do this? This feels a little above my scope.
Navmesh probably
2d game, dont believe that functions unfortunately
This is just basic pathfinding. There are literally thousands of resources for this. Google for "Unity 2d pathfinding"
yeah there is no 2d navmesh built in, and all of the extensions would require completely reworking the foundation ive set up
https://dev.to/christinec_dev/i-made-a-simple-2d-pathfinding-navigation-tool-for-unity-j9k
ill just use this then and start fron scratch i guess
There is a GitHub for a 2D navmesh, it works the same as the the built in one aside from the setup to mark things as obstacles in 2D.
I was just recommended by the formatter to simplify values[values.Length - 1] to values[^1], introducing me to the "index operator," where the number is the distance from the length of the array so, index 8 in a length 10 array is ^2 for example.
Seems simple enough, but are there other places where this operator is used like this?
probably anything that can use an index
just means the index counted from end
Interesting, thanks
there is also .. , this page has more
Oooh
I also found this cool example from the doc page for ^
string[] lastTwo = words[^2..^0];
yaa there is a bit you can do, but I think most of this is c# > 8
so if you're working with older unity or making code/assets compatible with older unity versions it wouldn't work
I see, thankfully I'm on 6.3 so I'm good on that front 😎
does anybody knows how can I get rid of these suggestions. I know these are usefull but currently I'm learning Unity and I don't need them. How can I turn them OFF?
and I'm using VS code
Bro i've been coding for like 5 years without them you can totally hide them if you want to
let me look it up for u
You can hide them but why would you ? its useful info..
It's a preference thing.
well okay people may want to hide them, I allow that 😄
Go to vs code settings and search "codelens"
I've always had it disabled and haven't had an issue
yes I know these are useful but currently I don't need then, I'm currently learning Unity C# and these are just bothering me. I'll enable them when once I'm ready
honestly I don't remember a sinlge time where the amount of references helped me, unless it's 0 which means I have forgot something
Personally I just see it as a lot of visual noise, and makes it more cumbersome to go up and down the code quickly.
probably more useful if you have lots of public methods / cross-script referencing
or a monolith
thanks problem solved
You can always just right click to see references if it's needed
doesnt seem to work on those two for me
Do you mean the codelens setting isn't working for you?
I mean... right, I mean I failed to find one for this
those I found and where is the other
I see
you can disable codelens altogether or you can disable specific extensions from providing codelens info
the ones you're still seeing are from unity's extension, you've only disabled the c# codelens
unity's codelens can be configured from this, which you can find by searching codelens and selecting unity in the extensions dropdown
you could also disable codelens altogether if you'd like, it's Editor: Code Lens
now my code looks so lonely 😢
Reverse it
Hey, why does this code not set the TileTypefield in my Tile script to the value corresponding to the pixelColor key picked from the dictionary please ? all the tiles are set to EN_TileType.None 🤔
Did you mean to check if the new type is not NONE?
Your code currently checks if the current type is NONE and does nothing in that case
Yes, because those are empty spots, so I don't have a Tile spawned there hence I can't set the TileType field as the gameObject isn't spawned there
but if all of your tiles start out with a type of NONE, then the set accessor of TileType will do nothing
How are you planning to set the initial type of the tile?
why is that ?
oh god, you're still basing it on colors?
eh, that's not a major problem
That's what I'm trying to do from Line 78 to Line 81, like I spawn a tile (if it's not a transparent pixel) then assign to it the right enum type depending on the color key
yes
just feels like quite a yikes that would easily lead to desyncs and bugs, due to your changes not being easily immediately applied
just drawing with tiles in unity would be more configurable and easier to manage, no?
Yes but the initial value of tileType is EN_TileType.NONE. And the setter says that if the tileType is EN_TileType.NONE then do nothing. So nothing happens.
But in the Setter for the property you're telling it to do nothing if it's already set to None
so I should remove that if statement ?
Depends on what you're trying to do. Surely you've placed it there in the first place for some purpose.
What is the meaning of the NONE tile type?
It appears to have two meanings right now:
- A tile that hasn't been set yet
- A tile that cannot ever be set, because it's an empty space in the grid
please do not crosspost. that is definitely not a code question
ok
this would be an #🔀┃art-asset-workflow question
why are you now going from image to tiles? the whole point of the discussion the other day was to remove the image step entirely and build your mock up of your map using tiles because you can just embed the relevant data directly into the tiles so you don't have to rely on images you've created externally to create your map design
i see
it does both
that workflow sounds significantly nicer
notably, you can create your own tile classes, which lets you store whatever data you want in them
this also completely removes the problem of having "uninitialized tiles"
and other weird in-between states
When you talked about tilemaps and having data embedded in it, I thought you literally had data embedded in the tilemap but in your explaination it's a class called "Tile", so it's what I have currently, just instead of using a tilemap to retrieve the data I use an image
that just.. defeats the purpose
I thought you literally had data embedded in the tilemap
that is exactly what i meant. like i told you, you can inherit from TileBase to create your own tiles that have whatever data you want on them and use those tiles to literally draw your map with on a tilemap
you can cut the image, with its lack of metadata and in-editor modification, completely out of the equation
you'd also be able to use the Tilemap system to position, query, and display the tiles
but uninitialized tiles are there only for a single step in the code (i.e when the tile gets spawned) then it's being attributed a value other than NONE 🤔
Yes, and you code says to not change the tile type if the current type is NONE
So nothing happens
what's tileType set to in tilePrefab
my point here, though, is that it's icky to have these "invalid states" in the first place
thanks, it fixed the issue 👍
depends on the retrieved pixel color from the image, tileType gets attributed the right enum value
that was not Chris's question
the question was what the default value of tileType was
(and since the default value was clearly NONE, your code didn't work)
this is incorrect
but, again, I must reiterate:
- you have two incompatible meanings for
NONEhere, which is already a major problem:- a tile that doesn't exist (somehow?)
- a tile that you haven't initialized yet
- this entire scheme doesn't make sense; just use tilemaps
you're setting to the instantiated Tiles, i asked about the tilePrefab
Oh yeah, by default all spawned prefabs get attributed NONE by default, then I switch it to the right enum just after
with this setter?
which doesn't do anything if it's currently NONE
... man, please just share code properly in the future
Yeah I removed that if statement as yeah it didn't make sense and now it works
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
i believe ive told you this many times before
the code is this now :
//Tile.cs
using System.Collections.Generic;
using _Game.Scripts.Enums;
using Sirenix.OdinInspector;
using UnityEngine;
public class Tile : SerializedMonoBehaviour
{
[SerializeField]
private Dictionary<EN_Direction, Tile> neighbours = new();
[SerializeField]
private EN_TileType tileType;
public EN_TileType TileType {
get => tileType;
set => tileType = value;
}
}
-# why even have the manual accessors lol
the not initiliazed part is temporary, in the sense that it's the case only when I spawn the prefab then the next instruction I set it. Why I still have None, is because I need it in the 2D grid that would hold the data itself about the board as I need it to attribute neighbours in my Tile.cs class, so seeing that the tile next to me is NONE would tell me that it's a transparent pixel, so I can't use it.
true, go for an auto-property ?
sure
but really, stop relying on images and pixels
it's such a fragile system
you're duplicating data in the code you showed
alright I will try to do the tilemap thing but I have no clue how
"single source of truth" is a good rule of thumb for a reason
boxfriend gave you a pretty good explanation last time, but you seem to have thrown that out the window and made your own assumptions
How stupid am I for trying to make a movement shooter while being absolutely terrible at physics
do you have a question
those are kinda unrelated
well
i wouldnt say they are completely unrelated
physics is far from the most important aspect
its not important but a lot of good controllers do custom physics for certain aspects
so theres an element to it
There is alot of physics in momentum forces n stuff
i just dont see how this is important to this channel or what your question is Zone.
So true kuzmo I am so humbly sorry for dare speaking in your code beginner channel about my challenges with trying to make a physics based system while being bad at physics
if you focus on those, sure. but on an overview, on a broad topic? imo, not that necessary to have going in. very useful, but not absolutely crucial. you can learn it along the way anyways, like everything else
what
this is a help channel, if you want help you have to actually ask a question
mate, this is a space for discussion and help, not for ranting
if you need help with something, you're free to ask, but we aren't psychic, we won't know until you ask lol
people are really desperate for a gen chat here fr
Hi guys i am new
not sure where to ask for this, but I can't find reference for the List type. The most helpful thing I could find was this forum topic which is itself now defunct. Is the scripting API reference for List accessible somewhere?
List isn't something from unity, you won't find unity docs for it
Google for "C# list". It's not a Unity concept.
ah ok, thanks
you can hover over types in you ide to see what namespace they're from. anything under System is a c# thing, anything under Unity/UnityEngine/UnityEditor is a unity thing
Also there's a direct link to the C# List documentation in the thread in the screenshot
the thread doesn't even open for me, though maybe thats on my end
oh I see the discussions is the new forums, I saw it didnt load and vaguely remembered an article about the forums shutting down so I thought it was defunct
like mentioned above only some things are provided by unity the rest of it is part of the C#/.net standard library
I have no idea why the gui of the serialized lists in every object are behaving like this, but sometimes randomly i get about 50 unity errors that a bunch of code outside of my scripts, like the actual engine code, is causing errors
not even during runtime either
you need to update to a newer patch. that bug was fixed a couple months ago
do i have to install a new version of unity?
that is how updating to a new editor version works, yes. but you don't need a completely different version, just the same version with a newer patch
alright
Hi yall, someone knows how can i get a bool from another script file, like i have a bool in the player script file and i have to get it in the wall script file too
Choose the best way to reference other variables.
Thx
i have been giving particle systems a try but, I can't seem to be able to get the hang of it. Any tips?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.

