#💻┃code-beginner
1 messages · Page 540 of 1
I tried to "just add it" but it gave me an error
a powerful website for storing and sharing text and code snippets. completely free and open source.
so I want to reference the player wall touch code to the Player's code
what was the error
reference ambiguity
of which ?
Be more clear
you have to show the full error
Show the actual error. The console at least, or paste the error
It is a good practice to always include the error if you received it in the course of getting help. It's hard to remember sometimes, I forget myself, but if we hold each other to this expectation, we will get in the habit of doing it automatically.
we can't really help you if you're going to dripfeed us information
I am having a brain fart. When we are talking radians in computers, do we include pi when we express an angle as a floating point number?
no, that's not how radians work
1 radian is not some specific fraction of pi, it's 2pi radians that completes a full turn
2pi radians is 1 turn
right. So when I enter sin(1.0) the answer should be 0 because that's the y value on the unit circle
I think I did gave all the info but nevermind lol
when we express an angle as a floating point number?
what do you mean by this?
it's always a floating point number
i'm just gonna skip this part
you barely gave us any context. you didn't tell us what the problem was, or what error you're getting right now
wouldnt it be easier to just tell us the exact error?
no, it's gonna be somewhere around like, 0.7
π radians is 180°, so 1 radian is gonna be a little less than 60°
that might be easier to visualize
I wanted to implement the wall check, I followed a tutorial but I did a different code, now I cannot implement it since it gave me error/ the code just doesn't work
ok... are you gonna tell us the specific error, or how exactly the code doesn't work?
Copy paste the error you are getting. There is a ton of information in the error stack trace you are not telling us.
or how exactly your code differs?
at first it gave me an error like reference ambiguity then I tried to match my code to his, it doesn't give me an error but the code just won't work
give us a screenshot of the error
Not helpful
stop saying "an error" and "doesn't work"
those are not helpful pieces of information
okay, we can forget this
Done!
give the exact error, and if you can't, show it
explain how exactly the code doesn't work
you still need to understand these key points of asking people for help
i'll ask again if something comes up with more detail
please do keep this in mind for the future (and not just for this server/topic)
i have a collectable item (just makes the ui number go up when collected) but i dont know how to get it to transfer across scenes
the number just resets when i enter a new scene
make it a DDOL and singleton , easiest way
SO are also viable option
i have no idea what that means lol
but ty! ill look it up
but you still need a holder for SO
ty!
Heya, im making an AI code and I was going through a tutorial, though it was quite old it was helpful in making a random walking AI, however im having difficulty making it switch it's state into either chasing or attacking, is this a raycast problem or it is a problem with "whatIsPlayer" and how AI doesn't detect the whatIsPlayer layer, at least that's what I think? The code for the enemy is below along with some screenshots, if anybody knows how to modernise this code or fix it that would be really helpful!
(its to big to put here lol)
(movement script is the player)
📃 Large Code Blocks
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Thank you!
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Should be all on here
(ignoring the using unityengine.AI, etc.. stuff)
and you're saying the raycast doesn't work ?
thats why we debug 🙂
for example you can also change the colors of the gizmos based on your bools
you should have the "what is player" layermask on the player for the checksphere to find it
yeah iv got that as a layermask
are the bools on , did you look in the inspector?
CheckSphere sucks because it doesnt return you the collider so its hard to debug whats hitting if anything at all
consider using 1 overlapsphere
Iv got one for sight one for attacking
yes can see that lol
and all im getting is there are 2 audio listeners in the scene
in the console
"There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene."
remove one
thats not related rn
so did you check the two bools in the inspector? what are the values
so the booleans are not true?
put logs in the methods to see if they ever get hit
overlapsphere is neat because it gives the array of colliders which is very useful for debugging
where would i see those?
the what bools? in the inspector, they are public
can you show both the enemy and the player objects inspector, dont crop
cant see the inspector
show player inspector
i added some print statements to print playerinattackrange and playerinsightrange and they arnt printing anything so
okay . lets see the player also
why cant i say k lol
alr uhh here
iv tried setting the include layers to whatisplayer but that doesnt work
scroll up
yeah i mean so I can see the object name and all its properties
there you go
player is in Default
you are not using the layermask
also the navmesh surface doesn't go on the player lol it should be on a static object
that is a tag
I had it scrolled the whole time
thank you
lemmie change it and see if thats a fix
wait the Fix is the Layer being set to Default and not What is player, just to be clear lol
it works so all good
also consider using a overlapsphere so you can return the colliders and find the player and remove that find method
if you use anything that returns more than 1 collider , use the nonalloc version
allocating a new array each time can get expensive
is it working ?
yup
actually while im here how would i send something to the player so they open a UI and delete themselves
if you plan on interacting with the player and its componens consider using the collider raycast/overlap
I never used that before, I probably should haha 😅
yeah In the beginning i never did but after profiling I realized it was creating so much garbage and some times even a 3 Length array is plenty if you're just doing grounding. and you save shit ton of allocating
probably a good idea but honestly all i need it to do is just delete the player and open a UI so i dont think it would be difficult
We asked you to share your code and/or give a proper description of the issue. You have done neither. If you want to be helped you have to give context to the people that try to help you, or we have to resort to all kinds of guess work, which includes just telling you to add it because we have no clue why you don't just do that
well i say think nothing is easy lol
its not easy because there are so many ways to do something
sounds right
I am using the 2D version (alloc) right now for my custom AI FOV system and it can have many targets. so I will probably switch to this method
you can profile it you will notice a pretty noticeable difference
especially if its called in Update. Imaging creating a new array each frame, yeah not a good time for GC
yes mine is called in update 😅
I should profile my project just to see what needs to be optimized
Layers do help at least filtering much of the colliders but still
the unity profiling tools are pretty good tbh
you can get pretty granular info (its a rabbit hole)
I have not used them before, so it should be an adventure trying to use it
yeah start simple, heirarchy mode. Sort by GC or .ms you will see whats mostly causing hog. Ignore EditorLoop. ofc profiling is best done on a separate instance (executable)
I will definitely check it out
their new video is pretty good too as a walkthrough of all the tooling
https://youtu.be/xjsqv8nj0cw
sweet thanks
my game seems to be running at just below 4000 FPS, but I do see spikes in GC when the AI "sees" a player which I thought I was using the overlapsphere method but I just double checked and I'm using overlapcircleall.
It does say in the docs that it does allocate memory, I'm not entirely sure if there is any method that doesn't (for overlapcircle)
also did you turn on deep profiling, it probably isnt a big deal with 1 enemy but multiply that by how many enemies you will spawn / have running at once
Hello, I'm trying to call a public void from one script to an other , but it don't work because the script that try to call the void is actually in a static class, and the void isn't static, so I have an error.
I tried to fixed the error by making my void static but it didn't work really well because , the UI that I'm trying to enable or disable in that script aren't static, and I can't set them as "static" because they won't appear in the Inspector anymore and because I already use them as non-static in other part of my script, so I wonder: Is their a way to call a void that's not static, from an other code that's in a static class ?
here's the part where I reference the script containing the void I want to call :
Myplayer = GameObject.Find("MainCharacter"); fpsController=Myplayer.GetComponent<FPSController>();
here's the part where I call the void :
if(MyLivingState == "0" && MyPreviousLivingState == "1")
{
FPSController.Died();
}
and here's the void that I'm trying to call:
public void DiedUI()
{
PlayerUI.gameObject.SetActive(false);
LeaderBoard.gameObject.SetActive(false);
DeathUI.gameObject.SetActive(true);
}
Why is it static?
Perhaps you want a singleton instance instead?
oh my, I turned on deep profiling and now it says it is 200fps with huge spikes in GC when looking at multiple enemies and "other" which I am unfamiliar with
Ehh, forget the first question, but regardless you probably want to implement some singleton pattern
Even then, your static class can probably be non-static
@warm raptor
are you using a cached array for the overlapcircle?
can't you change it for a non allocating version?
yes which I will do
It's static because it's the script that handle my websocket connection with my vps
4000fps? how does that even work
that is what it said with deep profiling turned off
Well look into singletons. It applies to your issue (and maybe the static class if you want)
Generally I advice you avoid big static classes unless they are purely utilities without states
The biggest reason to avoid this and to use singletons is because you can properly manage a single instance and it makes it testable
also keep in mind the editor and all the inspector windows have their own overhead
unity 6 made some massive fps improvements. this is normal now for minimal scenes
ok, thanks for your help ! I'm pretty sure I'll have to use a static class for my websocket. By the way, I've never heard of singletons, so I'll look into it!
Same as a static class, but instead of making everything static you define a single static variable that points to the instance to use. Check the article I linked for more info.
It goes further than this, because there are frameworks and libraries that work with singletons and dependency injection. This is just a basic solution
right but, do any screens even support that high of an fps
or is it just reporting the nominal fps, regardless of hardware
like, just processing as fast as it can
What’s the difference between local and global?
yes i believe its irrespective to hardware
Like world coordinates
World the axis are always in the same fixed direction
Local is relative to the gameobject rotation
Oh ok that makes sense!
local coords are based relative to the object's (perspective: rotation). world coords are relative to the world's origin: 0, 0, 0 . . .
local position/rotation is relative to it's parent. world position/rotation is relative to the world
ah, yeah. can't forget about the parent . . .
And it's the same with tools, you can rotate globally or locally depending of what you want to achieve (do i want to rotate the weapon locally (turning on hand) et rotate it globally (making my weapon point the sky))
It's the reference point
ah yup, also the nonalloc version of overlapcircle works wonders for larger arrays, I apprieciate it
i'd only use non-alloc versions anyway . . .
I never used it properly before, I believe I saw it and tried to use it then failed
but it works well
generally, you have an idea of how many items a collection will have, even if it's an estimate . . .
plus, with testing, you can pinpoint if a more accurate number is needed . . .
i need help, i keep getting errors when making a project???
this is a coding channel #💻┃unity-talk
mb bro😇🙏
Is there a cleaner way to write this code?
{
if (GameToPlay == 1)
{
}
if (GameToPlay == 2)
{
}
if (GameToPlay == 3)
{
}
if (GameToPlay == 4)
{
}
if (GameToPlay == 5)
{
}
}```
You could use a switch statement.
It sounds like you've put five different games into one component
also use enums
Perhaps each game should be its own component.
But if GameToPlay is really just "which round are we on?", then that's a different story
maybe SO too?
I made it that the game that is played has a code as an int assigned to it, helps me to organize it better haha
Explain what's going to happen in this function
public void PlayCurrentRound(GameToPlay) {
GameToPlayArray[GameToPlay] // Do something
}
Before this function is a function that randomly selects a game out of a list of possible games, so each new Round there cannot be any duplicate games after 5 Rounds and all Games are played once. The GameToPlay variable simply stores an int to link to a minigame, which means that GameToPlay = 1 would mean the minigame "tag" is played. So if GameToPlay comes out to be 1, all the code in the if statement runs the code used for "tag". But i know that its not a very clean way of coding but since im a beginner this is what worked best but it gets complicated quickly.
Thank you!
shuffle a list of games and loop through them, no need to pass indices around
if you're going to use integers at very least you should use enums so you at least know what the hell that number means right away, but yeah the solution Steve sent is probably easiest
yeah -- if you have a collection of games that are all used in the same way, put them in array or list
You should only have to write code to handle different kinds of things
also if you shuffle the list instead of randomly choosing one each time, you won't have issues with duplicates
indeed. consider the Fisher-Yates shuffle (I don't think List comes with a Shuffle method)
isnt list just Array with benefits?
It's quite simple.
public static void Shuffle<T>(this List<T> list)
{
int index = list.Count - 1;
while (index >= 0)
{
int i = Random.Range(0, index + 1);
if (index != i) (list[index], list[i]) = (list[i], list[index]);
--index;
}
}
look at me and my mildly clever use of tuples
yeah unfortunately c# doesn't have a built in shuffle method until .net 8, and it's on the Random class
You pick a random pair of items and swap them, narrowing the range by one item each time until you're done
It's equivalent to randomly drawing items from the list without replacement and putting them into a second list
instead of putting the items in a second list, you just stick them at the end
also you could take that a step further and use IList<T> instead of just List<T> and you can support arrays with that extension method too. this was my extension method for it:
public static void Shuffle<T> (this IList<T> collection)
{
for (var i = collection.Count - 1; i >= 0; i--)
{
var index = UnityEngine.Random.Range(0, i);
(collection[i], collection[index]) = (collection[index], collection[i]);
}
}
ah, if you haven't seen the this keyword used on a parameter before, this is an extension method
Extension methods let you define new methods to call on existing types
public static class ListExtensionMethods
{
public static void Shuffle<T>(this List<T> list)
{
int index = list.Count - 1;
while (index >= 0)
{
int i = Random.Range(0, index + 1);
if (index != i) (list[index], list[i]) = (list[i], list[index]);
--index;
}
}
}
a more complete example
and yeah -- go with IList to let this work on other kinds of data structures
List is a very specific type. IList lets you use anything that implements that interface.
(extension properties when)
I did share my code
It's here
...so are you still stuck on the issue or not
Still
so are you gonna tell us what the issue is
But it's fine, I'm just gonna skip it
How should I describe the issue?
then you're never gonna solve it lol
I know, maybe I'll take a look to another tutorial
instead of saying there's an issue, provide details on what the issue is
if there's an error, show us the error and where it's coming from
if there's unexpected behavior, tell us what the expected behavior is and what the actual behavior is
Hey, just wondering, surely there's a better way to write my if statement without having 4 or 5 && conditions in a row right? I've had a quick look but couldn't really find much. Any help would be appreciated, thanks is advance
Most likely. But without seeing the details of your code it's hard to say.
so I am trying to implement this. the thing is that mine doesn't work, tried to change stuff with no error or warning but still doesn't work
How to add a jump action for a platformer controller and management movement animations while in the air. This is part of my Unity 2022 Platformer Crash course.
Reference Project Patreon Download ➣ https://www.patreon.com/posts/2d-platformer-73894085
2D Crash Course Platformer Tutorial Playlist ➣ https://www.youtube.com/playlist?list=PLyH-qXFkN...
first time trying to code haah i tried making an enemy that shoots at you but...
You can always create a few local variables.
bool playerValid == player && player.alive == true;
bool enemyValid == enemy && enemy.health > 0 && !enemy.stunned;
if (playerValid && enemyValid) {
// ...
}
Ahh okay that makes sense
I'll just send my code quick if that's all good
Not sure how to do the whole code in Discord thing so will send it like this for now
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Thanks mate
but yes break that up into individual lines
you probably don't need all the parens either
My bad, I didn't see it
Hey, when I am creating a new volume profile via editor script, do I need to recompile scripts to be able to access them?
Logging asset gives me null in this case https://pastebin.com/LhYXWuv0
you should not be doing FindGameObjectsWithTag in Update
and this is the code https://paste.myst.rs/2ku2dys5
a powerful website for storing and sharing text and code snippets. completely free and open source.
Also replacing those FindWithTags calls with using your own Lists or HashSets to keep track of enemies and bullets would both clean up the code and make things more efficient.
Perfect, thanks for help
Yeah there are just so many chat so it gets buried
@stiff pollen are you going to tell us what the issue is
- the player could just expose a state instead of having to go through the animator
- why are you checking for a max of 2 bullets in the scene?
- what's with the
Random.Range(..) == 0?
yeah, the random.range part has confused me too
What do you mean by exposing a state? I don't want there to be more than 3 bullets being fired at the player at a time. That's how I'm doing rng but I'm guessing there's a better way?
all thats going to do is make it random whether the enemies shoot, but written like that, the chance of them shooting will go down the more enemies you have. 1 enemy and its something like 1/20 chance to shoot. 2 enemies is a 1/40 chance of shooting. Thats even if you reach that condition in the first place
- the player should keep track of its state directly, rather than going through the animator alone. you can expose a public property to let other components access that state
Yeah let's just forget this, cause that's all I can say, it doesn't work I don't know why. Doesn't work means just character still moving and stuck to the wall while the code prevent that
Oh yeah I want the enemies to have a higher chance to shoot when there's less of them, I'm doing like a Space Invaders game
just character still moving and stuck to the wall
this is literally all you had to say
Okay so when the animation changes, I change some sort of player state variable?
what's the idea of the player.GetComponent<Animator>().GetCurrentAnimatorClipInfo(0)[0].clip.name condition? I'm reading that as you wanting to check if the player is in a death animation (presumably because you dont want to shoot the player that is already dead
you would change the state, and that tells the animator to change. the player state is the source of truth
Umm okay, so the conditions in the animator would be like the player states?
yeah
the Random.Range(..) == 0 wouldn't work because you aren't factoring framerate into that
Yeah I'm just using that to get say don't shoot at the player when they're in the death animation
hey mates, where do I ask questions about the editor / IDE itself?
I'm losing it rn, not gonna lie
#💻┃unity-talk most likely... #🔎┃find-a-channel
Thanks btw, been here like 10 mins and learning so much already
thank you @wintry quarry
@stiff pollen i think this condition is reversed?
private Vector2 wallCheckDirection => gameObject.transform.localScale.x > 0 ? Vector2.left : Vector2.right;
if x > 1, it's facing right, so it should check for a wall to the right, no?
if the objects localScale of the X is Positive
@toxic tiger you'll most likely want to do something like Random.value / enemyCount * Time.deltaTime > chance with another factor to scale it properly
then ya,, Greater than that should be left..
wdym
no wait.. greater than X is right
Thanks a lot 🙏
-1, 0, 1, 2 ---> right right?
i mean, it depends on the initial direction. the initial direction here is rightwards
1 is rightwards, -1 is leftwards
so x > 0 should involve a check towards the right
the vector here is being used in a cast
ya, all comes down to orientation, and scale i guess
pretty simple to debug.. w/ some empty gameobjects
also debug the values ur receiving in script make sure that matches ur expectations
Hello. I am trying to make a endless surfer game as practice (kinda like subway surfers). However, I am not sure how to implement rules to limit how the obstacles are being spawned. I am currently spawning them along with the tiles, by using random to decide which lane (left, mid and right) to spawn. I am unable to keep track of them and hence can not use any rule to limit them. Also, I think the way I am spawning them is not very optimal as well. I would be grateful if anyone can provide me some advices. Thanks!
My code for tiles generation
https://hastebin.com/share/wohohabipu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I guess, it should be? I don't really know, I was following a tutorial, his explanation is that if it's greater then zero it should check both ways
@toxic tiger (to clarify, by "properly" i mean "in way that makes sense to you". chance here would be seconds per enemy, i think?)
well, either way, that code isn't doing what it's supposed to
so what should I change?
swap Vector2.left and Vector2.right
bump
make sure you've saved everything and let unity recompile
I know I'm late on this, but you could lay things like a little bit like this @toxic tiger it becomes a lot longer than what youve got, but some tricks here can make it a little more easier to read
int enemyBulletAmount => GameObject.FindGameObjectsWithTag("EnemyBullet").Length;
bool inRange => Mathf.Abs(transform.position.x - player.transform.position.x) < shootPositionRange;
bool isDead; //probably best to set this as true when the player dies, rather than rely on checking an animation
void Update()
{
if(!isDead) //the player is not currently dead
{
EnemyShootLogic();
}
}
void EnemyShootLogic(){
if(enemyBulletAmount > 3) {
return; //dont continue the rest of the function, too many bullets
}
if(!inRange) {
return; //dont continue the rest of the function, player isnt in range
}
if(some probability check here, like your random.range == 0.0) {
return; //dont continue the rest of the function
}
//perform the shooting code now
//once you reach this line, it means all your previous conditions allow the enemy to fire
}
Hey so I just started the junior programmer course on the unity website and I did everything right but when I open the prototype 1 scene in the assets folder the mountain and road are pink? How would I fix this?
Basically - as with everything in programming - you simplify through abstraction
shader error, if you are in URP you can use the converter to convert materials
not a coding issue, #💻┃unity-talk (i think #archived-shaders?) make sure you have the right pipeline and materials
in general you should be using the exact same UNity version and project template as the tutorial to avoid issues like this
I poked at this problem a few months ago
Okay thank you I will do that!
One option is to just create valid chunks of obstacles by hand and then spawn them in sequence. That way, it's impossible to create an unwinnable track.
still doesn't work
here's the update codes https://paste.myst.rs/trfavpj7
a powerful website for storing and sharing text and code snippets. completely free and open source.
they are most likely using URP instead of BIRP as it looks like they are using unity 6 which default template is URP
right exactly - they're not using the same Unityversion as the tutorial
its useful to have those if (blah) { return; } lines when you want to quit the function. Is the player out of range of the enemy? No point checking any other condition after, therefore you return
Perfect that makes senes, thanks. Struggling to visualise what I would do, maybe due to information overload loll, but once I try it I'll figure it out
alright, can you get more detailed iwth what exactly the issue is
You can also create groups of obstacles that are then processed to make them possible -- e.g. a wall that you randomly punch a hole in.
This doesn't require communication from group-to-group. That's where the real complexity comes in.
if there's unexpected behavior, tell us what the expected behavior is and what the actual behavior is
Ahh mate thank you so much, really appreciated. This is exactly what I needed. Already started some similar things but not like this, really wanna try keep my code clean so thank you
do you mean instead of spawning obstacles and tiles separately, create prefab that already include the obstacles?
hey yall, i've got a theory question
using the unity animator as a state machine (for code) - yay or nay?
watched my teacher do it and it just looks way too complicated for implementing a state machine
oh so instead of generating them 1 by 1, spawn them group by group, where these groups of obstacles prefabs are created manually?
nay
might as well learn other methods imo..
even a simple enum statemachine. but i like stateless statemachines
yeah it just looks really unwieldy, by the way how my teacher did it at least
yea.. teacher sounds sus
unless he just showcasing that the animator is basically a statemachine
he did mention that it basically is one, and then how to make it into one for code
Yeah. You can also do a little bit of automation within these prefabs.
Consider a prefab that has five solid walls. Each wall has a component on it that, in Awake, randomly deletes a piece of the wall.
As long as the walls are far enough apart, you now have a valid path.
If you put the walls too close together, you might create an unwinnable obstacle.
bro's teacher be like:
"simple"
yeahhh he's super weird in general tbh
average VRChat asset
that's the thing I don't know what's wrong, I was trying to make the character not stuck on the wall with those code, it doesn't give me an error but it just doesn't work, the character still get stuck and I get those codes from here https://youtu.be/qcRRYeGMZ68?si=r38gXaSCVjI5kq0x&t=1499
How to add a jump action for a platformer controller and management movement animations while in the air. This is part of my Unity 2022 Platformer Crash course.
Reference Project Patreon Download ➣ https://www.patreon.com/posts/2d-platformer-73894085
2D Crash Course Platformer Tutorial Playlist ➣ https://www.youtube.com/playlist?list=PLyH-qXFkN...
legend of zelda topic came up and he said he hates it because of how feminine Link is
which is like
?? huh ??
Don't completely undertand the top two lines tho, would you be able to explain this '=>'
That's kinda a smart way of doing it. Instead of adding, we are simply deleting to make sure there's always a pathway for player to use. Thanks for the advice! I will give it a try
i do definitely want to use state machines as i really liked the idea from an old electronics lesson we had
they just seem fun to tinker around with
yup, the beginnings of ur AI journey
but seeing the mumbo jumbo my current teacher is propagating just stunlocked me
can't have Game AI w/o a statemachine of some sorts
ah, I was going to mention those. Its basically a shorthand way of writing this
int enemyBulletAmount
{
get {
return GameObject.FindGameObjectsWithTag("EnemyBullet").Length;
}
}```
And thats similar to if you were to write
int enemyBulletAmount;
void Update()
{
enemyBulletAmount = GameObject.FindGameObjectsWithTag("EnemyBullet").Length;
}```
another teacher i had did show how to do state machine in a way, which was super cool, with all the patrol, alert, chase states
dont get me wrong.. if ur dealing with a very small statemachine then yea, the animator can be handy..
just b/c its visual..
make every AI movement random
i think the statemachine he made is for loading screens too
All it means is any time something wants to get the value of enemyBulletAmount the => means the code will quickly "get" the value in that moment
lol.. AI Budget Edition
Thanks. So it's still getting it every frame even tho it's not in Update?
oh, ya thats a pretty normal use-case
if its just managing screens and stuf
ahh i see
it is in update, just indirectly
Your Turn -> Action -> Enemy Turn -> Action etc
That hints at the more "general" way to do this -- if you can detect whether or not a set of obstacles is valid, then you can just spawn random stuff and retry if you create an invalid track.
I haven't thought too hard about that yet.
That was my initial thoughts. That's why I want to keep track of where they spawn.
Alright, thank youuu
mine is going to be based off of percentages so its semi random, so it gives the illusion of higher "Intelligent" AI instead of 100% scripted movements if certain conditions are met
should be pretty interesting to do
alrighty thanks, i'll look over the lectures since there might be something good
Pretty much. All that happens here is Debug.Log wants to do is get the value of magicNumber to print it. The code will then go to magicNumber, and => basically goes and gets the value of 42. That is what Debug.Log will end up printing
int magicNumber => 42;
void Update()
{
Debug.Log(magicNumber);
}```
ya, sometimes the best AI results from out-of-the-box ideas like that..
the harder it is to figure out whats happening behind the scenes the more intelligent it appears
(it's called a property btw)
haha, years of programming and I always forget the name of things
yea.. codes is hard
I vote to call them "the word that is the name of the thing you put numbers inside"
Hmm okay so 42 is a variable here and not the actual number 42? Then the Debug.Log is just printing whatever is attached to that variable?
so.. something like weighted, randomness?
also giving the AI more capabilities closer to what the player can do like jumping, crouch jumping/crouching, strafing, obviously it will have to be toned down since it is a computer versus a human which could be impossible for the player to counter
pretty much..
float myValue = 40;
Debug.Log(myValue + 2) would also print 42
Cool thanks mate
ive always heard this..
"the opponents/enemies should be able to do pretty much anything the player can do"
not quite
thats more about telegraphing..
yes so to speak, as each action will have a certain percentage to get called, some will be higher, some will be lower giving the illusion of "intelligence"
a variable (or field, in this case) holds a value
=> for all intents basically is just the word get
magicNumber gets the value 42 or whatever happens to be after it
but a property is like a function, in the math sense
you call it to evaluate a new value
yea.. i gotta make me a weighted system like that
that just sounds like memory
@steep rose care to share a snippet or so of how ur doing it?
yeah, most games only make the AI walk on the ground making it pretty much useless they don't really do anything else, maybe a dodge once or twice
Okay I get it but not completely, imma have to mess around with it. Thank you
Okay makes sense, thank youuu
sure, I'm implementing the base systems right now such as a FOV system, Hearing system, pathfinding etc. before I make it do weighted randomness yet
oh and a scoring system
a variable is a box you put data in
a property is a function (well, 2) disguised as a variable
int TextureWidth, TextureHeight;
Vector2Int TextureDimensions => new(TextureWidth, TextureHeight);```Theres one way I use it, but there its more just out of laziness than me wanting to create the Vector2Int elsewhere
Okay that's really interesting actually, I'm sure I'll figure it out after using it a few times, thanks
an example might help
A property is a member that has field-like syntax, but that invokes methods when you access it.
facts.. good outlook to have.. the more u use something the easier it'll become..
u can read about stuff all day long. theres not quite an alternative than actually using it
Exactly mate, obviously the reading helps a lot but to truly understand it I need to use it
i recommend getting nice and cozy w/ the console..
debug and log all kinds of stuff.. know when and how errors/logs/etc occur
using System;
class Example {
static Random rand = new();
int field = rand.Next();
int prop => rand.Next();
int Method() { return rand.Next(); }
void Ex() {
Console.WriteLine("With field");
for (int i = 0; i < 5; i++) Console.WriteLine(field);
Console.WriteLine("With prop");
for (int i = 0; i < 5; i++) Console.WriteLine(prop);
Console.WriteLine("With method");
for (int i = 0; i < 5; i++) Console.WriteLine(Method());
}
static void Main(string[] args) { new Example().Ex(); }
}
```@toxic tiger try running that in an online c# compiler
(whoops, forgot about the static thing)
Yeah defo is very useful, need to use it even more tho. Just need more input of new information really before I start to build bad habits
if you have any questions or anything about sensory stuff give me an ask.. i worked on my system like this last year.. i'd be happy to help
This is what I have so far
Thanks mate I appreciate that a lot 🙏
Loll what am I even looking at?
If you're trying to show through example this is maybe a little too much for me to understand
try running it and just look at the output first
Yeah I have
(not in unity, try googling for online c# compilers)
so notice that with a field, it doesn't change
it actually holds the value from rand.Next()
but with the property and method, it changes each time, because rand.Next() is called again each time
Whats the short cut to open the project tab?
but the property is accessed like a field, rather than a method.
Ahh okay I get you, different outputs of same thing with field, property, method?
you should use google or the unity docs to answer questions like that
different behavior, specifically
Thanks!!
So obviously field stays the same, but are property and method doing the same thing or no?
Ok! I will do that next time!
good, we are not here just because you are lazy
The not-so-secret secret is that a property and a method are ultimately the same thing, just some syntax sugar.
they're doing the same thing in this case
but they're typically used differently
methods do things, they're verbs
properties are values, nouns
just that, instead of being a single value until you change it (like a field), a property gives an up-to-date value
Okay definitely understand more now, but as I said, to understand fully probably need to use it for myself
Thanks for all the help, defo learnt a lot
Sorry
bump
Are you sure the path is correct?
I do something very similar and it works fine
create asset, then immediately load an asset at its path
I mean unless I am blind, this should be fine:
AssetDatabase.CreateAsset(CreateInstance<VolumeProfile>(), Path.Combine(_sceneDir, $"{_sceneName}VolumeProfile.asset"));
var ass = AssetDatabase.LoadAssetAtPath<VolumeProfile>( Path.Combine(_sceneDir, $"{_sceneName}VolumeProfile.asset"));
Print out the path of the asset after you create it and compare it to the path you’re constructing
(you can ask the asset database what the path for an object is)
how would you go about doing that?
I see the GetAssetPath but it expects an id
It takes either an instanceID or a unity object
want to say that i just arrived at the part in my course that starts explaining coroutine!
neat (:
yeah, but how would I get either?
you already have a unity object!
I believe you can call this on the object you just passed to CreateAsset
oh 🤦♂️
I could be wrong about that, though. I just noticed I did something...pretty silly
sure, imma test it either way, doesn't hurt
var found = AssetDatabase.FindAssets("t:IconSet " + key, new string[] { BASE_PATH });
IconSet iconSet = CreateInstance<IconSet>();
if (found.Length == 0)
{
var set = CreateInstance<IconSet>();
AssetDatabase.CreateAsset(set, BASE_PATH + setName + "/" + key + ".asset");
found = AssetDatabase.FindAssets("t:IconSet " + key, new string[] { BASE_PATH });
}
iconSet = AssetDatabase.LoadAssetAtPath<IconSet>(AssetDatabase.GUIDToAssetPath(found[0]));
I believe I had to do this because the reference stored in set is not the same reference that you'd have gotten from LoadAssetAtPath
So that would imply you can't ask for the path of the object you passed to CreateAsset
yeah, that would make sense to me ig
I do have a function that would ask for the script compilation, I just find it odd that you'd need that after creating an asset
thought that save+reload would be enough
I'm busy adding a feature where my cursor changes when im in different states the states are decided by tags and layers I don't know whats wrong its not changing the cursor but i added debugs and its running but not changing
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you don't seem to have any code that ever activates the cursor objects, only deactivates them.
what do you mean how do i fix this
if you want to activate a GameObject, you need to actually write code that activates it
All I see are markerInstance?.SetActive(false);
(which btw is duplicated 5 times unnecessarily)
Share your code with paste sites so I can actually see line numbers
Yet again - read this #💻┃code-beginner message
the only thing SetMarkerType is doing right now is deactivating objects
SHouldn't you be *activating * the new cursor?
I would expect SetMarkerType to:
- Deactivate the old one
- Activate the new one
right now you're only doing the deactivate part.
if you post a code screenshot, you really should include the line numbers in the image
Or better yet - don't poost screenshots
any of those could be line 119
You've alraedy been shown this - please follow it
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
overcomplicated
line 106 is red
Also:
(type = currentCursor) this doesn't make sense and is going to assign the thing
There's no need to duplicate all this code
If you are getting an error, you should probably say what it is
what should I do
Accept that as cool as it would be, ESP does not actually exist, and we cannot read your mind to know what your error is
what should i change
What are you trying to do on that line
he told me that there is no lines that activates the cursor so i added one that activates it by copying the deactivation one and changing it to false to true and from != =
Keep it simple:
https://hatebin.com/mgyctzpsei
no you added like 25 lines
and duplicated the whole if statement and switch for some reason
it still doesn't work
Define "doesn't work"
Take some simple debugging steps here
add some logs
see what's happening
the cursor does not get assigned
start debugging your code to see why
Are you sure the code is even running
yeah
what makes you so sure
How do you know
i fixed it
Lmao
hey, I just did a full script compilation and reload and that didn't help, what am I missing here?
You must have the wrong path.
I am loading a different asset in almost the same way
yeah, here's the other thing I'm doing:
var so = CreateInstance($"{_sceneName}ConfigData");
var soPath = Path.Combine(_sceneDir, $"{_sceneName}ConfigData.asset");
AssetDatabase.CreateAsset(so, soPath);
var sm = AssetDatabase.LoadAssetAtPath<ConfigData>(Path.Combine(_sceneDir, $"{_sceneName}ConfigData.asset"));
got this done (ty!) but i have another problem with the collectable
it worked fine before but then i added a script to change scenes and now for some reason whenever i touch the collectable it also transfers me to the next scene
when its not supposed to
im not sure whats making it do that
using UnityEngine;
using UnityEngine.UI;
public class Collectable : MonoBehaviour
{
public Canvas canvas;
private TextMeshProUGUI scoreText;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
if (canvas == null)
{
Debug.Log("Could not find canvas");
return;
}
var child = canvas.transform.GetChild(0);
if (child == null)
{
Debug.Log("Could not find child transform");
return;
}
scoreText = child.GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
scoreText.text = "<sprite name=\"collectooble\"> 1";
Destroy(gameObject);
}
}
}
``` this the the code for the collectable
using UnityEngine.SceneManagement;
public class ToNextScene : MonoBehaviour {
private int nextSceneToLoad;
private void Start()
{
nextSceneToLoad = SceneManager.GetActiveScene().buildIndex + 1;
}
private void OnTriggerEnter2D(Collider2D collision)
{
SceneManager.LoadScene(nextSceneToLoad);
}
}``` and this is the code for the scene transfer
you sure you aren't just hitting the scene transfer thing as well?
private void OnTriggerEnter2D(Collider2D collision)
{
SceneManager.LoadScene(nextSceneToLoad);
}
This punts you to another scene if this function gets run, ever
It doesn't care what got hit
ohh
mightve accidentally added it to some random object
or set up layers incorrectly yeah
So, for example..what if the collectible hits the scene-change zone?
(I'm not sure what object ToNextScene is on)
If it's on the player, then touching any trigger collider will take you to another scene
its on the collider that needs to be touched to trigger a scene change
but the collectable and collider arent on top of eachother
to sanity check that you don't have extra scene-change components in your scene, search for this in the Hierarchy search box
t:tonextscene
This will show you every object with a ToNextScene component on it
ah it is on the character too right
the tutorial i watched said to put it on both the character and the collider
Perhaps it meant to have two different components?
One could look for the other and only do the scene change if that second component is found
That way, random stuff crashing into the trigger zone won't do anything
how would i go about doing that?
no prob!
I'm guessing it wound up being something like
void OnTriggerEnter2D(Collider2D other) {
if (other.TryGetComponent(out Player playerComponent)) {
// do the scene change
}
}
i just wasnt supposed to attach the script to the character
Ah, that works too :p
but now my collectables arent working so im trying to get that working again!! yay
This kind of thing would make sure that other objects can't set off the scene change
ah okayy
private void Update()
{
ai = gameObject.transform.GetComponent<zombieAI_1>();
}``` why is ai always returning null? getcomponent isnt working at all
For more context, im trying to access the zombieai script from the Ragdoll script
The names don't match
one is called Zombie AI_1 and one is called ZombieAI
That could be down to how Unity displays component names vs. the actual class name
getting a strange error trying to do a room transition
heres my code for the room move function
It's complaining about your method's parameter type
Look at the type you asked for in the method vs. the type Unity is trying to give it
Pretty straightforward - you have the wrong parameter type
https://paste.ofcode.org/TceFXeR6itqvqdyBW24XaA I have a script that is on different gameObjects a function should be deleting two buttons but it isnt and bec its on different gameObjects i have been told this is the problem how can i solve this so it deletes for all
a function
Which function?
should be deleting two buttons
Which buttons?
ShowCountryStats()
You should really avoid stuff like this:
GameObject buildImage = instantiatedButton.transform.GetChild(0).gameObject; GameObject buildText = instantiatedButton.transform.GetChild(1).gameObject; GameObject costText = instantiatedButton.transform.GetChild(2).gameObject; GameObject lvlText = instantiatedButton.transform.GetChild(4).gameObject;
whats the solution i have to get the children some way
Put a script on the thing you are instantiating
have that script manage all of its internal stuff
this script should not "reach inside" another object like this
This code should look something like:
BuildButton instantiatedButton = Instantiate(buildButtonPrefab, Spawn.transform.position, Quaternion.identity, Scroller.transform);
instantiatedButton.Initialize(BStats);```
Then have that script do all the initializing inside itself
see how much cleaner and more readable this is?
Anyway It's unclear where you are trying to "delete" buttons here
I don't see anything that looks like that
foreach (GameObject buildButton in buildButtonDelete)
{
Destroy(buildButton);
}
so you will need to be more specific about where your problem is
but i realized thats not effecient since there are different gameObjects
using the script
my question is how to delete all the buttons for all scripts
wydm? im new at this sorry
This message parameter has to be of type: Collider2D
The message will be ignored.
This will delete any objects you have previously instantiated from this particular script insteance
would it be the other that needs to be replaced?
Your function's parameter has to be of type Collider2D
are you calling ShowCountryStats multiple times on this same instance?
Yes
look at ythe parameter you have
and look at what it's asking for
what does that mean though
Look at the type of that parameter
i have collider2d there
yes that's wrong. Read the error
yes every time i click a state
i did i still dont get it
It means change the type to Collider2D
on trigger enter 2d...
no you don't actually
Have you changed it since your screenshot?
read your code closer, it does not say Collider2D
that's not what you had earlier
wb other?
what about it? That's just the name of the variable, it's fine
You could literally change that to "Skibidi" and nothing would change
lmfao
alr it worked wow
problem is it doesnt warp me to the gate
it warps me completely out of reach
player change is def the issue
dunno what values id have to put tho...
thank you for the help tho
Hey @swift crag, I am 99% sure that the path isn't wrong now, are you still sure that's it?
https://pastebin.com/i13XaPTw
Sorry for the @, it's been a while since you answered and I won't do it again.
rather than hardcoding numbers in the inspector why don'y you just make an empty GameObject specifying where youi want to move the player to?
No prob :p
i got an idea how about i delete all gameObjects in the scene with a certain Tag aka button tag
Maybe try loading a plain UnityEngine.Object instead of a VolumeProfile? That shouldn’t change anything…
Is it possible for an IDE to "unconfigure" itself? It seems like it no longer wants to work with my scripts in VS despite updating.
Weird.
sadly didn't work
Try using FindAssets to search for assets in that folder. Use an empty query for the first argument and put the directory path in place of BASE_PATH
I’m curious to see what falls out
im using a tut bc im clueless
i have one year left b4 i go into
college and id like to learn how code works
not very useful 💀
I don't see a function to convert gui to path
AssetDatabase.GUIDToAssetPath
but it logged 5 assets regardless, there should be 6
I see 6 things in this folder--
yeah
You could quickly check by opening the .meta file for the asset of interest and seeing if its GUID is in that list
nop
Interesting. Your asset does not exist in the eyes of the AssetDatabase
ButtonDelete.Add(GameObject.FindGameObjectsWithTag("BuildingButtonTab"));
This is not working even tho my object is a list for some reason
I'll try to do a full reload, including the compilation, and see if it finds that asset guid then :/
try reimporting the profile asset
gimme 5 min cuz that includes a bit of code refactoring
wym
right click on the asset in the Project window and click Reimport
I can't do that, everything is done via script
you are trying to add an array to alist it seems
I just want to see if anything changes when you do that
It sounds like something is in a Weird State (tm)
I mean look, I just did this:
https://pastebin.com/gmZQMDHh
If this is not enough, I genuinely don't know what is :/
Imma need a bit of time to test the reimporting stuff cuz I need to isolate the function for getting the asset
I'm currently trying to make my own AI random roaming script from scratch for a snowman npc in my game and it's not going well...
My basic idea was to invoke a method every 30 seconds that adds a slightly varying number to the current position and calls that the target position and reports the number in debug.log. The script then moves the npc to the target position. However this is not working correctly, as at the beginning of runtime when the method is first invoked, the script records the current position as "(0, 0)", when in reality the starting transform of the npc is more like (39 , -323). It does record a target position that is within (25, 25) and seemingly moves to that position, then when the method is invoked a second time the npc logs its correct transform and a target position within 25 units of the current position. However the npc never tries to move toward that second target position. Any help would be greatly appreciated.
public class SnowmanAI : MonoBehaviour
{
public Rigidbody rb;
public float roamingSpeed = 1f;
private Vector3 targetPos;
private Vector3 currentPos;
void Start()
{
Invoke("FindNextTargetCoordinate", 0f);
}
void Update()
{
currentPos = transform.position;
}
void FixedUpdate()
{
rb.AddForce((targetPos - currentPos) * roamingSpeed * Time.deltaTime);
}
void FindNextTargetCoordinate()
{
targetPos = new Vector3(currentPos.x + Random.Range(-25, 25), 0, currentPos.z + Random.Range(-25, 25));
Debug.Log("Current Coordinate: (" + currentPos.x + ", " + currentPos.z + ")" + "Target Coordinate: (" + targetPos.x + ", " + targetPos.z + ")");
Invoke("FindNextTargetCoordinate", 30f);
}
}
i kind of fixed the problem by putting GameObject[] buildButtonDelete = GameObject.FindGameObjectsWithTag("BuildingButtonTag"); foreach (GameObject button in buildButtonDelete) { Destroy(button); } at the start of the function
but a new problem appeared
wait i think i know a solution
hii sorry im back 
i cant figure out why this isnt working
it worked fine before
but now when i try to interact it just doesnt do anything
this is the code for it
Check if the code is running at all
you can log before and after the if statement in the trigger enter method
What is not working specifically? Just not being called, or...?
Also consider logging the thing you hit
how can i check that?
triggers aren't for UI..
you've already got a few log statements!
this is an object you pick up in the game
it is a little silly to directly talk to the text component on the HUD, though
it does a getcomponent for the TMP, assuming this component has been placed on UI
oh, perhaps not.. it's doing it on the canvas.. with a load of unnecessary code to get a child component
I'm a little stumped so if someone could help, that would be amazing. Thanks
sorry can you give me a TLDR ? this messes with my add lol
eg
whats happening vs what you expect to happen
no need to do that, I just waited for the execution of my regular scene creation to execute, ran the thing that gets and prints stuff and it printed everything correctly :/
[MenuItem("Assets/Test", false, -202)]
private static void Test()
{
// Assign the newly created profile to it
var assets = AssetDatabase.FindAssets("", new [] { "Assets/Scenes/Test8" });
foreach (var asse in assets) Debug.Log(asse);
}
npc incorrectly logs its starting transform as (0, 0), and the second time the "find target point" method is called, it logs its transform correctly but doesn't try to move to the target ppoint
Need help with this
I just want a snowman npc that roams around to random points
whic log is that, also you should not put Time.deltaTime inside AddForce
oh forgot about that
FindNextTarget is called before the first Update, so CurrentPos hasn't been updated
The first log is the first coordinate log, the following logs are the next couple times the method is invoked
oh ok thanks that's what I'm looking for
so I should just add a delay on the first invoke?
why do you even need that current pos in update?
just put the transform.position when you do the FindNextTarget
Using Invoke() is poor btw .. especially with a string to call it. It inevitably leads to problems which the IDE can't catch. If you really must use Invoke() don't use strings with it, use Invoke(nameof(FindNextTargetCoordinate));
or set the current pos before using it..
Idk lol oversight on my part ig
ok now ive got it working again but im not sure how to get the number to keep counting up
i have the singleton set up
but when i collect a thing in the next room it just overlaps the "1" again
int++
instead of counting up to 2
where do i put that?
when you collect
int myInt = 0
myInt++ is same as myInt += 1
ah ok tysm!!
ok so I made those changes and now the npc logs the correct starting transform, but it doesn't move toward the target position. I assume I just forgot how to make stuff move?
void FixedUpdate()
{
rb.AddForce((targetPos - currentPos) * roamingSpeed * Time.deltaTime);
}
shoot lemme remove the deltatime thing quick
- never use TIme.deltaTime in AddForce
- this is going to rocket the thing towards the target position
I know I forgor
why is that?
because you're adding a continuous force in FixedUpdate
it's going to accelerate constantly
like a rocket
lezgo it works after I removed time.deltatime
Hi, how do you set the profile of a volume with an editor script?
I tried the following:
// Store the path
var path = Path.Combine(_sceneDir, $"{_sceneName}VolumeProfile.asset");
// Create a new game object
GameObject go = new("GlobalVolume");
// Attach volume component to it
var vol = go.AddComponent<Volume>();
// Assign the newly created profile to it
var asset = AssetDatabase.LoadAssetAtPath<VolumeProfile>(path);
Debug.Log(asset);
vol.profile = asset;
And I do get the asset back as seen in the screenshot, but it doesn't get set in the inspector.
I have the roamingSpeed set to 1 so it doesn't go very fast
either way I'm happy that it works now, thank you guys for the help
yes but force causes acceleration
just gotta make the snowman griddy now 😤
it will continually accelerate
it's just a slow acceleration if the number is low
if you're happy, it's fine
is there a different way I should move the npc by the rigidbody?
There is no "way you should" do anything
it's your game
you can move it how you want
it depends on what your desired motion is like
well now that I think about it, it would make more sense if it were a constant speed/motion
would rb.velocity or rb.MovePosition do that?
sorry I should google that
Do you know what "velocity" means?
yes rate of motion in a certain direction
so if you want a constant rate of motion in a certain direction, it stands to reason you want to set the velocity, right?
Hey Fen, I managed to fix it.
Turns out that recompiling stuff was necessary afterall.
On top of that, we both missed the fact that, for some reason, you are not supposed to set the profile property of the volume but sharedProfile instead, awesome...
With all that, it works flawlessly now.
Thanks for helping along the way!
Oh, that would not help, yes.
profile is like material on a renderer
you get an instantiated copy
I don't see why recompiling would be needed to create and load a VolumeProfile, though. That type already exists
yeah, I am as surprised as you are
I tried calling the regular reload and that didn't help, I'll try once again for good measure:
private static void Reload()
{
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
Perhaps the new assets did not appear until the recompilation process finished
(since recompiling is triggered by importing new or modified code assets)
quite possibly
I mean it's one more reload, which is like 5-10 seconds so not a big deal, especially considering the fact you won't be doing this process to often
hello everybody , can anybody help me out with this error pls
Step 1: read the error message
yes but i don t have any alternate solution than this line of code
YOu're jumping to solutions
step 1 - read the error message
what does it say?
Right because you have this:
orientation.right * (Input.GetKey(Left) && Input.GetKey(Right))
Well there you go. You can't multiply a vector3 and a boolean
Input.GetKey returns a bool
bool && bool also gives you a bool
orientation.right is a Vector3
WHy are you trying to multiply a Vector3 by a bool?
what do you expect that to do?
i didnt know that it was a bool
My guess is you're actually looking for Input.GetAxis?
i.e. orientation.right * Input.GetAxis("Horizontal")?
think about it
GetKey merely tells you if a particular keyboard key is pressed
which is true or false
GetAxis gives you a numerical value between -1 and 1 for the given input axis.
i updated my code but it only counts up to 1 still, and just overlaps after
{
if (collision.gameObject.CompareTag("Player"))
{
// Increment the score
int myInt = 0;
scoreText.text = "<sprite name="collectooble"> " myInt++
Destroy(gameObject);
}
}
}
// Increment the score
int myInt = 0;```
The comment says "increment the score"
but that's not whjat this code is doing at all
this code is:
- declaring a brand new local variable called myInt
- incrementing that brand new local variable
no other code can see that brand new variable
and it will promptly disappear as soon as this method finishes executing
Also this line: scoreText.text = "<sprite name="collectooble"> " myInt++won't even compile as it's missing basic syntax elements such as a + between the string and the int variable as well as a semicolon
oh right i forgot that
do you know how i can fix that?
- don't make a brand new local variable
- Change whatever existing variable you have that centrally tracks the score instead
- If you don't have some central manager for tracking the score with one single central score variable, you need to create one
ill try that out, thanks!
My npc now successfully moves to the target location, but since I'm multiplying the rb velocity by the difference between the target position and the current position, the velocity scales down as the npc gets closer to the target point. I want it to have a constant velocity and stop at the target point. I know my moving code can't do that, I just don't know of another way to do it... 😕
void FixedUpdate()
{
Vector3 moveDirection = targetPos - currentPos;
rb.velocity = moveDirection * roamingSpeed * Time.deltaTime;
}
- You should not multiply the velocity by deltaTime
- normalize the direction vector
As for stopping you can check your distance to the destination and if it's within a certain threshold, then stop
Really the "right" way to do it would be to check if your velocity would bring you to the target point within a single fixed timestep, and if it would, set a lower velocity that moves you to the target point in exactly one physics frame. After that, stop.
Don't ping people you aren't actively in a conversation with
pretty simple , make a timer with Time.time or a coroutine
maybe throw in a bool for good measure
sorry
show me :)
private void RegenerateHealth() { currentHealth += Mathf.RoundToInt(regenRate * Time.deltaTime); currentHealth = Mathf.Clamp(currentHealth, 0,(int) maxHealth); sliderhealt.SetHealth(currentHealth); }
public void Regen(){
if(health < maxHealth && !healthRegen){
StartCoroutine(RegenHealth());}
}
IEnumerator RegenHealth(){
healthRegen = true;
yield return new WaitForSeconds(5);
while(health < maxHealth)
{
health += Time.deltaTime * healthRegenRate;
yield return null;
}
health = maxHealth;
healthRegen = false;
}```
ideally you call the Regen in a hit method or something
probably want to store it in a coroutine variable to deal with canceling old routine for new 5 sec timer when multiple hits in row happen
ok thanks I'll try that
private Vector3 spawnRotation = new Vector3(0, 0, 0);
can Vector3 be used like this for rotation?
if you store / use euler angles
Um like this?
private Quaternion.Euler spawnRotation = new Quaternion.Euler(0,0,0);
private Vector3 spawnRotation = new Vector3(3, 2,1); transform.rotation = Quaternion.Euler(spawnRotation)
Quaternion.Euler is a method
That would make sense if Euler was a nested type inside of Quaternion
e.g.
public class Quaternion {
public class Euler {
}
}
magic keyboard, please
That's not the case, though. Euler is a method of the Quaternion struct that calculates a rotation from Euler angles
oh ok thx
useless fun fact: Euler is commonly mispronounced as "you-ler", when in fact its actually pronounced "oy-luh"
much like "oiler"
that made my overcomplicated solution sound simple 💀
I think that the solution to the message you replied to was simple using sharedProfile instead of profile, lemme make sure
ah yeah, that was it
my ui buttons work fine in the editor, but dont work in the build. is there something i did wrong?
`what am i missing here?
I seem to be misunderstanding how to apply a Vector3
{
transform.rotation = new Vector3(0,0,0);
}```
rotation is a Quaternion, vector3 would not make sense
if you want to give it a v3 you need Euler function from Quaternion struct
i just need to set all of it's rotations to zero
Quaternion.Identity should do fine
i don't know how to use Euler, Quaternions or what a struct is
I just told you. Euler is a function inside Quaternion.
Quaternion is just a rapresentation of rotatation. It solves issues with gimbal locking that euler angles experience
the struct part is not relevant, struct and class are similar.
thanks!
I am having trouble trying to instantiate a tmp text on top of an enemy the player destroyed. Can someone help?
what is the trouble exactly? you have to be specific
hi quick question, is there a built in function to display an arrow to point to a particular object in the 3D space? A bit like the arrows you have in video games when you get shot at
(basically the arrow making you turn your head towards the object)
LookAt or LookRotation maybe ?
idk what you mean display an arrow though
When my enemy is destroyed, I want to leave a piece of text representing the amount of points the player earned at its death location
I don't exactly know how I can do that
use a textmeshpro mesh version. Use Instantiate to spawn it with the amount you want, make a script /make it a prefab, so you can easily change stuff on the instantiated object
Mesh version? Can you explain?
yeah so it doesnt need a canvas. A mesh is similiar to how 3D object works (or 2D sprite renderer in unity)
its just a 3D object with a material/shader
The TextMeshPro component.
TextMeshProUGUI is the UI version
The former can stand on its own, and makes sense for in-world popups like this
I would suggest creating a ScorePopup component that's responsible for:
- setting the text based on the amount of points
- making the text move (if desired)
- destroying the object after enough time passes
What if I also want to clamp it so that it doesn't go off-screen?
You can turn a world position into a screen-space position (look at the methods on the Camera component), clamp the result based on the screen's size (see the Screen class), and then convert back to a world position
if the screen position's x value is less than 50, make it 50; if it's more than Screen.width - 50, make it Screen.width - 50
that kind of thing
Ok, I'll think about it
I am not sure how to explain it, but a bit like this:
(the offscreeen target indicators)
ohh like 2D indicators
you can look at the signed angle between the player's forward vector and the vector to the enemy
yes, when you are not looking in the right direction. Do you have to build it yourself or is there something built in ?
i have a script somewhere.. shite.
There isn't a component for this, no
Bonus points: If the point is on screen, just attach the target indicator to the enemy
Then lerp between that point and the edge of the screen as it gets close to the edge
so that when they go off screen, the indicator slides to the edge and then stops there
I did something quick and dirty by looking at the cross product of these vectors (component of the cross product on vertical axis) and the angle but meh
I do not develop a game it is just for research
I shamely used the codemonkey tutorial when I did it, so I'm no help there 😛
I'm still fussing with the effect
are 3d tilemaps good for a minecraft like game?
do they have chunk support and mesh combining?
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
[Header("Jumping Settings")]
[SerializeField] private LayerMask ground;
[SerializeField] private float distFromGround = 1;
[SerializeField] private float jumpPower = 1;
[SerializeField] private float cooldown = 0.2f;
[SerializeField] private float jumpTimer = 0;
[Header("Movement Settings")]
[SerializeField] private Rigidbody rb;
[SerializeField] private float speed = 1;
[SerializeField] private float maxVelX = 1;
[SerializeField] private float maxVelZ = 1;
[SerializeField] private Transform head;
[SerializeField] private float rotateToHeadDamp = 0.3f;
[SerializeField] private float acceleration = 0.3f;
[Header("Debug")]
[SerializeField] private bool grounded;
[SerializeField] private float timer = 0;
void Update()
{
float w = Input.GetAxisRaw("Vertical");
float a = Input.GetAxisRaw("Horizontal");
Vector3 mForward = transform.forward * w * speed;
Vector3 mRight = transform.right * a * speed;
Vector3 combined = new Vector3(mForward.x + mRight.x, rb.velocity.y, mForward.z + mRight.z);
rb.velocity = Vector3.Lerp(rb.velocity, combined, acceleration);
if(Input.GetAxisRaw("Jump") != 0)
Jump();
grounded = Grounded;
timer = Time.time;
}
void Jump()
{
print("Worked");
// If jump too recent return.
if (timer >= jumpTimer + cooldown)
return;
print("Nope");
// Grounded check
if (!Grounded)
return;
print("Yep");
rb.velocity += new Vector3(0, jumpPower, 0);
jumpTimer = Time.time;
}
bool Grounded => Physics.Raycast(transform.position, transform.up * -1, distFromGround, ground);
}
I have this code that doesnt work its supposed to jump every 0.2 seconds maximum but it doesnt jump at all
in ```cs
void Jump()
{
print("Worked");
// If jump too recent return.
if (timer >= jumpTimer + cooldown)
return;
print("Nope");
// Grounded check
if (!Grounded)
return;
print("Yep");
rb.velocity += new Vector3(0, jumpPower, 0);
jumpTimer = Time.time;
}
It prints "Worked" and thats it
Somehow its returning even though timer is way more than 0.2
debug your timer
oh wops just saw screenshot
what is the jumpTimer + coolDown value
Jumptimer is basically stuck at 0 since the jump function doesnt continue and cooldown is 0.2
I also tried changing the print message to see if maybe code wasnt updating but it is
well 6 > 0.20 so its returning
oh my-
Chill Guy
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⢀⣀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠜⠁⣷⢊⠤⡇⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⡠⠴⠨⠼⡜⡝⠀⠀⠀
⠀⢀⣀⣀⣠⡤⠔⠒⠚⠉⢙⣖⡎⢰⣞⣶⠄⠘⢣⠀⠀⠀
⢰⣿⣿⣿⣿⣿⠀⠀⠀⠰⠀⠎⠁⠈⠾⠏⠀⠀⠈⡆⠀⠀
⢸⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀
⢸⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⢄⡀⠂⡇⠀⠀
⠀⠙⠿⣿⡿⠟⠀⠀⠀⠀⠀⠀⠀⣀⣠⠮⠀⠠⢈⠃⠀⠀
⠀⠀⠀⠀⠉⠒⠒⠒⡆⠀⠀⠈⡽⠥⠄⠀⠄⢀⣼⡀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢀⠏⠓⠶⠖⣒⣲⡲⠮⠝⠛⠁⠈⢆⠀
⠀⠀⠀⠀⠀⠀⠀⡌⡆⠀⠀⠀⠀⠀⠀⠀⠀⠸⠁⠀⠈⡆
⠀⠀⠀⠀⠀⠀⠀⢏⢇⠀⠀⠀⠀⠀⠀⠀⠀⣠⠓⠋⠀⣀
⠀⠀⠀⠀⠀⠀⠀⠈⢺⠓⢶⢒⣶⣲⣶⡒⠶⠲⣄⣀⡸⠉
⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠃⠻⣥⠥⠄⠀⠐⠔⢸⠇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⢠⣄⠀⢻⡀⢀⠀⠀⠀⢸⡇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢘⡀⠙⠀⠘⡃⠘⠄⠀⠀⢸⡇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠨⣌⠉⠉⠉⠹⠉⠒⠒⠒⠊⣱⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡔⠉⠉⠻⣫⢗⣣⡶⢶⣷⣶⠞⡏⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠱⣤⣤⣤⡽⡮⣏⠀⠀⠈⣛⢿⠇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠒⠒⠒⠒⠁⠀⠀
can you not like spam ?
listen "guy" you will pretty much be booted quick. I suggest you check out the #📖┃code-of-conduct
and if you dont have a unity question, don't post
im gonna start tweaking
i was just watching brackeys and making my game by following him
and the ui JUST DOSENT SHOW UP WHEN I COLLIDE WITH THE FWEAKING END CUBE
ive used my final brain cells bruh
using UnityEngine;
public class EndTrigger : MonoBehaviour
{
public GameManager gameManager;
void OnTriggerEnter ()
{
gameManager.CompleteLevel();
}
}```
```cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
float WaitRestart = 0.5f;
public GameObject completeUI;
public void CompleteLevel ()
{
completeUI.SetActive(true);
}
public void GameEnd ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME, OVER!!!!!");
Invoke("Restart", WaitRestart);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
someone hlep me plz 😭
Use more logs or step through the code with a debugger.
wdym wot is that
im on my 8th brackeys video bro 🙏
put logs in the OnTirggerEnter
brackys doesn't teach well
the thing that says Log in your script
should be the first thing you should've learned
debug.log?
that would be the log function, yes
you need more of them, to verify each function and whats happening
its the same exact thing as print
Use debug logs to see if your collision is even being registered. If it is. You can then debug log your game manager script to see where the issue is happening.
where do i put the log to see the registration of collisions?
In the on trigger method to begin with. Also check out https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider.OnTriggerEnter.html
What are you colliding your end trigger wiith?
the player its a cube
i tried adding a log it did print after colliding
but it didnt show up the ui
OOP
now it dosent print
Is your game manager script on your player game object?
You need to ensure both player and the end trigger has a collider. Box collider should work fine for both. Set the end trigger box collider as end trigger.
What's player collision?
both hav a box collider
Mind sending all the relevant code? Use one of these to send each. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
using UnityEngine;
public class EndTrigger : MonoBehaviour
{
public GameManager gameManager;
void OnTriggerEnter ()
{
Debug.Log("Its, Working!!!");
gameManager.CompleteLevel();
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
float WaitRestart = 0.5f;
public GameObject completeUI;
public void CompleteLevel ()
{
Debug.Log("ITS, WORKING!");
completeUI.SetActive(true);
}
public void GameEnd ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME, OVER!!!!!");
Invoke("Restart", WaitRestart);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement playerM;
void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
playerM.enabled = false;
FindObjectOfType<GameManager>().GameEnd();
}
}
}
You have nothing to say that your player collides with the end trigger
You can use the link to the unity docs I provided and use CompareTag so the end trigger knows when it collided with the player.
ok
this one?
Yus
I would like to ask a question. I tried to use UI Toolkit in Unity 2022.3.52f1 version and used ImageElement to inherit Image, so that I can drag and drop it in UI Editor. The specific code is as follows. The effect is normal in Unity preview, but when packaging on Android, I encountered the following error. I tried to ask chatgpt or google, but they didn't solve it. I would like to ask if there is a feasible solution.
public class ImageElement : Image
{
public new class UxmlFactory : UxmlFactory<ImageElement, UxmlTraits>
{
}public ImageElement() { }}
From a quick Google it seems like uxmlfactory is obsolete
As for why it works in the editor, there could be several possible explanations. A likely explanation is that android build is il2cpp, while the editor is a mono/dotnet build.
All working now?
You're welcome 😊
Thank you very much for your reply. I'll check the relevant information on the build method.
Hiya I have two vectors, transform.up and rb.velocity. How do I find the angle between them? (Ik this is trig but Im looking for some unity function idk)
wait sorry how do I find the vector imbetween them
If I dot and get the angle how do i turn that into a vector aswell
Vector#.Angle will give you the angle between both vectors . . .
What should I use to calculate t he collision force between two objects ?
easy, that's just subtracting them . . .
that is, subtracting the positions of each vector . . .
Subtract the velocity of the two and project the result in your wanted direction.
actually, what do you mean by "vector?" do you want the position or the direction between both vectors because those two are different . . .
I just set the Scripting Backend in Player Setting to mono, and the same problem still occurs after packaging, so I may need to check if there is another reason.
Android build can't be mono afaik. It's always il2cpp.
Hmm... Maybe I'm wrong. I wonder how it works.
Thanks anyway, I'll search on Google again😀
I tried to make a Camera Following mechanic for the camera but for some reason, it shakes/vibrates a lot. Any idea why?
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public Vector3 offset = new Vector3(0, 5, -10);
public float smoothSpeed = 0.125f;
private void LateUpdate()
{
Vector3 desiredPosition = target.position + target.TransformDirection(offset);
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.LookAt(target);
}
}
Probably because your car vibrates
Smooth the lerp more
Also, this is not how lerping works
The third parameter is the intermediate between a and b so you only set it to a static 12.5% of the position using your current code
It does not vibrate in scene view though ;-;
ohhh
There are functions that can do what you want, but I forgot the names
Or change the code so you always have the desired position somewhere and the current camera position, and create some sort of elastic movement where the camera loosely follows the car
Also don't use LateUpdate, just use Update
You want to make it frame independent, so using time.deltaTime as your "speedValue" multiplied with your desired multiplier should be your way to go
I don't see why you'd have a visual camera be frame independent, you just need to fix the smoothing since there's no smoothing at all
the first part of the sentence is clearly self-explanatory, id say. You dont want to move it in different speeds at different fps, right. Still agree, that there is no smoothing at all but just setting the fixed percentage of the values. That time independence was just an add on on top of your answer
Okie lemme try
Okie it works now! Thanksss!
Vector3.SmoothDamp and using Time.deltaTime is what I did and it works better now. I also shifted back to Update instead of LateUpdate!
Clear, just making sure 👍
To add to my comment, LateUpdate is somewhat of a hack so some things happen after Update. You'd only do this if the code depends on stuff happening in an Update, but you have absolutely no control over a third element that might have to happen after a LateUpdate entry. So instead of using LateUpdate, you'd use events, or something else to measure an order of execution