#💻┃code-beginner
1 messages · Page 313 of 1
i don
Are you using breakpoints?
create a timer for 5 seconds then you can use built in MoveTowards or create your own
't use debug log, i use this fancy thing
Breakpoints
non-suspend breakpoint
but every frame in update the object is being dragged to another position
how can I "deactivate" them
for the time frame
show the code
I would try one that DOES suspend, just inside the ontrigger, before any check
here is the code that is constantly pulling the object to one of two position, below this code I have
A call to recoil animation
which
that's what i do scatter a few non-break points to log along
is set up to move the object where I want it
but only for a single frame rn
that's a tracepoint
I basically need a way to deactivate those methods constantly dragging the object in update... But I dont really understand what is truly happening when I call recoilAnimation(), is it cycling every second with Update()? Or is it running independently...
Like can I use a boolean to disable those if checks for the duration that recoilAnimation() is running, and after it leaves I set the boolean back to true, and those if checks can be accessed again
Just to be clear, am I reading the chart right?
It can be kinematic AS LONG as the kinimatic rb is attached to the trigger.
A kinematic non-trigger collider won't send OnTrigger with a static trigger collider.
no, kinematic rigidbody sends OnTrigger to static trigger. it's only two static triggers or no triggers at all that don't produce OnTrigger messages
well for starters, why are you null checking the way that you are?
Ah damn, I went back to see how I read it wrong and see I just looked at the wrong row.
Scrolling back and forth on a phone 
Thank you
yep, no worries
look
i don't like the wiggle that rider puts on ?. because it bypasses unity funky object lifecycle, yeah i'm as autistic as you guys 😉
i was referring to the way you were doing null checks in your actual code using the is operator
because that bypasses unity's overloaded == operator for null checks as well
anyway, if attachedRigidbody is null then the object that this component's collider is overlapping does not have a rigidbody
Really shouldn't be bypassing the check unless you understand it very well
Also, use TryGetComponent
hi, i am making a bullet and enemy script in which everything is working however the bullet pushes the enemy around due to its speed. just wondering, should i set the bullet to a trigger or pursue a different solution?
i don't want to bypass the lifecycle, hard to debug down the line. the is is just the shorthand to create the variable once without having to do it again in the if
is {} bypasses the null check
it does, that's the strange thing
much cleaner, thx if (other.attachedRigidbody.TryGetComponent<PlayerVersion>(out var playerThing)) {
apparently not. this is where unity's Debug.Log comes in handy. you can Debug.Break and then print a log that you pass other in as the context object so that when you select the log in the console it highlights that object
if (other.attachedRigidbody.TryGetComponent(out PlayerVersion playerThing))
is even cleaner
nice
you know what that might be it. the bullet logic detects the collision and self destructs before the black hole has a chance to detect...
tsss, nope because i'm pooling. alright time to call it a night
tsss*2 it was that:
it deactivated the bullet for pooling which apparently nulls the .attachedRigidbody even tho it still exists... must be deregistering it from physx before the end of the physx update... must be because i have auto sync on.
alright it's working now
and being able to change code while it's playing is awesome
thanks @slender nymph @north kiln
this is really cool, how do i add to the input system?
things i found out while digging VR
why you have static void Main?
Now I dont have one
ok i read that
and still dont understand what to do
I removed the static void Main class
I have my Random random declared in the Update now
static void Main is another issue, now the website tells you how to how ambiguous reference
programwise, what's smarter? To return a dictionary<string, float> and then look up keys or to return a large tuple tuple<float, float, ..., float> and knowing on what position you have what value?
The problem is with the dictionary, I have to deal with the possibility that I don't have the key in there. With the tuple I have to deal with knowing the precise position of the value.
oh okay
cool
but.. I can not use that either
this is not a valid variable nor method declaration
c# doesnt support variadic generic type argument so there is a upper limit of number of generic types passed into tuple
also tuple and dict serve as different purposes
you use string as key to find a float but you then told me you find it in "a list" of float (access by index)==you already have the float, i dont know what you want to do=>need more info
then why did you show me that
lol
You dont know where to put, put the example code inside a method and use it
anyone got any tips for how I could program my card abilities? itll have many different abilities so I was wondering if they should each be their own class or a struct etc
I literally cannot imagine a world where you'd use a tuple that long.
Dictionary or List.
I am dealing with a array of GameObjects. There are a total of 3 Objects in it and I am constantly switching between them. I don't like checking which is active with```cs
GameObject characterCollection[];
void Update(){
if (characterCollection[0])
{
print("Human");}
if (characterCollection[1])
{
print("Monster");}
if (characterCollection[2])
{
print("Alien");
}}
you could use a dictionary.
Why not just create a "activeCharacter" variable and whenever you switch, set that field with the correct character.
Then use that field.
Can you explain further on what activeCharacter would be?
GameObject activeCharacter
I am using that system, but I may be doing it weirdly. This is what I usually check cs if (activeCharacter == characterCollection[0]){ print("Human"); } Now I don't know if I am using it wrong?
You could just change the name of the gameobject itself.
And then do print(activeCharacter.name)
I need to switch between objects. I want them to have different values and scripts
!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.
I don't see the issue.
Have a method that handles the switching.
Do all the setup you want in there.
Set activeCharacter
use active character
So instead check the name?
Have the same script on all objects. Have that script define an enum with all character types. Then GetComponent from the objects and check the type. Dont check names since that is fragile and prone to errors
I dont know the specifics of what he wants
is it just debug or actual gameplay relevant
Ok…
I am having such a trouble trying to make my system more readable. I have 3 Objects, 1 that is default Character, 1 that is overcharged version of default Character, and 1 that is Machine Character that is completely different. Lets call the 2 Characters that are default similar to "Modes" and the Machine "Machine". When Mode 1 (Default Character) gets a charge variable up to a fixed number, it will change into Mode 2 (Overcharged Default Character). After a 10 seconds it is back to Mode 1.
Now, I want to check everytime Mode 2 was achieved, so I added a counter that was added everytime Mode 1 was changed into Mode 2. If this counter is 3 then I want the Player to be able to Press 'T' to change into Machine.
In Summary: I need help with making the code easily readable.
then you count the number of times that "a charge variable up to a fixed number"
I do
How can I moveToward() a child object
when I try to do it the parent just doesnt move
You want the parent to movetoward the child?
You would either have to unparent the child, or countermove the child towards the parent
And your child object world position depends on parent object
wym countermove
hey does anyone have any tips for how to make a system for abilities in my game? ranging from healing attacking or etc?
structs, interface?
Move the child instead of parent
but the whole point of the child is because it allows me to keep track of a position always a certain amount behind the parent
how do I move the child behind itself
I asked you to clarify what you want
Do you want to move the parent toeards the child?
I want the object to move backward when I click the mouse button
so I made a child thinking it could always be behind the object, and I could move to it
Then you shouldnt use tree, you parent depend on child but your child depends on parent
Use transform.forward/right/up
I mean yeah, you can do that
If I want the object to move x distance backwards, how do I keep track of it with transform.forward?
"Keep track of it"
Do you mean distance?
Transform.forward is direction not position
yea
A quantifiable number I can keep track of
Then just add the distance moved to a float
I am not very familiar with how to do something like that, the distance is a vector 3, if I say like, move 10 in the z direction, it won't produce the effect I want because the z direction is constantly changing
I forgot to mention the object is tied to the player
You want your object move in speed x m/s then use move towards to find the position (direction*speed, amount is time.dt) and assign it back to tf.pos
Distance is not a vector3. It would always be a float
The magnitude OF a vector3
Direction wont be changed unless the rotation is changed
rotation is constantly changing
lemme try
Then use vec3.forward, it is dir in world space
man this is so weird
forward goes forward
but -forward goes to the right
it also seems dependent on which way my character moves....
like if I move to the right it goes to the right
oh nvm
vector3.forward is based on the grid
Vector3.any direction is world rotation
transform.any direction is based on the transforms rotation
maybe you guys could catch this if i showed like a vid or something
This is the code for me trying to move the obj backwards(up is backwards because I rotated it )
2d top down game?
Mornin' all, I have a character with animations attached, but I would like it to 'bend' at the waist for the up and down mouselook. But the Animations take priority, so the mouselook has no effect. Is there a way to 'override' the animation on that bone to allow for the mouselook to work?
seems the tf.forward is always pointing to same direction
yea...
but when I call the method isn't it going toward the most recent "transform.up"
based on what i showed here
Sounds like something that animation rigging can do
Fixed it
now it works as intended
oh yes, i always forgot to turn a direction into position
MoveTowards a point. That's how I always remember. You can MoveTowards that mountain, but MoveTowards east sounds funny
Hmm. Okay thanks, will have a looksee.
Hmm, okay, I've found a bunch of posts etc. saying that LateUpdate() is the way to go for rotating a bone through code, but that you need to store the bones rotation. But not one post has shown an example, so I'm a bit stuck as to where I'm supposed to be storing the rotation value. 😕
Same as any other value you want to cache🤔
Well I know how to do it, I'm just struggling a bit as to where lol.
The question is why do you need to store the rotation ?
Store what rotation? Before the animation ?
Well, where would you cache something usually?
!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.
Okay, this is what I have at the moment. In my head, this should work, but the bone isn't rotating (well, it jitters, which says to me that the rotation is getting reset by the animator?)
Update()
//Mouse Input
mouseRotation = mouseSensitivity * Time.deltaTime * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
transform.Rotate(mouseRotation.x * transform.up);
playerBoneRotation = mouseRotation.y * transform.forward;
LateUpdate()
private void LateUpdate()
{
playerYBone.transform.Rotate(playerBoneRotation);
}
Is transform the camera?
So does it jitter or not rotate at all? If it were to be reset by the animation, you wouldn't see any change from with or without the code.
transform is the player, the horizontal rotation works fine, so that's not an issue.
Gimme a couple of minutes, I think I just had a brainwave. lol.
Why don't you even rotate the playerYBone directly in the Update instead of assigning a variable and rotating it in the LateUpdate?
Because that doesn't work as the Animation is processed after Update, so the Animation will always take precedence.
What is your animation even doing? Do you even need it?
It's an idle animation, but there will be others.
Why do you need an idle animation to reset the rotation?
Also, why do you apply the Time.deltaTime directly to the transform? This is what might actually cause the jitter
Huh? I don't, I'm trying to stop it from resetting the rotation. 😕
Well, but it's resetting it, as you have previously mentioned
Which should make you consider about this animation being redundant
But it's not. And it's something I need to solve because there will be other animations that I'll be using.
Start by debugging the values and making sure they're all what you expect.
One thing that's incorrect and has been mentioned is multiplying mouse input by delta time
Okay, well at the moment, this is what I'm getting.
Debug.Log is the bone Rotation.
Update()
//Mouse Input
mouseRotation = mouseSensitivity * Time.deltaTime * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
transform.Rotate(mouseRotation.x * transform.up);
playerBoneRotation.eulerAngles = new Vector3(0f, 0f, mouseRotation.y);
//playerBoneRotation.eulerAngles = mouseRotation.y * transform.forward;
Debug.Log(playerBoneRotation.eulerAngles);
LateUpdate()
private void LateUpdate()
{
playerYBone.transform.localRotation = playerBoneRotation;
}
I've modified the code a bit, but still getting the same results. I'll fix the deltaTime thing later (if it was that much of an issue tbh the horizontal rotation wouldn't be working either)
Why would you want to fix the Time.deltaTime issue later?
Honestly, this is the thing that's most likely to cause the jitter
In the Update you multiply the mouseRotation by Time.deltaTime, even though it's only appropriate for rotating the transform, not setting it directly
Yeah, deltaTime does not belong with mouse input
So, you'll have to remove the Time.deltaTime from the mouseRotation and use it just when rotating the transform
mouseRotation = mouseSensitivity * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
transform.Rotate(mouseRotation.x * Time.deltaTime * transform.up);
playerBoneRotation.eulerAngles = new Vector3(0f, 0f, mouseRotation.y);
This might fix the issue you're having
Mouse delta already has delta time taken into account. Multiplying it with it again will make it inconsistent
Hey this is kind of stupid but im struggling with something pretty bad,
im making a roguelike and i want room transitions to go like this : freeze the game, fade in black, change room, fade out, resume game
ive tried using time.timescale = 0 but that seems to also pause the animations, keep in mind id also want some functions to run right after the fade in to black animation is completed
Change the animator to run in unscaled time
oh lmao ok
Simulation Mode in the inspector IIRC
Okay, well the bone does rotate more, but it seems to be still fighting with the animation as it reeeeeally wants to return to its 'base' position.
You might also wanna check your Simulation Mode on the animator, what is it set to?
Wait it might be called something else
Maybe Update mode
Yeah that
I see, yes, you're right. Applying the Time.deltaTime to the mouse input is redundant.
The code I shared above doesn't require the Time.deltaTime
transform.Rotate(mouseRotation.x/**Time.deltaTime*/ * transform.up);
Yep
This is as simple as rotating the bone in LateUpdate, yes. Dont you have your player's look angles stored in a variable? Could just rotate the hip/spine/whatever bone by the X look rotation
Yeah I have the vertical look stored in a variable but the bone I'm applying it to keeps moving back to it's 'animation rotation'
Update()
//Mouse Input
mouseRotation = mouseSensitivity * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
transform.Rotate(mouseRotation.x * transform.up);
playerBoneRotation.eulerAngles = new Vector3(0f, 0f, -mouseRotation.y);
private void LateUpdate()
{
playerYBone.transform.localRotation = playerBoneRotation;
}
I just do something like this in LateUpdate
bone.RotateAround(bone.position, rightAxis, lookAngleX)
I dont get what all the other stuff is for
What other stuff?
Vertical look angle yes. The horizontal rotates the whole of the player object, the vertical I want to just rotate the 'spine' bone so that the player bends forward and back at the waist.
Right ok. Did you check my example?
Just rotate the spine additively in lateupdate
Don't directly set it to anything
Okay, will have a go. lol.
And dont use the current frame's mouse input for the rotation, store the total rotation in a variable instead
So the x angle you use for spine rotation would be somewhere in the -90...90 range
Though ofc you can multiply the final angle to rotate by with a smaller value so it looks more sensible
Okay, so not sure if I've done this right tbh, but it's still 'fighting' to get back to it's original position.
private void LateUpdate()
{
playerYBone.RotateAround(playerYBone.position, Vector3.forward, -mouseRotation.y);
}
This is frying my brain. And it's only 8am. lol.
From what i can see, mouseRotation only stores the delta of the rotation this frame.
You need a variable that holds the accumulated rotation. You know, you add the delta to it every frame
Yeah something like that
okay will give it a go.
Ideally you would use that accumulated rotation value as base for all your rotations, instead of just rotaing transforms and reading back their angles
Make sure to clamp the vertical though
Yeah, I will be. And yeah, that works, kinda. lol. The bone rotates forward and back okay, but when the horizontal is changed, it goes a bit screwy.
Fixed it. lol.
I had Vector3.forward instead of transform.forward.
Thank you so much for the help, really really appreciate it. 🙂
Nice 👌
So just to check, with the horizontal rotation it would be 'better' to do a similar thing to the vertical? (accumulatedXRotation += mouseRotation.x) ?
Well thats how I like to do it. Store rotations in variables instead of in transforms
Makes it clearer for me at least. And you know that nothing else changes the value, while a transform can be affected by other stuff such as animation
Okay cool. 🙂
how can i make the canva ui text always adjust to the size of my screen in unity?
is there a way for that ?
like a built-in method or build-in keyword or smth?
In your canvas inspector, there's a dropdown for how you want it to display, choose 'Scale with screen size' and enter a 'default' screen size (I usually go with 1920x1080)
(Right side)
So I have a abstract class ChessPiece that my pieces inherit from, and the idea is that when you attempt to move a piece, that piece should broadcast it's location to all pieces on the board, and they respond with their position and color, so that the piece you want to move can determine if that is a valid movement.
But the BroadcastMessage and SendMessage methods don't work on inherited classes, they work on objects and monobehaviors.
Would it be a better idea to keep a singleton data structure with the list of positions instead then, so that when a piece updates it's position it modifies it's position in the structure for all other pieces to see?
But the issue is that singletons and global variables are frowned upon. In this example the only interactions should be from ChessPiece inherited classes, and the interactions will be done through a method inherited from the ChessPiece class, so maybe that makes it more acceptable since there is only going to be two ways of interacting: reporting new positions/colors, and reading the positions/colors.
I'm not aware of a more effective way of keeping track of the gamestate, if you guys have a suggestion.
maybe I should make it a struct since it's meant to store data and not actually do anything
How do I make an object that is rotated by the player camera rotate 15 degrees on its x axis using rotateTowards?
I also making chess & i think you should make static array of chesspieces and on move just modify this array. It will be really useful if you will make method that tells cn someone beat this chess piece (for example, for shah or for check can king move there)
alright, that makes sense. I'll probably put the array and such in a struct because that seems like it will make the most sense for the state management
what's a shah?
When someone can beat king
singletons and globals are fine
could be a little messy if not organized correctly in larger projects but chess isn't something to worry about
ok then, cool.
it's not like you're doing some traditional scripting for some c# program. Unity's scene and gameobject lifetime adds some extra complexity that makes it harder to grab references.
what kind of chess game are you making?
attempt to move a piece, that piece should broadcast it's location to all pieces on the board, and they respond with their position and color
What are you trying to do with this
you can simply store all the pieces in some 2d array, and anything that tries to move a piece will do so through the class storing the array.
theres also no need for this array to be static
hexagonal chess. I have a chesspiece class and each piece type inherits from that, and they move themselves when the player drags them.
all the other pieces move themselves? i dont see why really the other pieces need to be aware of the movement
well I store how the pieces can move in their script, and then on drag the piece follows the cursor and then updates it's position when it's dropped in a valid spot
storing the movements as vector3ints helps me generate clone meshes for where the pice can move
yes but how does this affect other pieces, i am trying to see what you are doing when you said "piece should broadcast it's location to all pieces on the board, and they respond with their position and color".
It sounds like you dont need this at all. at the end of each turn, you can calculate valid movement for each piece
rather than based on when a piece moves, do it from whatever the game manager is
oh that was basically when I click on a piece to move it, it would call out to the other pieces to figure out where they are located to determine valid moves. I'm gonna scrap that in favor of the list because it makes more sense
Ah i see
Just populate some container of unoccupied and occupied positions
and refer to that (easily accessable from the gamemanager)
Also just a note, i dont think the original solution would work unless you store them in some 2d array after grabbing all the positions. There are more cases than just "can i move here", for example u cannot move if it would put your king in check.
yeah, which helps that I have the "sights" stored, so I can stop the king from moving to a place that is in check using vector addition
all of my locations and movements are stored as vector3ints so the tests should be relatively simple and quick
I'm new to work with objects (here .obj) in unity & i have a problem. I'm making objects after start & all primitives work fine except object. When I adding script to an intance created by GameObject.Instantiate(Resources.Load<GameObject>("path")) it doesn't works. But all of this objects has a child named default & when i adding script to it, it doesn't work too.
I would say declare a gameobject variable at the beginning, assign it's value in start using resources.load, and use UnityEngine.Debug.Log to check if resources.load is loading the object into the variable correctly (check if it's null).
are you getting a nullreference error from the line?
no, script just does not work
any error, warning, or log at all in your console?
can you use http://gdl.space and send your code? just the method where you call the resources.load
i added some Debug.Log in my code. Created is on creation intance of object (not primitive), Moved on clicking on GameObject with script, currently added to child. After 1 click on pawn & some clicks on king here's console
and it's just failing to create one of the pieces, or is it failing to load something else?
fail only in zero logs with some King moved
I'm don't know what that means.
if i add this script on parent & on default situation is without changes
private void OnMouseDown()
{
ChessVector vector = ChessVector.GetCoordinatesFromVector(transform.position);
Figure.select(vector);
Debug.Log($"Moved {Figure.GetFigure(vector).figure.name}");
}```
code from script, i clicked on king
so you click on the king, ChessVector gets the coordinates from the pieces transform, and the log prints out that you moved the piece
yes
and sometimes it's failing to print out?
but log doesn't print if i click on the king
does the king have this script attached to it?
all GameObjects has the same script, but it doesn't work only here
yes, parent & child
can I see the code for figure.getfigure(vector)?
and figure.select(vector)?
do you need to use that to get the name, instead of just using name as it's built in?
yes
public static Figure GetFigure(ChessVector vector)
{
if (vector.isValid())
return chessBoard[vector.x - 1, vector.y - 1];
else
return null;
}```
public static void select(ChessVector vector)
{
OnSelect(GetFigure(vector), EventArgs.Empty);
OnSelect = (sender, e) => { };
selectedCanBeat.Clear();
selected = vector;
selectedCanBeat.AddRange(GetFigure(vector).canBeat());
GameObject parent = GetFigure(vector).figure;
GameObject[] moveSpheres = new GameObject[selectedCanBeat.Count];
int counter = 0;
foreach(ChessVector i in selectedCanBeat)
{
Vector3 coords = ChessVector.GetVectorFromCoordinates(i);
bool isFigure = GetFigure(i) != null;
moveSpheres[counter] = GameObject.CreatePrimitive(PrimitiveType.Cube);
moveSpheres[counter].transform.position = new Vector3(coords.x, 0.025f, coords.z);
moveSpheres[counter].transform.localScale = new Vector3(1, 0.05f, 1);
moveSpheres[counter].AddComponent<ForMovePads>();
if (isFigure)
{
moveSpheres[counter].GetComponent<Renderer>().material = materials[((int)(GetFigure(i).color) + 1) % 2];
GameObject killButton = GameObject.CreatePrimitive(PrimitiveType.Cube);
killButton.transform.position = new Vector3(coords.x, size / 2, coords.z);
killButton.transform.localScale = new Vector3(1, size + 0.1f, 1);
killButton.GetComponent<Renderer>().material = materials[3];
killButton.transform.parent = parent.transform;
killButton.AddComponent<ForMovePads>();
OnSelect += killButton.GetComponent<ForMovePads>().delete;
}
else
moveSpheres[counter].GetComponent<Renderer>().material = materials[2];
OnSelect += moveSpheres[counter].GetComponent<ForMovePads>().delete;
moveSpheres[counter].transform.parent = parent.transform;
}
}```
uhhh, guy, it's genious
Please, consider using the sites for sharing big code blocks. !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.
would this:
$"Moved {name}"
be better for the debug.log or do you need to get the name through the figure call?
wondering if the figure call has something to do with it
no, this name ==== Figure.GetFigure(vector).figure.name
Guys is it possible to remove the texture from memory if an object is culled ?
as of right now I can't really help with this. Someone with experience in object loading or asset management may have an Idea of what's going on.
basically the code seems to work fine on primitive objects, but once he created a king.obj file and tried to load it, the creation works fine and the start works fine, but the onmouseclick method fails
gn guys
i've never seen an obj file before
if someone knows how 2 make onMouseDown() to work with custom models, please help in this thread
Oh it's like a mesh and stuff?
yes, simple blender export
Wait do you have a collider on your king?
I'm pretty sure onmousedown needs a collider doesn't it?
what is collider? it's just cone
Try adding a mesh collider component and see if the onmousedown works
In the inspector or the prefab or you can do it in code when you create the object
That might be why primitive game objects worked, because they have colliders on them
tysm!
Did it work?
yes!
Yay!
Took me a while to think of it but this is like my second time actually helping someone
I can sleep in peace
Is there a way to get a NavMesh sorta coordinate? Like I want a NavMesh Agent to pick a random position within the NavMesh boundaries
Is that a thing?
https://docs.unity3d.com/ScriptReference/AI.NavMeshTriangulation.html
https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
you can choose a random vert and also sample the position. can just sample position as well if you know roughly where you want them
https://forum.unity.com/threads/disable-gameobject-textures-in-memory.204725/
Calling destroy() might be an option
Basically I just want an enemy to wonder around sorta aimlessly without getting to close to the edges
And not sure what I should do with those methods
Is that supposed to return a vector 3 something?
hello this is a frame where i have a big frame drop and this is what seems to cause it. what conclusion can i make from this?
First link is just so you can get a random point, by accessing a random index of the vertices. Sample position is to find the point on the navmesh near where you want.
How do I destroy the texture when the object is culled ?
I have 100s of copies of the same object in my world how will I detect a cull ?
But a Vertex is like... the actual surface vertices? Like the outside area?
That seems tricky
Honestly idk much about what it is exactly. The vertices should just give you the location of every part that makes up the navmesh.
Could be an easy test to see what it gives you if you draw or put objects at some of the vertices and see for yourself where they go
looking for a collab
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
i will make 24 hour game challenge
Gonna try that, but I am pretty sure is not going to do what I want it to do
Hey guys
Can I have a look at an example code that does "When the player is dead, it uses an Action to broadcast to the GameManager so the GameManager carries out some functions such as end the game" ?
I vaguely remember doing what I suggested above when making an enemy spawner. It should be fine
i have couple of enemy spawning script stored in case i don't find one
Also, I think none of my enemies have a reference to the NavMesh itself at all, since it is meant to not be an specific one
What part are you struggling with? Based on what you wrote, it seems like you know exactly what you need to do
The functions are static, doesnt need a reference to any specific navmesh. It uses data from all of them
So... it gets a random vetx from any active MavMesh on scene?
So I'm watching this video
And when the player dies, I want to open a canvas that tells the player they are losers
https://www.youtube.com/watch?v=8fcI8W9NBEo&t=627s
Learn how to decouple your code by using Actions, Delegates and Events! Trigger code from anywhere in your project by subscribing to an event as a listener, they never need to know each other exist!
Join me and learn your way through the Unity Game Engine, the C# language and the Visual Studio editor. Remember, if this video was useful then DRO...
You'll have to create e.g. an UnityEvent and call it when the player is dead, which might happen in the one of your methods or OnDestroy
// The private method serialized in the Inspector
[SerializeField] private UnityEvent _onPlayerDead = new();
// The public property for the private method
public UnityEvent OnPlayerDead
{
get => _onPlayerDead;
set => _onPlayerDead = value;
}
private void OnDestroy()
{
OnPlayerDead?.Invoke();
}
You'll be able to subscribe to the event from any other class, assuming you have a reference
playerController.OnPlayerDead.AddListener(DoStuff);
The triangulation just has an array of them. You choose a random one however u want. Or just use sample position in random places around your agent
I have not study Unity Events thoroughly
Can you explain please ?
Do I catch the
private void OnDestroy()
{
OnPlayerDead?.Invoke();
}
Like I do with actions from other classes ?
There's nothing more to explain.
The Invoke method calls the event for every instance currently subscribed to it.
Having 3 different subscriptions to the event, regardless of the classes they're in, will call them all.
playerController.OnPlayerDead.AddListener(() => print("1st"));
playerController.OnPlayerDead.AddListener(() => print("2nd"));
playerController.OnPlayerDead.AddListener(() => print("3rd"));
// =>
// 1st
// 2nd
// 3rd
Say, invoking the event in the Update, will print the 3 messages above every frame.
private void Update() => OnPlayerDead?.Invoke();
By putting the operator ? after the event's name, you ensure no NullReferenceException is thrown in case the event is null. Not using this operator may give you the errors if it is.
=> print("3rd")
Can I replace this with a method instead of writing directly ?
How should I organise my scenes? I was thinking a serialised list in the inspector. Opinions?
Yes, of course.
By using the () =>, you make sure the listener cannot be removed.
() => print("3rd");
If you want to use a method, it will have to match all the parameters your event has. In this case, the method should be passed directly without the parentheses ()
OnPlayerDead.AddListener(DoStuff);
private void DoStuff() => print("3rd")
When the parameters don't match, you'll have to use the parentheses () with the parameters inside of it
OnPlayerDead.AddListener(DoStuff); // error
OnPlayerDead.AddListener(() => DoStuff("something"));
private void DoStuff(string something) => print($"{something}, 3rd")
You can give your event from 0 to 4 parameters by placing them inside of the <>
UnityEvent<string, bool, Vector2, float> YourEvent
does .AddListener work with any public method?
It does work according to the access modifiers' rules
How do people deal with GameManagers or scripts that should only have one, persistant instance?!
yoooo! I wanna ask a pretty silly question, but basically, I want my game to have a cutscene in a middle scene, and press f to load the cutscene, code are below:
private void Update() {
if (inventoryManager.hasSoda) {
drink.SetActive(true);
Time.timeScale = 0;
if (Input.GetKeyDown(KeyCode.F)) {
SceneManager.LoadScene(sceneBuildIndex, LoadSceneMode.Single);
}
}
}
however when I press f the scene loads but not my animation. Whys that?
I want a GameManager.cs that exists between levels
does timescale bring forward to the next scene?
google singleton
It is a singleton. But surely that should not be the fix
So it has to delete the other instance every single time a scene is loaded?
Doesn't really make sense, right?
yeah, you assign one instance in awake if instance is null otherwise delete game object
Does ontrigger enter works with character controller? I have a trigger on room entrance to detect if player has entered. After debugging i found out that code doesnt even executes that method, ignores completely, when player enters
So again, that implies everytime a scene is loaded it deletes the clone.
Example, MainMenu has the GameManager.cs. Then you go to Level1, player dies, it goes back to MainMenu.
Assuming MainMenu has GameManager, it will delete the script upon returning to MainMenu from Level1... Since when that Level is reset it will recreate the original GameManager meaning two exist
Your !ide doesnt look 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
• Other/None
You could just have a loading scene which exists at the start, then loads the main menu
That initial loading scene can have the game manager
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
create a primitive GameObject, and attach a Collider and Rigidbody component to it.
Does it have a collider and Rigidbody?
Oh. So a scene that exists in the start, containing system-wide scripts, that lays out persistent stuff inside DoNotDestroy?
Makes sense. I wanted to avoid having an extra scene, more memory allocation and then have to deal with loading another scene from my understanding
player just has a character controller on him, thats why I'm asking if it has in build collider
Nope, I don't think it does
Yes, and you'll have to delete a singleton if there's an another version of it
"More memory allocation" is literally irrelevant in this case. If you have a performance issue, then address it with the profiler
Okay, but there should not be another singleton though?
It is a singleton, that functionaility exists, it deletes clones
But say I did the intial loading scene, it shouldn't ever clone the script unless it is unexpected behaviour?
it shouldn't, you just protect it in case you add that singleton script by mistake to another game object or other mistake
Okay thanks for confirming
It's not clear but apperently scenes do actually have a close relation to allocating memory, hence why people would skip additive loading... That's what I saw but I'll take your word on it
Since when you LoadScene, you are allocating the memory, unloading is freeing the memory
It doesn't matter anyway, it's just annoying to deal with another scene. Is what it is I guess
Not really sure where additive scene loading was brought up here, I'm not saying to load it additively
I brought it up, to make a point about memory allocation with scenes; purely from what I read on the docs/forums
Like I said, doesn't even matter, Thanks for the guidance I'll try what you suggested
Dont worry about memory or performance until you actually have an issue, it's a waste of time to think about
You can run a LOT more than you think
Okay, even for mobile? I want it to support older devices and seen some horror stories
I really don't know
It is lightweight physics based, uses a lot of triggers and rays
2D
Mobile wont run as much of course but usually when there is a performance issue, it'll be from one main area. Like if you're trying to simply run too many enemy AI
ahh, does anyone know another way of checking if the player entered a room besides triggers? I have build the whole player controller system around character controller, trigger collision doesn't work with character controller but I don't think that just adding collider with a rigidbody solely for room entering is a good architectural decision
w server w community
Raycast maybe. Uses the Physics class instead. You can use layerMask and declare it "player"
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Will NavMesh be a concern?
normally it should't be, but if it is you can check Brackeys video on nav mesh agent optimization
https://www.youtube.com/watch?v=G9Otw12OUvE
Let's see how many NavMesh Agents Unity can handle! That's right, another excuse for making a huge simulation ;)
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
····················································································
♥ Donate: http://brackeys.com/donate/
♥ Subscribe: http://bit.ly/1kMekJV
● Website: h...
Oh great, I'll bookmark that
Honestly idk enough about 2d to even know how you use navmesh with it. But as a general answer, the worst part about it will be how much logic you're trying to run at once. Like you arent getting 100 enemies at once on mobile
Brackeys also really isnt a good source. You should just test it yourself, see when the framerates really drop
Okay, yea, like you guys said, we'll have to see. I dumped a few features like lighting too, just precaution
Thanks guys
Are you in 2d or 3D and what is the shape of your rooms?
And how many rooms do you have?
Are they box shaped or will they have arbitrary shapes?
I think just adding a kinematic rb should be fine. Theres really nothing wrong about it, kinematic means its excluded from the physics stuff
it is strange actually, i added rigidbody and collider on top of character controller, made sure that part of the collider are above character controller and it still doen't register anything
I plan to do one in box shape, one as a circle and one curved, like a line
but fps drops when I enter the room:))
I always use Gizmos
https://docs.unity3d.com/ScriptReference/Gizmos.html
It's a bit extreme but pretty much anytime I do a new collider/trigger. You could make a simple Gizmo that changes colour when the player connects, it's the best way to debug that. Or if you prefer, a Debug Ray too. Other than that I can't think what else
Gizmo best way to visualise connections
void OnDrawGizmos()
{
// Draw a yellow sphere at the transform's position
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(transform.position, 1);
}
well, i just added a break point on the line of code inside the on trigger enter method when it check for the Player tag
What do the connections between your rooms look like?
if it stops there it has at least detected collision
Just open connections or something more restrictive?
For now it just a playground, where i check if everything works as planned
that collider on the ledt is room entrance on the right - player
int z = 0;
while(z < 50)
{
z++;
Debug.Log(z);
yield return null;
}
why is this running only once in my coroutine?
and I am sure it does work because when i start running the scene it detects enemy inside the room
This this an individual class or it's written somewhere ?
What do you mean?
Local value cannot be changed outside of the Coroutine, so this is supposed to be executed 50 times. Your coroutine is somehow stopped.
I mean the whole
// The private method serialized in the Inspector
[SerializeField] private UnityEvent _onPlayerDead = new();
// The public property for the private method
public UnityEvent OnPlayerDead
{
get => _onPlayerDead;
set => _onPlayerDead = value;
}
private void OnDestroy()
{
OnPlayerDead?.Invoke();
}
part here is written in the same script with playerController or in a different class ?
do you wanna know what it was? i forgot to uncheck use gravity on room entrance rigidbody🤯 so it kept falling
Why does your room entrance have a rigidbody? Just the player having one should be fine
because collider provides a volume but rigidbody is what registers collision, no?
Only one object needs the rigidbody
oh, I'll keep that in mind, thank:)
It doesn't matter. You may want to use it in some sort of a GameManager, but you can also use it in the player's script
Okay ...
Thanks
I don't see why you would use the crying emoji. Is there something I haven't explained well enough?
Hi. I have some questions about optimizing the script. I have 2 choices for storing big data: an Array and a Dictionary. I agree that the Dictionary will be more convenient to use. I read on the Internet that the Array takes up less memory and works a little faster (although all I read was that it was written more than 5 years ago). If we take better performance (ignoring the convenience of writing code), will the array be better optimized?
Array (or List) for fast iteration, Dictionary for fast item access through keys. Can have both to sacrifice memory for performance.
Well, I understand that the array will load the system less than the dictionary?
what is load the system less? less memory?
You select them for their utility as this would make the most impact
Yes
Arrays are to hold and iterate finite number of items, List/Queue/Stack same but you need to add/remove items. Dictionary you don't often iterate but fast keyed access.
dictionary use more memory for space-time trade off, if you need O(1) access then you should use dict unless you key is int and continuous eg 3,4,5,6,7....
Ok. I understand. Thanks
in some cases using other data structure maybe faster than dictionary, but rarely.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float moveSpeed;
public float jumpForce;
Rigidbody2D rb2d;
private Animator anim;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
transform.localRotation = Quaternion.Euler(0, -180, 0);
rb2d.AddForce(Vector2.left * moveSpeed);
anim.SetBool("isMoving", true);
}
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
transform.localRotation = Quaternion.Euler(0, 0, 0);
rb2d.AddForce(Vector2.right * moveSpeed);
anim.SetBool("isMoving", true);
}
else
{
rb2d.velocity = Vector2.zero;
anim.SetBool("isMoving", false);
}
if(transform.localPosition.y < -1)
{
Vector2 v = new Vector2(transform.localPosition.x, -1);
transform.SetLocalPositionAndRotation(v, transform.localRotation);
}
}
}```Sometimes the player gets stuck and I need to move in the opposite direction to go in the original direction, why is that?
Could it be that you are not stuck but velocity still puts you in that direction?
Sorry? I don't understand what you mean
By this I mean for example when moving right, sometimes the player just stops and I need to tap left to be able to go right again
Hello everyone,
I am a student and I have a project on unity and I have a problem that I think it's easy to solve but I'm a newbie in this field. Can someone help me with my problem ?
I am creating a 2D platformer avec I have an issue when i paused the game, go to the menu and go play the game, I have a lots of errors like this :
MissingReferenceException while executing 'performed' callbacks of 'Land/Move[/Keyboard/leftArrow,/Keyboard1/leftArrow,/Keyboard/rightArrow,/Keyboard1/rightArrow,/Keyboard/q,/Keyboard1/q,/Keyboard/d,/Keyboard1/d]'
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
But my character can do all moves it supposed (just a problem in my console I think)
Thank you ❤️
(i am not english sorry for my faults)
The object of type 'Transform' has been destroyed but you are still trying to access it.
The first error is a direct result of the second error and can be ignored. Fixing it will fix the other.
You should post the full error message, as it contains a stack trace, which indicates where exactly in your code the error occurred.
Stack trace of the second error
guys do you know what is wrong with this code because im getting a lot of errors
if (transform.postion.y = > deadZone, tranform.position.y = < deadZone)
Yes there is a , in the middle lol
not valid syntax
That is invalid
also =< => operators doesnt exist
i need to remove =?
You type the characters as you'd say them out loud
"Less or equal" <=
"Greater or equal" >=
(equals always last)
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.set_localScale (UnityEngine.Vector3 value) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
PlayerMouvement.FlipCharacterDirection () (at Assets/Script/Game/PlayerMouvement.cs:59)
PlayerMouvement.<Awake>b__11_0 (UnityEngine.InputSystem.InputAction+CallbackContext ctx) (at Assets/Script/Game/PlayerMouvement.cs:24)
UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Utilities/DelegateHelpers.cs:46)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
There we go:
PlayerMouvement.FlipCharacterDirection () (at Assets/Script/Game/PlayerMouvement.cs:59)
Your issue happens in thePlayerMovement.csfile, on line59
More precisely in the FlipCharacterDirection() function
how do i set the deadzone to 2 points for the y? because in my flappy bird game i want the gameover screen to come when the bird get to these to points above and down
Either use trigger colliders or check the y position of your bird in Update
i found to 2 positions where i want the bird to "die", but how do i set those to points as the deadzone?
Like this
Well, do you simply want to check the position of the bird being one of the values of the list?
it's not going to be exactly one of the values in a list
it will be above or below
i already made this but is this the correct way?
if (transform.position.y >= deadZone || transform.position.y <= deadZone)
{
gameOverScreen.SetActive(true);
}
I see, using a simple range does it
No, it's wrong
you're checking against the same position
this will always be true
This condition is true in every case, because of you checking for the position being either the same, greater or smaller
don't you have two positions ?
yes i have -13.5 and 13.5 where the bird is out of the screen and when i want it to die
but why this is just on the console my error cause my character done well ?
something like:
float y = transform.position.y;
if (y > upperDeadZone || y < lowerDeadZone) {
// die
}``` @rustic maple
So you should use a range or multiplication by -1
Errors prevent scripts from running but they still can run before the error happens. So it might seem that there is no problem, but that's not the case
So you should fix them anyway
If you're already triggering game-over via trigger colliders (or will do so) when hitting an obstacle then do yourself a favor and do the same for the "deathzone", there's no need for extra code
So either what PraetorBlue sent or simply multiplying the value by -1 if if max = -min
float y = transform.position.y;
if (y > deadZone || y < -deadZone) {
// die
}
But it's definitely better to use the range.
do you know where I can fixed those cause it's not the flipcharacter() the problem i think
Well it's happening in there, as per the stack trace
but the script doesnt have to know that the deadzone is -13.5 and 13.5?
What do you mean?
if i tell that the y position has to be > than the deadzone and that it dies, how does it know that that only happens when he reaches y -13.5 anf 13.5?
well simple - you write code, such as this. #💻┃code-beginner message
I still don't get it.
yeah i probably make things complicated because i am still new to this
If you want it to be 13.5 or -13.5, you simply assign it to the value.
can i send you a private message to explain you with more details ?
What's the problem of providing more details here?
start a thread^
No, you can just post the !code and the relevant messages here
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't want to polute the chat
start a thread
and than instead of the //die i use my gave over screen variable?
you do whatever you want to do when the bird dies
the game over screen variable is on another screen so i first need them to talk to eachother right
Didn't you already have that part figured out here?
not sure what you mean by "on another screen"
i meant on another script oops
okay i have good news
it works kinda
now when i go out of screen i indeed did something
Great!
but i got the message that the gameOverScreen is not assigned to the script from the bird
because it indeed is assigned to my logicscript for the game over when you die
yep you didn't assign it
Could you show it?
what exactly?
i tried putting public GameObject gameOverScreen; this on top of my bird script
yes now you have to assign it
OOOH
You only did the first step.
Excuse me
Can I get your help please ?
Here I subscribe this class to an event
But that CanvasLoseOpen kept being called constantly
So I called that OnDisable() to unsubscribe it
But then the game said the event is null
Please, don't adress your issue to the particular person. They're not your personal tutor
I'm sorry :(((
But that CanvasLoseOpen kept being called constantly
That would mean you're invoking the event constantly.
But then the game said the event is null
What do you mean by this? If you're getting an error message, share the full message and the line and file in which it's happening
here's the message
ok so the error is on line 57 of Character.cs
now the game over screen pops up when the y are touched, but now i need to pause the game like it does when you die by touching the pipes
cuz now when i go outside the map the screen pops up but i can still play
Yes here the line I highlighted
So what's the question?
can someone point me in the direction for a good tutorial for implenting walking/jumping sound effects? every tutorial is just basically "if walk, play sound" which, sure, but I need it to be way more dynamic than that...
the CharacterOnDeadAction is null
no nothing just sharing 😂
When you invoke a delegate it's safer to do CharacterOnDeadAction.onCharacterDead?.Invoke(this);
if there's no listener it will otherwise throw an NRE.
but thank you guys you really helped me there
Yes yes
Idk why it's null after unsubscribing
that's how it works
That's why people invoke them like this
Oh ...
Idk I had to do that
Well, I've literally explained it to you in our previous conversation
Yes I remember that, but I thought I'm using Action instead of Events so they are different
private void OnCollisionEnter2D(Collision2D collision)
{
logic.gameOver();
croissantIsAlive = false;
}
no they are exactly the same
this is my code for the bird to die when touches pipes
can i just copy that and put that to when he touches the y positions?
Yes, they are different, but are invoked the same way
event is just a keyword that says your delegate can't be invoked except by the class that declares it..
._.
Delegate and Actions are the same but Events too ?
event is just an addon to the variable.
public Action example;
public event Action example2;```
It's a modifier to the variable
it just means nobody else except this class can call example2.Invoke();
Action is a delegate type
it just means "A delegate with no parameters that returns void"
I think they're talking about UnityEvents
could just make it a function..
public void EndGame(){
logic.gameOver();
croissantIsAlive = false;
}``` but yea, whenever player < y position or w/e -> `EndGame();`
If it's UnityEvent, then yes that's different
it works now!!!
Copy and put that? Why not call it?
Okay I think I'm getting a bit hang of these stuff now
Yes, because that's what we were discussion in the previous conversations
i put these 2 logic.gameOver();
croissantIsAlive = false; under this float y = transform.position.y;
if (y > upperDeadZone || y < lowerDeadZone) {
// die
}
The difference is that the Action should be subscribed and unsubscribed, otherwise it will cause you troubles,
private Action yourAction = new();
private void OnEnable() => yourAction += YourMethod;
private void OnDisable() => yourAction -= YourMethod;
while you can simply add a non-persistent listener to the UnityEvent, which shouldn't be unsubscribed
private UnityEvent yourEvent - new();
private void Start() => yourEvent.AddListener(YourMethod);
UnityEvents need to be unsubscribed too..
assuming the subscriber is destroyed before the publisher
RemoveListener is a thing
They're usually simply subscribed to in the Start
But yeah, they should be unsubscribed if destroyed in order not to cause null errors
The same rules apply as with C# events. If the subscriber has a shorter lifespan than the publisher, the subscriber needs to unsubscribe when it dies.
if the publisher will have a shorter lifespan than the subscriber, there's no need to unsubscribe.
I see, yes, the listeners are not removed in the majority of cases
A frequent source of bugs 😉
What are you guys talking about ? @@
About the question you've asked
We're talking about when you need to remove listeners from events and when you don't.
Oh ...
I might need to record this for later uses
Alright, simply note that my previous response wasn't entirely correct. You'll have to unsubscribe the action (or event), if the class where the action is subscribed to lives shorter than the class which has the action.
It is usually so that the actions are always unsubscribed, UnityEvents are just subscribed to using AddListener
You don't need a reference when you don't unsubscribe from the event. In this case you may use (...) =>
Oh okay I got
Thank you
How 2 make 2d button in 3d project with web-link?
I checked some guides but it doesn't works
probably a dumb question, does C# have "if then" statements?
yes
it's not unity question, but yes. if (condition) { ... } else if (condition2) else {...}
i think the then is just the scope { }
if else is different, thanks tho
You really should at the very least start with basic tutorials https://learn.unity.com/project/beginner-gameplay-scripting
if(true)
DoStuff(); // for sinle line instructions
if(true)
{ // open scope
DoStuff();
DoStuff2();
} // close scope, for multiline
How 2 make 2d button in 3d project with web-link?
my question is not being understood but that's fine I'll figure it out
maybe, you ask it in other form?
you may have phrased it inaccurately to what you meant to ask
c#'s if statement is just that
Are you asking about ternary conditional operator?
condition? ifTrueValue : ifFalseValue
I'm losing my mind, I have this code, tag is set up properly, got a rigidbody on the pickup, this script is on the object to be destroyed, my player has a collider idk what is wrong: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttackBonus : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("Collision");
//BulletLife.damage += 1;
Destroy(gameObject);
}
}
}
try ontrigger, just checking for .gameobject without tag, still nothing
This code is on the pickup?
yes
The rigidbody is NOT kinematic?
it is NOT kinematic no
is it logging?
the oncollisionenter does not happen no, got nothing in console, There's other stuff in the project with collision that's fine as well,i honestly have no clue
Im trying to figure out how to have something trigger after a particular if statement occurs, in other languages I used it would just be if then, have not heard of ternary conditional operators so reading about them now
It's just called if in most programming languages, C# included
am I overthinking this and just put it after the if statement lol
yes
LOL ty
try 2 add 2 player child cilinder & add player tag 2 it
these are identical constructs
// c-like
if (condition) statement;
``````py
# py
if condition:
statements
``````sh
# sh
if condition; then
commands
fi
Code runs one line at a time, top to bottom. The if condition is evaluated, then, if it's true, it moves into the block and starts to execute it one line at a time.
If the if condition contains a function, that function will fully complete before it can move on to either execute or skip the block
yeah this was a case of over thinking on my part, thank you
for c-like languages, the statement may be a block statement ({ ... }) which contains other statements
How 2 make 2d button in 3d project with web-link?
2d button as in UI button?
yes
ui canvas > add button?
how do i get the rotation of a configurable joint? In my case im using a configurable joint instead of a hinge joint for a door because the hingejoint was bouncing on its limits even when bounce was 0
it works, but web-link doesn't work
oh, I don't know how. But my logic woudl be to think that depending on OS and hardware / software, you would want to call the default browser of your OS, aren't you?
or we aren't talking about like link to some google. com?
any browser of my OS
Can someone help me with tile maps, i use composite colliders yet it sort of bugs my player out
Thank you
the answer I found by googling, tho, would be something like Application.OpenURL(url); where url is string. I don't know if that actually works though
what do you mean? you just wanna open a link with a button?
uhhhh, i just changed my url 2 www.google.com & it works
oh okay 😄
are you using thios thing here: Application.OpenURL(url); ?
Make sure the URL starts with "http://" or "https://" for it to work properly. <- string I found in documentation
is KeyCode.Space a real thing? what else would i call it
Application.OpenURL("www.google.com");
this works
Have you checked https://docs.unity3d.com/ScriptReference/KeyCode.html ?
that isn't a url, perhaps http is inferred when the scheme is missing
oh
i forgot to add a tag to my gameobject
thats why it wasnt working
my unity editor doesn't think so
not sure what you mean by that
my button can work with that url & works
im just saying that it isn't a url
wait now I am also kinda puzzled. What is it if not url? 🙂
okay, url has to have protocol specified, okay
it's a domain
tf is AltGr
its a keycode
my best guess would be the alt key but whats the gr for
That is the Alt-Graphics key, it's used for selecting keys which are not normally on the keyboard
exactly
cool
does anybody know why when i press my button to restart the game, it did restart but i cant play? i used this code
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
is that the whole thing
wdym by "can't play"?
My guess is you set the timeScale to 0 somewhere and forgot to reset it to 1
i can press the button to restart and it restarts but i cant press space to start playing again
i got this undernead it
Why would you expect to be able to press space to start playing?
one sec
public void gameOver()
{
gameOverScreen.SetActive(true);
PauseGame();
}
public void PlayGame()
{
gameOverScreen.SetActive(false);
scoreText.gameObject.SetActive(true);
Time.timeScale = 1f;
}
public void PauseGame()
{
gameOverScreen.SetActive(true);
scoreText.gameObject.SetActive(false);
gameOverText.text = playerScore.ToString();
Time.timeScale = 0f;
}
no i meant that the game just freeses because normally the game would run again and play
!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.
oh yeah
sorry
{
gameOverScreen.SetActive(true);
PauseGame();
}
public void PlayGame()
{
gameOverScreen.SetActive(false);
scoreText.gameObject.SetActive(true);
Time.timeScale = 1f;
}
public void PauseGame()
{
gameOverScreen.SetActive(true);
scoreText.gameObject.SetActive(false);
gameOverText.text = playerScore.ToString();
Time.timeScale = 0f;
}
// your code goes here
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
public GameObject gameOverScreen;
public Text gameOverText;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameOver()
{
gameOverScreen.SetActive(true);
PauseGame();
}
public void PlayGame()
{
gameOverScreen.SetActive(false);
scoreText.gameObject.SetActive(true);
Time.timeScale = 1f;
}
public void PauseGame()
{
gameOverScreen.SetActive(true);
scoreText.gameObject.SetActive(false);
gameOverText.text = playerScore.ToString();
Time.timeScale = 0f;
}
}
Still nothing here about pressing space
its not about the space its about that the game freezez after i press the play again button
You siad you're not able to press space to start it again
that has to do with pressing space
yeah thats true, i think i mentioned it wrong, because i want to solve the problem that the game just runs after i press the button and not freeses
could someone perhaps please help me normalise my vectors
MyVector.normalized
Did you google it first btw?
then show what you tried and the issue
this.transform.Translate(Vector3.forward * _vInput * Time.deltaTime);
how would i place it into here
just vector3.forward.normalized?
becuase i dont have new vector3 anywhere
Please properly explain your error and share the !code instead of this
📃 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.
Make a vector3 variable, normalize it, pass that into translate
This sounds like an XY problem
Vector3.forward is already a normalized vector
so what are you actually asking how to do here?
Why are you asking about normalized vectors? What's going on? Give some context.
im about to
I'm chill, just asking for clarification.
this is all i have including vectors
_hInput = Input.GetAxis("Horizontal") * MoveSpeed;
_vInput = Input.GetAxis("Vertical") * MoveSpeed;
this.transform.Translate(Vector3.right * _hInput * Time.deltaTime);
this.transform.Translate(Vector3.forward * _vInput * Time.deltaTime);
the issue: i dont know what to do here
What are you trying to do?
Do only one translate call for one thing
fix the xy issue
what is "the xy issue"?
going diagonal is faster than the cardianal directions
Thank you!
i heard normalising is a good fix
now you said your problem
normalizing isn't the best fix
Clamping the magnitude of your motion vector is the best fix
i didnt say best
alright
I am making an Enemy Count Script, this script will check its collider to see how many Objects with "Enemy" Tag there are in its collider2D. The issue I am having is that the collider2D is checking all the colliders of the enemy. So instead of it giving me 3 Enemy Checks, it will say 6 because each enemy has two collider2Ds(One for rough terrain, and another to make sure they don't clump together when attacking the player.) How can I check for only the 1 collider on each Enemy to ensure I don't get multiple checks for each collider2D on the Enemy's?
Apologies, here is the code: cs private void OnTriggerEnter2D(Collider2D collision) { int counter = 0; if (collision.CompareTag("Enemy")) { counter++; print("1 Enemy" + counter); } }
maybe check for a different tag on the Enemy
that might be the simplest fix. see if that'll do
or are the colliders on the same object?
put it on different layer and use Overlap
so where would i put the .ClampMagnitude
or what navarone said
Yes, but I will try to move the terrain collider on another object without a tag.
you cant move a terrain collider
oh yeah they need to be separate for sure, to easier distinguish
does anyone know why this happens? (code used for the main menu in vid)
and assign a new tag on the other collider and check for that instead
tourn off play on awake
in the sound
what is "this" exactly
shot sounds in unwanted places
It works! That was the easiest solution. Thank you!
because i dont know how i would place it in there
unless its as simple as Vector3.forward.ClampMagnitude
but i doubt it
Take all your input and turn it into one vector
You do new vector and do hInout for x and whatever the other one you had for z
Or just do new Vector3(Input.GetAxis, 0, getAxis)
but would i add that after transform.Translate
How should I go about making a Objective Manager that will check it's children to see which are active? I may be making it more complicated then it should be.
The Objective Manager itself doesn't have a collider, but the children do and also have the code I provided earlier.
Well when going back to the main menu and then pressing play , it doesn't load the game properly like you can't do anything, it doesn't load the stuff in that scene
Idk why
to get all the children of a gameobject one by one. foreach over transform
Can you provide an example of what you mean?
No, it of course has to go before the translate
ok
do you not know how to write a foreach statement?
I think so, but I don't understand the transform part. What transform am I getting?
thats not my problem lol
the transform of the gameobject, in this case your Objective Manager
Dw it's fine
I am not understanding what you are saying.
ok. if you put this
foreach (Transform t in transform)
into a script on any game object. it will return the Transform all of the children of that game object
Oh, okay. I'll try that
fixed it , the problemw was that i didnt put the timeScale back to 1 cause when i was in the pause screen and went to the main menu , it was still "Paused"
{
if (Input.GetKeyDown(KeyCode.B))
{
canBlock = false;
didBlock = true;
Block();
}
else
{
StartCoroutine(ShowBlockMissText());
}
}``` so im trying to make a message pop up if the player didnt block the move. but even if i block it that message courtine still beng called.
On one frame you can block, but you don't, so the coroutine starts. On the next frame you effectvely block, but the coroutine is already running
yh your correct i just cant think of a way to fix this as its in update
im stuck in a loop
should keycode b be in a timer
You'd want to start the coroutine if the "can block" grace period expires (when canBlock is set back to false after some timeout)
i have a trigger at the begining of the animation that sets canblock to true and can block to false at the end of the animation.
would i need a timeout if im using animation events
surely once you have started the coroutine canblock should be set back to false
No, run the coroutine in the ending animation event if didBlock is false
could someone explain to me how I could make traffic lights
If the event occurs and the player hasn't blocked, then didBlock will be false
Break the problem down
I don't understand how to make it so that if the player leaves a box collider before the animation for the traffic light ends they get punished
can't you just make it
else if (!didBlock)
{}?
punishment is pending
i will try this but is this what you was thinking
Yup
cheers
Use Animation Event
Guys what is the best way to check if there is internet?
Just ping Google?
depends how complex you want it to be, I've made a few traffic light systems
wont go into a full on explanation but i can tell you its pretty easy
yes make a webrequest, if it fails. No connection
even has an exmaple on this usecase https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Get.html
Great, thanks 🙂
thanks, Been working on a massive laravel project all week and am drained but feel guilty not working in the game. Cheers for that
just could not think
if (!setKillAmount) {
if (collision.CompareTag("Enemy")) {
print("Counting");
enemyCounter++;
} else {
print("Count");
setKillAmount = true;
}
}``` This code is in OntriggerEnter2D. The issue I am having is that I want the "else" statement to take place just after the collision finds no more "Enemy" Colliders. How can I do this?
What's the "goto" for text for a 2D sprite game that exists in the world itself?
textmeshpro
World-space canvas or a proper mesh?
No I know that part 😛
if its only text is ur best bet, if you need things like icons and a whole layout infobox then yea using World canvas make sense
I am using OnTriggerEnter2D and am using the collison.CompareTag. I am adding an int every time it finds a collision with that Tag. The code works but I also want to check when it stopped adding up. How can I do so?
whats the usecase, there is probably a better way
if (!setKillAmount) {
if (collision.CompareTag("Enemy")) {
print("Counting");
enemyCounter++;
}
}``` I want to setKillAmount to true after the collision has found all "Enemy" colliders.
Hmm. No controls for sprite sorting unfortunately.
and where do you track , where is your original amount of the enemy colliders
yes UI deals with sorting differently
I am not quite understand what you are talking about
No I mean't on the Mesh version.
yeah might have to use Z positioning for that sorting
Which makes sense, this is handled by an SDF shader.
UUuuuuuuuugh
Alright
how do you know how many enemies were the correct amount
what is the original enemy count, to compare it to
how will you know "all enemies amount" was reached
Exactly my issue. This code has to be adaptable and I just don't know how to do so. That is why I am trying to check when the Compare Enemy Tag "if" statement has finished.
if the enemy counter is greater than the number of enemies
process the done events```
well you ideally want to keep a list of enemies
if you want it to be modular
a list/array will tell you exactly how many enemies you got
I need some help, i wanna build and this keeps happening:
I don't know how many enemies there will be. Each room will have different amounts and counting and setting a int for every single one is not ideal.
#📱┃mobile for build related issues for mobile devices
I won't know the amount of enemies that the room will have. The code has to be adaptable
exactly why you should use a list..
Maybe you should consider how to evaluate the number of enemies in the room
eg
List<Enemy> enemiesList = FindObjectsOfType<Enemy>().ToList()
int enemiesFound = enemiesList.Count
That wouldn't work as each room is in the same scene. This would check for all Enemys in the scene.
where else are your enemies gonna be..
Are the rooms procedurally generated?
If not, you can populate the list prior to build
If they are, you can differentiate them with some ownership relative to position, trigger event or whatnot.
Room 1 has 2 Enemys, Room 2 has 5 Enemys. The Room Check Objects have a script that has the code I showed. Each Object checks their collider for Enemy Objects and Counts them...
There will be more rooms*
Each room should know how many enemies it has. Add that number to the total count when a room is spawned
if (collision.CompareTag("Enemy")) {
print("Counting");
enemyCounter++;
} ``` Doesn't this do that?
or even have each enemy register itself with the enemy counter when they spawn, on OnEnable
seems very inefficient way to count
IDK what the context of this is
public class Enemy : MonoBehaviour {
void OnEnable() {
EnemyManager.Instance.Register(this);
}
}```
Would do exactly this ^
I'd do something like this
A bool to simply tell you that you're done would still require you to know when you're actually done - no dodging the bullet.
Instead I should Make the Enemy Collision check if they are in the Room Check Collider, and if so then add to the list. Is this correct?
Are the rooms procedurally generated?
No, they are not
Wait a minute.
It respects sorting groups
interesting
yeah thats following the typical UI sorting (hierarchy order)
_>
Consider populating a list through the editor per room and have a counter that evaluates against that list per room.
Sorting Groups will sort sprites by hierarchy order by default too.
good to know, this is my first time seeing it in use 😛
The real answer is probably "transparent materials"
expensive operations
I should just set a max enemy list amount by counting the room myself and setting the max enemy amount. Is that what you mean or am I misunderstanding?
The implementation is up to you but I'd do something likecs player.room.killCount++; if(player.room.killCount >= player.room.enemyCount) //done
Where you simply set the room reference/value when a new room is enabled
I would just keep a HashSet of all the currently living enemies
and once that's empty you're done
Register them like this
What is a "HashSet"?
unregister when they die
A collection
unique collection (can't have duplicates)
The problem I find doing that, is that it will check the whole scene for the Enemy's right?
no that will simply register Enemy to the list
like RSVP to a party, you added yourself
wdym
Your previous image indicates that only certain rooms will be active at any given time.
#💻┃code-beginner message
What's the goal here?
Yes
Having each room keep track of its enemies?
Room Checkers* The Enemys all exist at start.
Make a Dictionary<Room, HashSet<Enemy>> or something then
or have each Room have a script with a HashSet<Enemy> in it
to track its own enemies
Or if the enemies are all disabled at the start then you needn't do anything other than the first example
I still think it'd be fine to docs void OnEnabled() { player.room = this; }Assuming everything is in the scene by default and can be easily referenced.
Unless you've got multiple rooms active at any given time..
I do that already in the Room Checker Script cs if (collision.TryGetComponent<PlayerCollisionScript>(out PlayerCollisionScript playerCollision)) { playerCollision.currentRoom = gameObject; } It is just using OnTriggerEnter2D instead.
Right, what's the issue then? Just make the rooms have an array or list of the enemies in its room.
The integration should be quite simple
if (collision.CompareTag("Enemy")) {
print("Counting");
enemyCounter++;
}``` This is doing that. No? The enemyCounter is adding every Enemy that is found in the Room.
I just need to make a way to have the enemyCounter added to a list.
so I'm trying to understand this tutorial for making a ship game in unity, but I don't understand why they're adding a force to the rigidbody using the existing velocity of the rigidbody.
same with the addtorque they're in the middle of typing, in my mind it makes sense that addatposition would have the rigidbody just work it out
Is there a way to check after a collision has found no more?
they're calculating drag force, which is proportional to the current velocity
hello, I am a complete newbie in coding in unity, but for some reason i decided to do my seminar assigment in it. Everything worked perfectly but now the game doesnt work and just stutters for some reason, is there anyone that could help me its probably a stupid small fix but as i said i am not very good in unity
ohhh, so they're pushing up at the corner and then down in the middle proportionally to the combined amount of up?
not up or down, but against the current velocity direction, hence -rigidbody.velocity
ok I think that makes sense. This is done on the individual "floaters" (the corners for simplicity) but if each floater is running this at fixedUpdate, would it be better to have a fixedupdate on the actual rigidbody run the drag calculation?
I'm not sure what your setup is but if this script is on the player and designed to discover the number of enemies he's met you could probably just set the enemies collider to be ignored after being found once, if you're simply trying to not add an enemy more than once.
You could probably change the enemies tag, disable the particular collider (assuming it's used for nothing else), ignore collision between those specific colliders, disable a particular component that you'd try to get on collision from the enemy, etc
maybe but you'd have to loop over each floater right?
doesn't look like the values change so I guess just *floaterCount it or something
I'm sure when I get around to trying this with my system I'll discover why it's individual XD
That code is on each room checker Object.
Does each floate r have its own Rigidbody or is that the main ship's body
the main ship's one
What about the AddForceAtPosition
I still have that issue though, how can I check when there are no more enemys.
what position is it using?
also I just realised the displacement multiplier changes so that's probably it
also that
yeah the displacement is using the floater's position
same with likely the AddForceAtPosition
ok that makes sense then
and the wave height at this floater
yeah it uses the floater's position on the ship's rigidbody so I get why that is on the floater script
so yeah you'd do a loop over the floaters if you wanted to consolidate this to one script on the main boat doing it all
ok, probably not worth it
Why not just manually populate an array/list from the Editor? Else just add the enemy using a hashset and it's count property would be the number of enemies there are.
Can you explain what you mean by "manually populate" from the Editor?
The hashset will only contain each enemy once regardless of how many times you try to add them
NEVER MIND sorting layers are in Extra Settings
Have an exposed array/list member and drag/add each enemy already in the room to the array or list - assuming they aren't able to change rooms.
pretty handy
That is the simplest way to fix this solution, but will be time consuming in the long run. That is why I avoided that solution.
It's part of the level design process and bug proof
Is there no way to just check that this code is not getting used? cs if (collision.CompareTag("Enemy")) { print("Counting"); enemyCounter++; }
Impossible for physics system determine if some area does not contain collider anymore (in future).
you can use a timer to set time out manually but not recommend
what do you wanna use it for
I am trying to set up Unity with Visual Studio, I have done everything, but when I open C# files in Visual Studio from Unity, it doesn't recognize any Unity function/variable in the code
did you select visual studio in preference?
regen project files
Can you elaborate further?
The common misstep is with the workloads setup where people often forget that you'd have to manually click the unity workload. Other than that, external tools and regenerate.
why do you need to check that?
This is the whole picture ```cs
[SerializeField] bool setKillAmount = false;
private void OnTriggerEnter2D(Collider2D collision) {
if (!setKillAmount) {
if (collision.CompareTag("Enemy")) {
print("Counting");
enemyCounter++;
}
}
if (collision.TryGetComponent<PlayerCollisionScript>(out PlayerCollisionScript playerCollision)) {
playerCollision.currentRoom = gameObject;
}
}
An enemy trigger enter should only be occurring once so why do you need to avoid triggering again?
I have done everything, now I am trying to reset the MEF cache
It worked
MEF cache?
Yeah I searched up my problem on google and a site told me that resetting MEF cache could solve my problem
And it did
That is the whole issue. I don't know how to just have this get executed at start. If I can achieve that, then I can easily make a int called "enemyList" = enemyCounter after it was executed at start
If the player triggers it again, they'll not be tagged enemy so it won't add to the counter
A bit confused on what you mean. But if I am correct you are saying that the Player shouldn't have the code CompareTag("Enemy") occur because it isn't tagged "Enemy". That is correct and is how the my whole system works.
you can let the rooms spawn the enemies then store them in their list/hashset/whatever
How can I see how Untiy Executes their Methods? Like Awake is before Start, Start is before Update, etc
What's the issue then? Unless an enemy walks out of the room and back in, the counter should not increase and those lines of code dependent on the enemy tag will not execute again.
Woops, wrong reply
Meant for @small mantle ^
you can just enter some numbers (of enemies) to the inspector of rooms monobehaviour, done
public class Room:Monobehaviour{
[SerializeField]private int numberOfEnemies;
private void Awake(){
for(int i=0;i<numberOfEnemies;++i){
//spawn the enemies and store them
}
}
}
If you're activating and deactivating rooms and their enemies, maybe consider resetting the room's kill count on enable so that you'll be able to recount the enemies properly?
So, I found the solution because there was no issue. This whole time I thought OntriggerEnter2D would occur after Update method. I was wrong and could have stopped trying to find a solution to an imagined issue. My fault for not testing it sooner. 