#💻┃code-beginner
1 messages · Page 157 of 1
The diagonal arrow is the original vector. The vertical arrow is the result of using Project with Vector3.up
And the horizontal arrow is the result of using ProjectOnPlane with Vector3.up
The result would be Vector3.right.
I added a plane to this imagine because its normal vector is Vector3.up
ProjectOnPlane flattens your vector onto a plane with the given normal vector
So if you add the results of Project and ProjectOnPlane up, you get the original vector back!
@sonic dome so, if you use those methods to split your velocity into two pieces, you can modify just the horizontal velocity, then put them back together
thanks
Vector3 vertical = Vector3.Project(rb.velocity, Vector3.up);
Vector3 horizontal = Vector3.ProjectOnPlane(rb.velocity, Vector3.up);
horizontal = // do something to it here
rb.velocity = vertical + horizontal;
yes i got it partially this is my 1st 3d project i have only worked with 2d ill revist this thing later thank u so much
If gravity goes straight down, you could also just do this
float yVelocity = rb.velocity.y;
Vector3 velocity = rb.velocity;
velocity = // do something
velocity.y = yVelocity;
rb.velocity = velocity;
Project and ProjectOnPlane work correctly for any direction
I think it's also a little more clear what you're actually doing
this also implies that
Vector3.ProjectOnPlane(foo, bar) == foo - Vector3.Project(foo, bar)
Project, Angle, and Dot are really useful.
Oh okk ill save these SS
thank u so much
Hi guys
If Im planning to create a Football Management game, Unity can Help me out with that?
Don't crosspost
Not a code question
Sorr
sorry
In this code here, how does deltatime make it so both players see the same thing?
That's not what deltatime does
It's the time in betweeen each frame
can anybody help me with my time.deltatime position in my code, i cant seem to figure out where to put it so that it fixes my slow camera interpolation
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
mouseXSmooth = Mathf.Lerp(mouseXSmooth, mouseX, 1.0f / smoothness);
mouseYSmooth = Mathf.Lerp(mouseYSmooth, mouseY, 1.0f / smoothness);
rotationX -= mouseYSmooth;
rotationX = Mathf.Clamp(rotationX, -80f, 80f);
rotationY += mouseXSmooth;
float moveDirectionX = Input.GetAxis("Horizontal");
currentRotationZ = moveDirectionX * sensitivity * rotationSpeed;
// Apply the rotation to the player's body around the y-axis
playerBody.rotation = Quaternion.Euler(0f, rotationY, 0f);
// Calculate smooth camera shake
float time = Time.time * shakeSpeed;
float smoothShakeX = Mathf.PerlinNoise(time, 0) * 2 - 1;
float smoothShakeY = Mathf.PerlinNoise(0, time) * 2 - 1;
float smoothShakeZ = Mathf.PerlinNoise(time, time) *
2 - 1;
smoothShakeX *= shakeIntensity;
smoothShakeY *= shakeIntensity;
smoothShakeZ *= shakeIntensity;
// Update currentRotationZ before setting local rotation
currentRotationZ = Mathf.Lerp(currentRotationZ, moveDirectionX * 1, Time.deltaTime * 2);
// Set the local rotation with added camera shake
transform.localRotation = Quaternion.Euler(rotationX + smoothShakeX, 0f + smoothShakeY, currentRotationZ + mouseXSmooth + smoothShakeZ);```
public class MyClass
{
private struct PrivateStruct1
{
public int camelCaseValue;
}
private struct PrivateStruct2
{
public int PascalCaseValue;
}
private PrivateStruct privateStruct1;
}```
Which one? I usually just do camelCase because it's still only accessible in that class, but I'm seeing conflicts with other examples.
its just convention though i tend to do all Types and public things as PascalCase, locals and camelCase and fields members as _camelCase
hmm, alright. I've been slacking on underscore naming. That's a lot of extra effort ;p
well great thing is, consistency matters most and this is just convention so you can adopt what ever you and the team you work with likes and stick to it
an animation event is called only once for every time it plays in an animation right? also, if i want to reference an animation event in another script, how do i do that? like
once animation event in script 1 is called, something should happen in script 2
Call a function in script 2 from the function in script 1
Or fire an event in script 1 and listen in script 2
the animation event will only call on a script on the same object as the animation
how would a fired animation event look then, would it be AnimationEvent(1)? or would something else be in the parentheses
yes, but like, i want to know when it is called. im a coding noob. i basically want a bool to only be true the frame the animation event is called and then be false again
make 2 animation events
one setting this bool to true
second estting this bool to false
📃 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.
but then my animation would need to be one frame longer than it should be, so this doesnt work
one frame longer wont be noticeable
if you want only one animation event
then make it in a coroutine
myBool = true;
yield return new WaitForEndOfFrame();
myBool = false;
hmmm, ill try that
Guys i'm trying to make a mini-soccer game. I'm working on the part where if the ball hits the net it says Goal inside my console but for some reason it's not working. Here are the 2 scripts i'm working on right now. Can you help me find out what's not working? Both the net and the ball have colliders2d.
https://hatebin.com/sqccwgdpsm
https://hatebin.com/arclcpmjmu
I'm very new to c# and i've some experience with C if it can helps
y am i getting this error
?
You're probably missing some braces
Impresive, you managed to obscure the code causing the error
https://gdl.space/uruquhoyim.cs this is the code
rather than just debugging sucess, debug failure
Got it
how do i do that? @languid spire
my compiler glitched and showed the wrong line
Add more debug logs, if the method being executed, what is entering it etc
OnTriggerEnter & OnTriggerExit doesnt work
code: ```cs
public class CollisionDedector : MonoBehaviour {
private readonly List<Collider> _colliders = new ();
public static CollisionDedector Instance;
private void Awake() {
Instance = this;
}
private void OnTriggerEnter(Collider other) {
Debug.Log("Entered");
if (!other.CompareTag("Player")) {
_colliders.Add(other);
Debug.Log(_colliders);
}
}
private void OnTriggerExit(Collider other) {
Debug.Log("Exited");
_colliders.Remove(other);
Debug.Log(_colliders);
}
public bool IsColliding { get { return _colliders.FindAll(collider => !collider.CompareTag("Ground")).Count > 0;} }
public bool IsGrounded { get { return _colliders.FindAll(collider => collider.CompareTag("Ground")).Count > 0; } }
}
isTrigger is set to true in the box collider it doesnt log anything when it collides with something
and the thing it collides do have a collider
I see thanks, i'll try
Rigidbodies?
is it required?
triggers still require rigidbodies
@languid spire problem solved https://gyazo.com/fb6c590650e0e04709c8a76518d8b8f7 i was hiding certain types of messages tysm
ok ty
I am trying to get make a scoreboard, I get the score to go one up, but the next time it hits something it's not going up. Isn't a function supposed to be a loop? How can I fix it?
Should I use;
{
public int score;
void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
score = +1;
}
}
}
}```
?
This is just a raw version of the code to show my idea
@open apex if you find out how to do that bro let me know, i was trying to do that too yesterday
are you messing around with me?
what? i'm for real 😄
hello
Actually, let me double check. I usually just use casting methods myself over trigger colliders but I could be wrong about this.
i am super confused, why does this not work?
You need to set the position itself, you cannot update just a single axes.
So give your gameObject.transform.position = a new Vector3 that includes the new x position you want.
Vector3 is a struct so is set as a value, so you need to create a new vector and pass it all in at once
or save position to a temp var modify x then assign it back
https://gdl.space/elidovicax.cs i have reached the point where i have no idea how to add a jump functionality any suggestions?
Can anyone help me with my code please?
@open apex https://hatebin.com/hizplkljtg check this if it can help. My score is now getting properly updated inside the console
thanks
a function is not "a loop"
a loop is a block of code that repeats as long as a condition is met.
OnCollisionEnter is invoked every time you collide with another non-trigger collider.
Why do you think the score is only going up once? Are you looking at the inspector for this component while the game is running?
hello, everytime i run that code while one of the slotvar isused bool is set to true , my game crash, i dont understand
private void Is private what makes you start a new void inside a void?
by "crash" do you mean that it freezes up?
nothing here is called "a void"
my editor closes itself
void is a type.
it's a special kind of type beacuse you aren't allowed to actually create a variable of type void
Hello, I am new to untiy and I want to learn first person movement, is using character controller better or a rigidbody? also can u suggest a good tutorial to start? I also want animations as I have a model ready in blender.
It's used to indicate that a function returns nothing.
private is an access modifier. It's used to control who is allowed to see a function, field, etc.
exactly as fen said, when you say "void" "int" etc before a function name you're just indicating the type of value the function should return
It also happens to be the default access modifier for methods, so both Start and OnCollisionEnter2D are private.
Both methods return void, so neither of them returns a value
Teleport is a recursive method, so it will crash
An infinite loop will freeze the editor, since the code never finshes running.
Infinite recursion can crash the editor by exhausting the memory used to remember which methods we're calling
so what type of value is "void"
fen G.O.A.T
There are no values for the void type.
void is nothing
it’s not like a real type
void means it returns nothing
yeah i guessed it was the problem, but sadly i dont understand why it is infinite, since the bool have only 4 chances on 6
int f() returns a int void f() returns nothing
4 chances on 6
Guys, this is more like a technicism, but how do I check for OnCollisionEnter() but just for a specific layer of objects?
what if every single slotvar is used?
so why am I not able to start a void inside a void
4 chances on 64 to return true*
so let's say your functions is like private int number() --> this returns an integer 5,6etc -->private void number() ---> This return nothings at all
show a example hard to say what you are talking about
yeah but its not the case so i dont understand why it crashes there are only 4 who are used
There is no such thing as "starting a void"
Cause I have tried to make a reference to the layer I am looking for and compare it to the one of the collided item, but doesn't seem to work at all
void Foo() {
}
void Bar() {
}
You can declare several methods in a class, of course. You just have to declare them one at a time.
-
OnCollisionEnter has an argument of type Collision, which contains a reference to the thing you hit. You can check the layer there.
-
The object has a layer, and the physics system settings can be changed to automatically count 2 layers as not colliding with each other. Which makes OnCollision calls not trigger
-
Colliders have layer override options, so you can make that specific collider not count with colliders of a specific layer.
If you are going to be filtering out a lot of collisions, then you want to use layer overrides or layer collision settings so these methods don’t get called in the first place
so you know how mario maker lets you put 100 goombas all in a little ball, touching each other? That would be 100^2/2= 5,000 collisions every frame. In this case, you would make the goombas not count collision with each other, so physics system doesn’t even call those methods 5,000 times
Ok, yeah. You need at least 1 rigidbody from either triggering object, but you can set it to Kinematic so it wouldn't be affected by physics otherwise. As for IsTrigger on the collider, only one is required and it doesn't matter who has it, but doing this also prevents OnCollision methods from triggering.
understand?
consult https://unity.huh.how/physics-messages for help with specific physics messages
I am trying to make a scoreboard
When the collision happens, the score goes up by 1 only once and the next time it collides it doesn't work anymore,
so I tried to write;
{
OnCollisionEnter (Collision collisionInfo)
{
If (collisionInfo.collider.tag == "Obstacle")
{
score = +1;
}
}
}
But it says I have to define "Oncollision Enter" When I try to make it " Void OnCollisionEnter" it gives me an error.
You've just created a local function
OnCollisionEnter is only usable inside of Update
Unity has no clue this thing even exists. Don't do that.
a local function called OnCollisionEnter 😂
so local functions exist but do not work how you think they do. also they are not a tool for a beginner
actually, this isn't valid syntax in the first place, since this local function has no name
so yeah dont define a function inside a other function
This is correct. Do not try to put the function somewhere else.
Basically I have a proyectile I am want it to just collider with the layers Enemies and Walls; for now I am just searching for the Walls layer, the proyectile is a trigger collider. I am doing void OnTriggerEnter (collider other) {if(other.gameObject.Layer == wallCollisionLayer){}}
unity only sends messages to call OnCollisionEnter on collisions if you have a function called OnCollisionEnter, that takes a Collision argument, and returns void
If you're having problems with the score not increasing, then you need to figure out:
- whether OnCollisionEnter is running at all
- whether you're hitting something with the correct tag
But that "if" doesn't seem to ever be positive for what I have tested
Don't really know why
honestly just spherecast and use a layer mask :)
Have you tried logging other.gameObject.Layer and wallCollisionLayer to see if they are what you expect
Debug.Log. See what the values are for wallCollisionlayer and gameobject.Layer
Log them before the if
Yeah, I have a Debug.Log(other.gameObject.Layer + * / * + wallCollisionLayer); just before the if statement
oh jeez
And what does it print
I might have missed what you wrote
then go back and read.
scroll then and read
They both return Unity Engine.LayerMask...?
you need to learn the basics of C# non of that is valid syntax do not put your collision function inside the update
Don't know how to interpret that
i think you need to be looking at !learn to get a handle on how C# works
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
does it just print out as "UnityEngine.LayerMask"?
if so, grab .value from them
To be fair it's a lot of bs reflection method binding to easy to be confused, but yeah maybe want to brush up on some c#
LayerMask and Layer are not the same thing
you don't have to know about any of that
I am currently following a tutorials, I tried to give a try to the coding on my own first.
write a method with the appropriate name and signature and unity will run it. that's it.
beginnners dont need to know how that is done though, just if they define a function called Update it does what they want etc
Layer #5 corresponds to the integer 5.
A layer mask is a 32 bit integer, where each bit corresponds to whether or not to check interaction with that layer. So a layer mask that only touches layer 5, would be layer mask 64
im confused, i thought animation events are only called once. i have a single frame event in my animation and i want when it plays to add a fixed value to the position of an object. right now however, value is added many times over, even when the animation is only playing once. but if i add a debug log, it only fires once
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I know, but don't know exactly the difference either
because that is 000…000100000
this
i dont know whats the problem but i cant jump and i get and error that says NullReferenceException: Object reference not set to an instance of an object
PlayerGround.OnTriggerStay (UnityEngine.Collider other) (at Assets/Scripts/PlayerGroundCheck.cs:30)
could this be something with my groundcheck script?
and a Layer mask that includes layers 0 and 2 would be equal to 000…00101 = 5
you may have Collapse turned on in the console
that will combine identical log messages into one
understand?
@frigid sequoia download this plugin. It will make your life easier. https://openupm.com/packages/net.tnrd.layertagsgenerator/
Maybe show us line 30 of the 'PlayerGroundCheck' script.
this plugin has code to automatically generate a class called Layer, which contains public consts for specific layers and layer masks in your game
{
if(other.gameObject == playerController.gameObject)
return;
playerController.SetGroundedState (true);
}``` this is where the problem is
So.. which line is line 30?
if...
I'm guessing the if-statement
I have not touched anything from the physics to tell any later to ignore collision with any other, they should be in the default values, I just added a few later mask one of which is "Wall" and is the one I am checking for with this collision
so if I have Layer 5 being terrain, then it will have Layer.TERRAIN, which is automatically 5. And Layer.TERRAIN_MASK, which is automatically 64
yes
Yeah, so playerController is null and accessing the gameObject property threw an error because playerController was null.
I suspect you meant to say you added a layer called "Wall"
you added your own layers to the game?
I just literally made something pretty similar, but with a raycast instead of a OnTriggerEnter for another script and It worked perfectly
yes
then you need to go to project settings, and go define the layers that Wall can interact with
don’t leave that shit default
when i debug it also says that i am not grounded
you will tear your hair out
Project Settings => Physics
there will be a giant matrix of checkboxes with layers
A NullReferenceException (NRE) occurs when code tries to access members of a variable which has no value assigned.
https://unity.huh.how/runtime-exceptions/nullreferenceexception
If X and Y have a checkbox on, then they interact. Otherwise, they do not (by default) without layer overrides.
So just to be clear, when I am declaring variables, can I call a Layer instead of a LayerMask? Cause I don't think it lets me declare a Layer in the script, just LayerMask
No, that isn't built in, unfortunately.
The logic for drawing a list of layers is in there, but it isn't be applied to anything
I believe you can make a custom property drawer for this?
It came up in this server recently
a layer mask is a bitmask
the different 0 and 1 directly mean like 32 separate booleans in one integer
Both layer IDs and layer masks are integers. That's why it's easy to mix them up.
C# won't stop you from doing if (thing.layer == myMask)
because they're both integers, making this a completely legal comparison
So it should be something like... public LayerMask layerMask; public int layer = layerMask.value; or something like that?
LayerMasks can be cast to integers, but are not exactlt integer
No. This will just copy the layer mask into the layer variable
What are you trying to accomplish here?
Checking if a thing you've collided with is on a specific layer?
LayerMask.value wouldn’t make sense to convert to an int representing a single layer
what if your layer mask has anything besides exactly one bit set 1?
To get the index of the layer mask as a layer???
it could be 00010001, 1101111, 000000
There is no such thing.
Dunno I am really confused XD
What are you trying to accomplish?
I don't want to hear what thing you've tried to do to solve your problem.
A layer MASK is not a layer
Tell me what your problem is.
We're way off in the weeds here and not getting any closer to solving your actual problem
Explain your original problem.
this
000…00111 =7 is an integer representation of a layer mask that interacts with layers 0, 1, and 2
Question about "Multi-Stage Objects"
a layer mask is alike an integer for 32 booleans, where each 0/1 corresponds to if that one layer is included in the layer mask or not
(7, not 5)
What was the actual issue?
Ok lets play it slow to make sure we are talking about the same. That think in the corner, that dropdown; those are layerMASKS, right?
No.
Those are layers.
You are picking which layer the object is on
One, singular layer.
Image says that they are layers
The object is on the Character layer in this screenshot.
this way, if I want to filter for specifically layers 1, 4, 7,8,9, 23, then I can make a single layer mask that has those bits on. Then I check vs layer mask, so I don’t need to use 7 if else if else if to check if that layer is relevant
You can't be on two layers at once.
i don't think we need to keep talking about the intricacies of bitmasks right now
he doesn’t understand the difference between layer mask and layer
We'll get there.
Then why the hell does it shows the Layer Dropdown when I am assigning a LayerMask variable for a script in the inspector?
The property drawer for a LayerMask lets you pick multiple layers
you're choosing which layers are included in the LayerMask.
layer mask is 1 int that corresponds to booleans for 32 layers (some combination of those 32 layers)
a layer is just an integer for its own layer ID.
Humans read and use layers. The layermask is the value represented by the layer.
No, this is wrong.
you cannot convert a layer mask to a layer, because the layer mask could correspond to 0 layers, or multiple layers.
you can convert one layer to a single layer mask that describes just that one layer.
A layer index is a number between 0 and 31. It identifies a single layer.
A layer mask can have any value. It identifies whether or not each of the 32 layers is included.
So, every layer has a LayerMask value that determines which layers it can interact with?
I would not say that layers "have a layermask value"
Are you talking about the Physics settings here?
every layer has one specific bit (one 0/1) on every layer mask that it corresponds to
I think you guys are making this overly complicated..
Layer 0 corrsponds to if the rightmost bit of a layer mask is =0 (not included), or =1 (layer 0 is included in the mask)
No it is fine, knowing how this works is actually kinda important
I would strongly advise reading through https://unity.huh.how/bitmasks#bitmasks-and-layermasks if you're at all unclear on what a mask is.
can anyone pls help me with this warning?
well, don't do that
is PlayerDataHolder just a bag of data?
not something that's attached to a game object?
If so, you could just make it a regular class.
it is attached
that link about bitmasks is great, it a good topic to learn about since its not just for layers or even unity. its a common programming thing
If it is attached to a game object, then you must create it with AddComponent, as Loup said.
Monobehaviours should only be made by AddComponent
in that case, just do what the warning tells you to do (:
(accidentally replied)
https://www.alanzucconi.com/2015/07/26/enum-flags-and-bitwise-operators/
Good use of bitmasks beyond layers too
that is a better explanation of layer masks tbh
Guys if i wanted to make a status in a mini-soccer game where the player would enter a kick state in which if he collides with the ball, this one gets kicked away, how should i do that? (Enter kicking state means, i press a button and player is kicking)
https://gdl.space/xojepigiwe.cs can anyone tell me why my rotation feels buggy and freeze? in void LookRot()
The fundamental difference is..
- An index or ID identifies a single thing
- A mask identifies many things
wanted to make it as it is in haxball if you know the game
idk why unity doesn’t already just have a layer enum
no explain
that would not really solve any of this, also would require code gen to deal with user names on things
So basicallyh in haxball you have your player, and when you press space, if you hit the ball you basically add a force to it that kicks it away.
You won't really be needing to know it mathematically unless you're planning to do bit operations - or reading bits.
Being able to differentiate between the types for method calls is likely enough.
ok sounds easy enough, so what are you struggling with ?
do some type of overlapscircle check if you have ball in range and use ur characters forward to kick it
well, the whole process tbh. My goal is to add that kick action or status when i press a button. I'm kinda new to C#
you need to start by chipping away one problem at a time, sounds like you already trying to do 4 different things at once
doing it a kick only on collision will be extremly difficult to get right, I would use a quick overlapcircle to check for ball is in the range (slightly bigger than player) and use that
he needs to know to understand how it is stored, how they are different, and how to go between them. otherwise the physics system will make your life very difficult
Ok, so these are Layers, what is a LayerMask? As far as I know, it is an int that determines which layers it should interact with
yes
I'll check it out 😄 don't know what an overlapcircle is and how it works, ty buddy
and again: this link helps a lot. https://unity.huh.how/bitmasks#bitmasks-and-layermasks
Was that the individuals issue? I'm assuming something was used in place of another.
more or less and it works because of how a int is represented as binary, but masks take all the bits used to define a int but treats them each as a bool
I've been trying to extract this information for a while now...
the initial issue was caused by not knowing how to work between the two. He did layermask == layer, being confused as to why it doesn’t work
that was the start of this
time to learn then 🙂
think of it like an "invisible" circle collider that checks whats inside like anOnTriggerEnter does
except you call it at will
So how should I check if a LayerMask includes a specific layer? This is, I have a LayerMask declared and I want to check if the collision object's Layer is on those that the LayerMask should interact with
Do exactly this.
Hi, is it possible to set the cursor icon to the hand pointing up in unity?
yes
also not a code question
you can also use this plugin: https://openupm.com/packages/net.tnrd.layertagsgenerator/
it automatically generates a class for you that contains consts for the mask corresponding to just one of each specific layer
Pretty sure it is, i dont want to just change it in general, i wonder if its possible to make it point up when hovering over the object
like
public const int WALL = 5;
public const int WALL_MASK = 64;
can also easily just do if (mask & (1 << layer) != 0)
point up when hovering the object ?
Yeah, cursor icon change to hand pointing up when hovering over an object
You'd compare the mask using logical operators:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#logical-and-operator-
i do this when I don’t have a specific reference to the one particular hard coded layer I want. I use the const if I do so that I can backtrack in case I need to change references to that one specific layer
(1 << layer) will take a layer index and make a mask from it, then the & will tell you if the 2 things share bits or not
so use the Function of SetCursor
as the link I sent explains, yes.
0011 & 0010 = 0010, which is not zero.
we're dogpiling dorito with like five copies of the same answer and I have to imagine it's extremely confusing
That seems... more manageable than learning bits, thxs!
just learn bits
Well yeah but is there a specific method to change it to that god forsaken default icon 😭
you should still learn how bits work.. you're using a computer
you also need to learn bits, but it makes life much easier
because you don’t need to get into the weeds that much
wdym default icon? which one?
It is, but I am trying to follow all, and get as much info as I can, which is why I am here, so it is fine 😄
I would highly recommend going through this link, it's got interactive diagrams and everything.
https://unity.huh.how/bitmasks#bitmasks-and-layermasks
(layer mask & (layer mask with just the one bit on for one specific layer) > 0)
this is true => that one layer has its bit on in the mask
you can skip over the problem for now with some utility methods from that library. but the concept of bit masking and bitwase operations is good for any programmer in any context to know
DUDE the hand icon
😱
default hand pointing up
bit masking.. shivers
so just use that image
You have no control over that in unity.. its specific to OS .
layer mask1 & layer mask 2 = a layer mask that only includes layers in both.
mask1 | mask2 = a layer mask that includes any layers in either mask
& and | operators work basically the same as normal AND and OR
So true
that is how you can easily manipulate the bits
Search the hand icon online; download it as sprite, set the mouse visibilty to false, place the Sprite at the mouse position. That's what I would do.
Imagine if you had an item with multiple tags as: Sword, Slash, Fire, Expensive, Metal, Explosive, ect.
How would you develop the logic to check if this item contains at least a Fire tag? Most would loop through it, but with bits you can just compare them and be done.
did you miss this, Ounch?
this allows you to set a custom mouse cursor.
Pay close attention to everything on that page. If you don't read it, the custom cursor will not work.
Yeah i got that, i was wondering if there was a control over it as in the OS
It's really good but as soon as I see bitshift operators I'm almost certain most would be lost, haha.
They'd have to know that their layers are simply integer and the binary representation of their integer.
Guess that's why there are the link embedded to Microsoft docs.
this is the superior method imo, vs the custom cursor
thats basically what I sent with the link..
custom cursor always feels rigid to me
the only way to do it
and i like being able to swap thru different cursors at will
someone was saying that hiding the cursor and applying your own can be somewhat inaccurate
there always is a delay ofc
nah, as long as u line up the graphics to the root's center pivot
No, SetCursor changes your hardware cursor.
It doesn't position a Sprite where the cursor is or anything like that
I know that
they're talking about custom cursor which Im not
making custom cursor Software(delayed) vs Hardware (os)
a gameObject? blasphemy !
I used Shapes to create a cursor in an RTS once
the problem I ran into was that drawing in AfterPostProcess with dynamic resolution scaling is broken, but drawing in BeforePostProcess means that the damn thing gets post-processed!
is that a package?
Yeah. It's a package for drawing nice lines, discs, etc.
Oh nicee, i only knew about GL. Gotta look into shapes sounds fun
I have solved my problem here but I have a quesiton 🙂
The script won't accept TextMeshPro as a "text", in order to fix it I have to remove it and add a text component. But is there a way to use TextMeshPro instead of a Text component?
Oh its third party not Unity right ? found the github I think..
TMP_Text and Text are different
normally you use TextMeshProUGUI or whatever
so if I code it as TMPText it will work?
but TMP_Text is shorter and the base class that will accept any TMP variance
100%
thanks
Just for clarity, there's an underscore.
TMP_Text is a parent type of TextMeshPro and TextMeshProUGUI.
mymyb underscore too
There are differences between non-UI and UI text, but they're not relevant in most cases
so you can just use TMP_Text to cover both
Yeah I saw it on the website you sent
i thought UGUI covered both?
No, UGUI is just for Unity GUIs
I need to name a dictionary that maps "things that make noise" to "loudness of perceived noise"
struggling with a name
intensities sounds more like a list or something
just toss map on the end of the name
perceptions is closer but it's such a general name
AudioMagnitudes
and "Perception" already has a very well defined meaning
The values fade to 0 and get removed from the dictionary, so maybe activeNoises or something..
Don't be clever be descriptive. NoisemakerToIntensityMap
bigNoisesDic
Audio Susceptibilty
true, that works :p
causeToIntensityMap
since it specifically stores "causes" of perceptions
DictionaryOfThingsThatMakeNoiseToLoudnessOfPerceivedNoise
then there you go
This is the ouput but when I put a 0 in the brackets; ToString("0") why does it become a whole number?
Yeah, when the name isn't obvious, fall back on verbosity
Because that's a numeric format that tells it to print a whole number
F1 - F(x)
thanks
ok hmm
heyya! tbh this is my first time coding anything beyond html so you may need to explain any errors to me very simply :,)
i'm creating a dialoguemanager by following this tutorial : https://www.youtube.com/watch?v=vY0Sk93YUhA&t=840s. however i get this error:
Assets\Scenes\Scripts\Dialogues\DialogueManager.cs(111,35): error CS0103: The name 'choice' does not exist in the current context
here is the cs file:
https://pastebin.com/P2b0v5kC
also, i'm using inkly to create a dialogue branch that goes down 3 layers of options, however the dialogue stops after the first set of options are selected. if someone could point out/fix that issue that would help tremendously :)
In this video, I show how to make a dialogue system with choices for a 2D game in Unity.
The dialogue system features Ink, which is an open source narrative scripting language for creating video game dialogue that integrates nicely with Unity.
Thank you for watching and I hope the video was helpful! 🙂
NOTE ABOUT INPUT HANDLING - If you're try...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
follow the tutorial exactly
what do io put in negative and positive button on scroll wheel
when i set my sword's parent as the bone it follows the bone but its not snaping to the exact position 😦
Input.mouseScrollDelta
in the inputmanager?
Ohh the input manager hmm
not sure if mouseScrollDelta is the axis
Just a question
maybe its because i had getaxisraw?
I've made a text where it show how many items you have collected but for some reason when it reached 10 it dissapears
we cannot guess, you need to share !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.
it should work fine with it
I just dunno how to put it in the Input manager
i think unity already did though with GetAxisRaw("Mouse ScrollWheel")
nooooo
read the bot message I sent
don't use screenshot for code
let alone a phone picture.
Ik I cant copy and send it rn
ok do that
why not
Wait lemme install dc on my laptop rq
Use a more appropriate means to post code as suggested by the bot #💻┃code-beginner message
Brb
you can just use the browser version
if you dont want to install 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
When you reach 10, does the entire text disappear or just the number
it diappears because it probably isn't big enough
I'm assuming the string is too long for the display box
just the number
yup rect transform prob too small
Yeah, looks like it's just overrunning the size of the box and can't fit the number. Increase the width of your text box
so if i make it bigger it should be fine?

is there a way in visual studio to move a whole block of code back a tab?
Ty guys
Select the lines and shift tab maybe
Shift+Tab
tysm
think its ctrl+[ and ctrl+] but i could be wrong since i dont use vc code
nah its shift tab
how do I get the rotation of a vector3?
"I dont need it, Im low on cash I should buy it, dont buy it, dont buy it resist the urge, but its on sale!"
What kind of Vector3
these are stupid investments imo
if you need to rotate a vector, you need to apply a rotation operator to it, which is equivalent to multiplying a rotation matrix to it
but its tempting
what happens when something breaks ?
and you dont know anything about fixing it
there are many ways to represent a rotation, but at the end of the day, some sort of rotation operator/matrix is needed to rotate
For future references, these are the keyboard shortcuts:
https://learn.microsoft.com/en-us/visualstudio/ide/default-keyboard-shortcuts-in-visual-studio?view=vs-2022
When it comes to getting a "[Genre] engine" if it's not like $200 it's not worth it. Stuff like UFE are absolutely worth it but they're enterprise priced for enterprise products
Im trying to do some math on a 2D plane, so I need to figure out the local coordinates of a point T given that its on a plane defined by points T, A, B
why you need rotation
true Im just thinking someone who mostly buys it has 0 coding knowledge so if something breaks they're at mercy of Dev Support questions :\
I think they're worth if you're doing quick protos and know how to modify it to your will or at least know if something goes wrong how to fix it
the price is cheap enough to be worth it though
like if I were to have point A be (0,0,0), point B be (0,1,0) and T be (1,1,0) then it would be as simple as removing the z coord
but Im rusty on rotation matrices and stuff
I'm tempted of making one of these Templates myself ngl xD
I assume you do something like take the cross product to find the normal of the plane, but I dont know how to find the rotation of that normal
are you working in 3D, or are you projecting a 3D vector to a 2D plane, and then doing math on this 2D plane, which is not the xy plane
FromToRotation
Quaternion contains methods to apply rotation operators in true 3D. But might not be needed if you are actually in true 2D
I want to project the 3D vector to 2D
not like the shadow or anything tho
I want to find the local coordinates on the xy plane that goes thru the 3 points
Vector3.Project gets a Vector3 projected onto a 2D plane
you can also do the math by hand. Wiki has the very simple math
is it a flattening projection tho?
ya like a1 is multiplied by the cosine of the angle
so there is deformation
a projection takes only the components of the vector that would be in plane
Hello it's me again, I have made a code where when the player gets in touch with an obstacle and it gets replaced with another destroyed version of the player. This creates the illusion of destruction, the code works but it's faulty, it only runs once. when I drop to the game it touches the ground and after it, it won't run again. How can I make it to keep on running until the even occurs?
it does not rotate the vector
yea, I want to rotate the vector ON to the plane in that case
the norm will almost certainly decrease
precisely
then why don’t you project it, and change the magnitude
look at the code it runs only once for a reason, you are destroying the object with this code on it
I mentioned thats not what I want to do 😅
project the vector onto the plane, then change the magnitude to match the original. And you need a special case where the original vector is normal
also this is very expensive, you should just activate/deactivate the destoryedVersion as child
idk how many objs you have but it can easily get very garbage quick
which you’d need anyway
I dont think this will work given what the reason Im doing this math is for anyway, Ill see if I can visualize it tho
that’s the easiest way to do that
are you talking about the point as the vector?
cuz if so its already on the plane lol
there are no points here
you have a 3D vector, and want it to be rotated such that it is in a 2D plane
what you have asked for is projection + rescale
I made it so it's not very expensive
not completely, I want to find its orientation relative to an axis
and how did you do that ?
believe me Instantiating and Destroying objects creates garbage
so I guess projection works, but there is an extra step of finding the angle between it and the axis
that has nothing to do with a 2D plane then
This only happens when the player dies, when he hits the obstacle the game ends. So have everything has to reset
well my points have to do with a 2D plane, the vector is how I align my arbitrarily rotated 2D plane with a 2D plane of normal (0,1,0)
gotcha
also just a more simple implementation if its just a case of turn on and off child objects for the change in visual state
I have a plane passing thru points A B C, I want to find the local coordinates of C
Sorry for bothering you but I do not understand, the game object gets destroyed only when it meets a certain criteria
what do you expect it to do?
idk man. once you can better articulate what you need in terms of vector/matrix operations, everything will become clear
since you're destroying it
you need 3 basis vectors to define that
The obstacle likely doesn't have this script attached to it and you instead destroyed this object
It supposed to get destroyed only when it hits an object, when the game begins it hits the ground and the script runs and then it doesn't run again. It only runs once only (it runs when it's not supposed to)
...sorry Im a little rusty with matrix stuff, could you elaborate
whoops, wrong message
I couldn't explain myself
the local coordinates of anything in 3D require 3 basis vectors to express
Maybe consider destroying the other object colliding with this object
So your Ground is tagged as Obstacle?
no
can those be calculated or do I need to define them
vectors form a basis if they are linearly independent, and fully span the space
thats the only way it would destroy this object
you need to properly define them, at least in the sense of knowing wtf coordinate system you are in
start Debug.Log your collision and the hit objects etc.
if you give me an arbitrary 2D plane, and tell me to get the local coordinates of a 3D point, I will tell you that your query makes no sense
ah, euler coordinates you mean? I have my 3 points defined by 3 3Dvectors already
I have 3 3D points, A B C
I want to orient them so that they are all on the same 2D plane with a normal of (0,0,1)
how do I do that
how? I did this a while back when I was making a 3D renderer
because you still haven’t defined your new coordinate system
how do I define it, point A is at the origin?
if order to change from one coordinate to a different coordinate system, you need a 3x3 matrix
Im staying in euler coords the whole time
this 3x3 matrix effectively contains information for all 3 axes for the new coordinate system
wtf are euler coordinates? that isn’t relevant here
Someone knows why my VSC ide is so buggy? It worked the last week, and now it donts
you are doing a simple linear transformation. but you can’t do that unless it is fully defined
Im sending a desmos 3D graph of what I want
let’s say I’m standing on the plane, and forward is my X axis
i can turn around
different x axis. still satisfies your constraints
different coordinates
therefore your question is ill posed
What's the issue then? Do you get some weird error on the bottom right with VSCode about sdk?
No
Maybe you've missed a step..
i get this tho
And when you go to output?
how do I transform the triangle onto the flat one, given any arbitrary points, A0 is at the origin, and B0 is downwards along the y axis
The git issue tracker on your error: https://github.com/microsoft/vscode-dotnettools/issues/391#issuecomment-1684483731
Yeah, but it worked for me one time, it works and it dont works randomly
okay, i went back and rewrote the dialoguemanager and dialoguetrigger script to a T. this new error comes up:
https://pastebin.com/z6SxWJxy - dialoguemanager
https://pastebin.com/zUfkApAY - eventsystems
Ink.Runtime.Story.Assert (System.Boolean condition, System.String message, System.Object[] formatParams) (at Assets/Ink/InkLibs/InkRuntime/Story.cs:2827)
Ink.Runtime.Story.ChooseChoiceIndex (System.Int32 choiceIdx) (at Assets/Ink/InkLibs/InkRuntime/Story.cs:1785)
DialogueManager.MakeChoice (System.Int32 choiceIndex) (at Assets/Scenes/Scripts/Dialogues/DialogueManager.cs:135)
UnityEngine.Events.InvokableCall`1[T1].Invoke (T1 args0) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Events.CachedInvokableCall`1[T].Invoke (System.Object[] args) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnSubmit (UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:150)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.ISubmitHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:134)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How do i add a AssestPostProcessor to a obejct i imported so i can add a script into that prefab?
make an AssestPostProcessor script
nvm figured it out, needed to modify MakeChoice
how can I sense clicks anywhere on the screen?
depends on the input system, but could just listen for when the mouse button is pressed then its its position
does Input.GetKey(KeyCode.Mouse0) work for tapping a touch screen?
iirc it will but for more info about touces and for multitouch you got Input.touches
also would use GetMouseButton or GetMouseButtonDown
ah
https://www.youtube.com/watch?v=VsSqkfKUZJQ&ab_channel=LEME, does anyone know how to make the background loop infinity like in the game?
Too many death magics have been abused for the decades of wizard war...
The spirit living in nature becomes a demon by remnants of the magics that pervaded it, and it devours all living creatures.
Google Play : https://play.google.com/store/apps/details?id=com.vkslrzm.Zombie
lol, pretty bad censoring job
i tried
Two of your assets show it
Maybe show the complete error?
viewspace -> clipspace -> screenspace using a projection matrix is usually how computers render 3D objects to our screens so you can research into that. As for your question, I'm still not sure what you're aiming for, as to solve that specific problem I'd just rotate until I eliminate an axis.
UnassignedReferenceException: The variable firing of turret has not been assigned.
You probably need to assign the firing variable of the turret script in the inspector.
UnityEngine.Transform.get_position () (at <f7237cf7abef49bfbb552d7eb076e422>:0)
turret.Shoot () (at Assets/turret.cs:47)
turret.Update () (at Assets/turret.cs:37)
Turret line 47
Pretty self-explanatory, you haven't drag-dropped something into the "Firing" of the "Turret" script
It's one of the easiest messages to interpret, the longer you code, the harder they get
And you need to configure Visual Studio so it works with Unity
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
It's required to get help here
sorry my bad
Configure, then come back
okay
If you have any issues about it you can still post here
I have a game object, tower, that stores enemies at an array and then it shoots, but, is it possible to add detections so if there is a wall in front, or some object, it wont be able to shoot?
thats not at all what Im looking for sorry 😅
I don´t know if It´s possible to make it throught detection of the wall or something like that
how can I convert Input.mousePosition into a Transform?
Yes, for each enemy, raycast towards it, and it if does not hit the enemy, something is between the turret and the player
You can't
You don't. Vector3 and Transform are not the same type. What's the real question here?
You can instantiate a gameobject and move it to that position though, I guess
For some reason... probably want to use an offset though for that
Are you using moving cameras?
Wait, I think with that code you dont need to
how do I comment the code in discord?
i think he meant use default transform values and add Vector3 to position
That's your interpretation
Might be correct, might not
Hence why, the real question is what should be asked here
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
Vector3 mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
```
Spr2 was asking for clarity. It may be an xy problem
I'm trying to be able to click on the screen, move the cursor and get a direction value that points from the first click to where the mouse is rn
I think we need to wait for the actual question because I'm pretty sure what happened is a "Cannot convert Transform to Vector3" and they did not understand what it meant
Thats how I made it in a game where you shoot whenever the mouse is pointing
Thanks, im going to see it
So, you store the position the mouse was when you click, and then get the position of where the mouse is now, and subtract them then normalize to get the direction from one to the other
yea
I tried something
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;
using static UnityEngine.UIElements.UxmlAttributeDescription;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private Transform target;
private Vector3 clickPosition;
public Vector3 direction;
void Update()
{
if (Input.GetMouseButton(0))
{
target = Input.mousePosition;
direction = target.position - clickPosition;
}
}
}```
but it's not complete
and it gives an error
What sets clickPosition and why are you trying to set a Transform variable to a Vector3
the first one, I haven't written yet. The second one, I don't know what I'm supposed to be doing.
Why are you trying to store a Vector3 in a reference to a Transform component
I don't know
Just change Transform to Vector3 then
issue here i got these 2 scripts one named turret other BULLET
https://hastebin.com/share/barehakuja.csharp - turret
https://hatebin.com/akzoqmuiff - BULLET
i want for the bullet to spawn at "firing" and follow the "target" untill it hits
but it wont move once it spawns can someone help me fix this isue
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
im not getting any errors issue is in the script
in bullet
in turret
you can further debug your bullet code
need to figure out if it's your targeting or how you're doing the speed
Unrelated but if the literal first thing you do after instantiating a bullet is get the Bullet component from it, why not just make that prefab field of type Bullet and skip that step
i dont quite get that
alright
similar to how you're declaring your variables as transforms and gameobjects
you specifically want to work with the types, so you might as well reference them
since i started this way im going to finish it like this but i will keep that inmidn for the next time
Your bullet variable, should be of type BULLET instead of GameObject. Then you won't need to GetCOmponent the result
it's just ambiguous
benefit of having your fields as their specific types also makes binding stuff in the editor clearer
so you dont accidently bind the bullet field with a type of gun, because you instead wanted to declare the field as a gameobject
i see
guys, trying to do a little experiment after the challenge 1 of Junior programming guide!
I did managed to create a code that doesnt give me any errors, but it just flies to the sky, can someone tell me the error?
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
// making the camera move along with the player
public class camera : MonoBehaviour
{
public GameObject player;
private UnityEngine.Vector3 offset = new UnityEngine.Vector3(1, 2, -3);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
transform.Translate(player.transform.position + offset * Time.deltaTime);
}
}
- !code
- Every frame you add
offsetto this object's position so what you're describing seems to be exactly what you've written
📃 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.
sorry, just joined server. So should I apply it to start instead?
When do you want it to move
its bc in the tutorial it places it in LateUpdate
Do you know what LateUpdate means
after each update
sorry for the NSFW but this is the testing so far
i wasnt able to find anything maybe ou could adress something thta i migt have missed
it did shoot once i dont know how
not really nsfw
only fsome pixels

Hey, I want to write a script that removes all children that are currently active from parent
are a few ways of doing it, if you loop over your transform in a foreach you will loop over all its child items
or could use https://docs.unity3d.com/ScriptReference/GameObject.GetComponentsInChildren.html
to get all child components of a certain type
What exactly a variable being created/declared with => does? "float _var => 10"
im doing brackey's tutorial and this doesnt work for the score counter, im pretty sure its something to do with the text mesh pro but idk what to do, can someone help
looks like a function? a variable and function at the same time? lol
It's a Property
It’s a shortcut to make a getter property.
public float _var
{
get { return 10; }
}```
What doesn't work about it
oh wow I didn't knew c# had these
basically in the tutorial he says to add the text component to, in this case, Score Text, and i literally just cant lol
Text is the legacy “Text” Component. You’ll have to reference the TMP_Text component instead if you are using TextMesh Pro
Is the thing you're trying to drag in an object that has a Legacy Text component?
add using TMPro; to the top of your script, then for the text type use TMP_Text
ohh ill try that thanks
this isn’t a linear transformation
at least not one you can do with a 3x3 matrix
you would need a rotation operator to transform the whole plane about some defined center.
only then can you get the difference in position, and add the vector
yes i fixed it btw, thanks
yeah in general always use TMP_Text instead of the old Text component old one is really only still around not to break legacy projects
Why changing a "get" function I had for a shortcut says there is 0 references?
one of those is a function the other is a property
they are not the same
public Vector3 GetVelocity() => _rig.velocity
how can I check if a child component is active on not
is what you want
I see, I'll read the documentation slowly. Ty though!
you were just missing the () at the end of its name
though a property in this case would be a better choice
I'm just a bit lost about where to use each in this kind of situation
properties are essentially functions that look like regular field access
like public Vector3 Velocity => _rig.Velocity; then on access it would just be thing.Velocity
would anyone like to help
Hello, how do I make one object rotate like the parent object?
Not sure what you mean. You want an object to rotate LIKE its parent? That should happen automatically
Have you shared the code?
yes
here
It does
I didn't realize that the object wasnt rotating just the camera
--BULLET
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BULLET : MonoBehaviour
{
private Transform target;
[SerializeField] private float bulletspeed = 5f;
[SerializeField] private Rigidbody2D rb;
void Start()
{
}
// Update is called once per frame
private void FixedUpdate()
{
if(!target) return;
Vector2 direction = (target.position - transform.position).normalized;
rb.velocity = direction * bulletspeed;
}
public void SetTarget(Transform _target)
{
target = _target;
}
private void OnCollisionEnter2D(Collision2D other)
{
Destroy(gameObject);
}
}
---turret
}
private void OnDrawGizmosSelected()
{
Handles.color = Color.black;
Handles.DrawWireDisc(transform.position, transform.forward, Range);
}
private void FindTarget()
{
RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, Range, Vector2.zero, 0f, enemyMask);
if (hits.Length > 0)
{
target = hits[0].transform;
}
}
private bool TargetIsInRange()
{
// Check if target is null before accessing its position
if (target != null)
{
return Vector2.Distance(target.position, transform.position) <= Range;
}
// If target is null, it's not in range
return false;
}
private void RotateTowardsTarget()
{
// Check if the target is null
if (target == null)
{
// You may want to add additional logic here, or simply return
return;
}
float angle = Mathf.Atan2(target.position.y - transform.position.y, target.position.x - transform.position.x) * Mathf.Rad2Deg - 90f;
Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
GunRotation.rotation = Quaternion.RotateTowards(GunRotation.rotation, targetRotation, rotationS * Time.deltaTime);
}
}
i tried to fix it using chatgpt
but it couldnt find any errors
I summon thee from the depths of hell. Come, Dynobot! Use !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.
Your timer and shoot code are inside the check for target being null
I still dont see any debug logs
Why does this not remove the child component that is active
yess thank youuu
it worked
also that would at best try to move the child to the root of the hierarchy
that wouldn’t remove any components, btw
also that would do is make the parent of that child be scene root
that would just set the i-th child to be in the root of the hierarchy
yes that is what I want to do, basically just unparenting the child and setting it in root
but I only want it to happen to the singular child that is active at the moment
i would debug.Log to see if that line even gets called
that code would do it to all child objects that are active
could break out of the loop if you just want the first one it finds
since there is only one active at the time so all active children works fine by me
but it doesnt unparent any at all
this
also there are multiple ways to check for active
also, if you unparent it successfully, then you will get an index our of bounds error. because you changed the list of children. So you need to break
the one you used would return false if the object was active but its parent was not
how to check whenever a player is holding down a button and do smt when the button is holded
input system
look up tutorials for it
if(Input.GetKey(Keycode.{WhateverKeyYouWant}))
{
//Stuff you want to do
}
maybe I am just trying to do this a really stupid way but basically I have an inventory and whenever I pickup a gun it is added as a child of the inventory. I want that if I try buying a 3rd gun so above my max child limit the gun currently active is replaced by the new one
use OnClick on its button, or a EventTrigger component or use one of the IPointerHandlers
alr thx, i alr tried some stuff but none rl worked im prob doing smt wrong
using IPointerDownHandler and IPointerUpHandler and a Update
Sounds like you can just store the guns in a GameObject list and work with that, as opposed to using the list of children.
Like in your GunManager class or whatever, when you add a gun it parents it to whatever gameobject you want and adds it to a list. When the Gun is removed it removes it from the list and unparents it.
set a bool true OnPointerDown, set it false in OnPointerUp then in Update do what you want to do while the bool is true
bro, use a c# object. Don’t do janky shit in the hierarchy to effectively store data.
that is a recipe for disaster
^ The hierarchy is really for managing the active state of things and organization.
it can work
unless you have an unlimited inventory then you're asking for a scene of gameobjects
of guns
There are a total of 5 weapons that one can get and up to two can be in the inventory at one time
I dont quite understand everything you guys say but ill do some research into the things you guys recommend and get it working hopefully
Thankyouu
When you un-parent the child object, that invalidates your loop and it doesn't even notice. Everything after it shifts down one place, meaning every other child object is skipped
Hello I am currently calling an idle animation in update like this
void Update()
{
if(!playerUnit.IsPlayingAttack && !playerUnit.IsPlayingIdle)
{
StartCoroutine(playerUnit.PlayIdleAnimation());
}
}
Im having a problem with the fact that when I want to play the attack im basically always playing the idle so it doesnt work, if I try and WaitUntil in my attack anim the update always sets it faster
don’t enable him, mao. Using parenting to effectively manage inventory, which requires a lot of querieing, size control, sorting, etc… Doing all that in hierarchy is a really terrible idea
Just use a list
The issue here is that I am using assets from the unity store and those work by adding a weapon as a child to have it be part of the inventory. Maybe ill try changing up the system it self
well, you'd have a manager. The only difference between storing it in data vs having it on the scene is you don't need to instantiate the data onto a gameobject everytime you want to use it
how do you make a value in an inspector seen but like dimmed out and uneditable? i thought private and [serializefield] might do it
You can't disable it without a custom inspector script
so more mem vs overhead elimination, but otherwise for small amounts not really a concern.
and the advantage of having it in a list is the ability to actually manipulate the list. Instead of querying the hierarchy, and doing all sorts of janky nonsense
oh yeah, I wouldn't deparent and stuff, but you can just get a list of all current siblings and keep pointers to them in a list
like, sorting the list, or filtering through, or whatever… that is going to be a massive pain
what he is doing right now is deparenting, parenting, and shuffling around hierarchy, so that the hierarchy has a representation of his inventory, based on the parenting scheme
so you need to go reading the hierarchy to know the contents of the inventory
you need to parent, deparent to move things into or out of inventory
and querying or sorting the inventory is a mess
all this, instead of a list
yeah I wouldn't care too much about how it looks on the hierarchy, you'd just read the pointers from the manager and then child them to the inventory with an Add method
that’s what i’m getting at
again, I wouldn't do this for a large inventory of stuff, but if you wanted to show your side arm equipped to your guy and your rifle (the whole load out), you might as well just keep it all on the scene
the hierarchy exists to maintain specific relationships between gameobjects. Not to store misc gameplay information, like what is or is not in your inventory
imo, my limit for doing that is an inventory size of one. Where there is supposed to be a unique object parented/child
and even then, both will have a monobehaviour to establish and maintain the connection
How do i fix this? it wont let me add a script into a model i imported from blender.
make a prefab from that model, then add the script in the prefab
Hello, i get the " Object reference not set to an instance of an object " error and I dont understand why, when using the following code to create floating damage text popups
Something on that line is null
There's like fifty things it could be
That's definitely a line of code
so the first step is to split that up so you can find out where the problem is
Well, the 0th step is getting rid of the pointless .gameObjects
i think i found that the problem is probably the GetComponent<>() part
but my object has a textMesh i dont understand why it returns null
70% of that line can be taken out if you directly reference the script for Instantiate
GetComponent itself doesnt null its what comes after the ()
And then you dont have to worry about keeping the same structure, where you look for a certain child
Yeah just make damageTextPrefab of type TextMeshProUGUI
Ah, wait, no it's in a child object
how so?
I doubt the parent object is even needed, but does it not work with child objects?
Instantiate returns an Object
using GameObject is kinda useuless
You simply just use the text mesh type and drag it in as a reference. Then instantiate that
Nah, you wouldn't be able to drag in a prefab if it's a child object that has the type
make parent have script and prefab has the TMP reference of child, use a method on that script to do ChangeText
right my bad
wait i dont understand
how should i do that?
personally I would make these a Pool of DamageObjectsText
instantiating a bunch of new prefabs on each damage sounds expensive
oh okay thanks
make the main script on it that controls the TMP_Text
everytime you get from Pooled objects set the text to new damage amount
Ey! Can anyone give me an idea how to make a crosshair that can detect an enemy from afar?
ok ill try thanks for the help
I am trying to detect to change the color.
Ray Cast
!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.
good idea....
And what is the code to detect when the beam is next to the enemy?
wdym "next to"
how would I find the rotation needed to point a vector in the direction of (0,-1,0)?
transform.forward = new Vector3(0, -1, 0)
no, like if I have a unit vector (x,y,z)
how would I find the angles to rotate that vector so that it aligns with (0,-1,0)
I mean some code to detect when the beam is together with the enemy.
you mean when the Ray hits the enemy ?
how do i fix the postion because when the codes start the objectiv is rotated and in the ground. But i fixed the Rotation but i can seem to fix the Position. Can someome help me?
!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.
also you cant make up functions and expect them to work
yea
does anyone know hwo to do this?
have you looked into the documentation how you find the position?
also dont screenshot code next time, use the code formatting / link
ok
if you want only position its
https://docs.unity3d.com/ScriptReference/Transform-position.html
If you're doing both use the former
This doesnt make sense, if you want a vector to be 0, 1, 0 then just assign that as the value
Vector3 has a .angle method
ok, but is it on an arbitrary plane or is it euler xyz angles
wat
https://docs.unity3d.com/ScriptReference/Vector3.Angle.html look at the docs for what it does. I truly dont know what you're asking because you've asked 3 different questions in your attempt to ask one
and I have some arbitrary unit vector
Hey I plan on making a gameElementsManager of some sort to help make designing my game a lot easier. I want to be able to just add from my list of enemies to the scence when I right click on the heirachy window. I want to be able to just add playerElement to the list of playable characters and have it reflect on everywhere with a send of probably provided animations in it's own animation controller. I also want to implement my map generation feature. I have no idea how to start with creating it as I am used to just draging and dropping everything thing into the scence. I need help on an explanation on how to go about with starting to design it or a link to some tutorial could also help
yeah, this is not what I need
Then take a minute to think about what you need. You asked for the angle, I gave you a method for the angle
Ask it in terms of your game, not in terms of code. What are you actually trying to do in your game?
None of this "I want angle xyz euler this that", what is the gameplay mechanic
there is probably a better solution to the problem
but we dont know the problem if you ask solution for Y when you're solving X
ok, so basically, this is going to sound very far fetched from the earlier question, since I have spent the past 2 weeks simplifying the math for this
xy problem incoming 😏
if I have 2 points, A and B, and an initial velocity v, and an arbitrary gravitational acceleration g, with gravitational vector G, then what is the velocity vector to send the object from a to b
B - A
That's the direction between two points
yes I am aware
So you're trying to compute a trajectory? That is absolutely nothing resembling your original question
in before remove an axis and rotate and be done with it all
I can explain
Any one helping? or am I not explaining well. Am i asking in wrong channel?
I did the math, and figured out the equation for the trajectory in 2D
See you've still yet to explain this in terms of your game. You asked another specific question that wasnt your actual need, you got an answer that is correct, then you say no because it's not truly what you need
can you give me TLDR
i hate reading
since a plane can go thru any 3 points, I want to rotate the plane to 2D so I can do the trajectory calculation
I have a launcher block in my game, I see the elaboration youre requesting as completely unnecessary
Want to make a gameElementsManager to manage my whole game. No idea how to start. I should be able to add characters and shit with it
Start by identifying one specific thing you want it to be able to do, and make a script that does that
ask your self Why do you want this in the first place
yeah, call it game manager and make it a singleton
nvm Im going to a math server they can probs understand better what I need
Add a new character and have it reflect everywhere as a playable character? is that possible?
is it that complex explaining a game mechanic you want
leaving aside all the mathy shit you're trying to portray
Pretty sure they want to compute a trajectory from one point to another
it sounds like that Ikr
Making life easier?
🤷♂️ no matter where or who you ask, you're gonna go through the same conversations. You are asking questions, receiving answers, then saying no because it's not what you want.
No I meant it more like "I want script to do this and that" and thats how you. start , you write those functions etc..
well I dont know how to elaborate elsewise my question
Sounds like a singleton that anything that needs to know the player would reference:
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
I have a degree in math, it's not about me not understanding. You haven't asked properly
lol
i need like 12 more credit hours for a bachelors in math but I can't be bothered. Maybe if quaternions start kicking my butt harder I'll reconsider.
Anyways it's better to ask in a unity context because there are specific methods that exist, in a math discord they may just think you are doing all steps yourself
I had the same situation and found 2 few easy courses, along with a upper year calc and linear algebra course. Was really worth it imo but I like math
mind if I put my problem in here too?
ok lol i kinda like that, k one sec.
I probably should have done that from the start, as my trajectory formula is just a long coded equation
(oh ya, forgot to add, using unity's rotation order)
How come you need it by individual axis? If we are talking about any vector at all then sometimes it would be the Z axis you rotate. Anyways you can get this result by doing Quaternion.LookRotation and I guess converting to the euler angles. Although theres no guarantee x and y have values while z is 0.
I dont mind, any axis works really
Better to remake something now rather than continue with a suboptimal solution
Working with eulers are kinda shitty in some cases
So I have this problem that's really bugging and confusing me. I made a door script where if you press F on it, it will play an animation of it closing or opening, I did this using Animator Booleans. This is used by 2 scripts, one which has the method of Opening and closing and then another Interact script which checks if I'm pressing F on something Interactable and if so, it will call the necessary function.
This is the Door Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorOpenFront : MonoBehaviour
{
public bool IsOpen = false;
public AudioSource OpenSound;
public AudioSource CloseSound;
public Animator animator;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Open()
{
OpenSound.Play();
animator.SetBool("Open", true);
}
public void Close()
{
CloseSound.Play();
animator.SetBool("Open", false);
}
}
Tell me if you want a look at the Interact script.
I removed about 40 eulers methods last week and replaced all with AngleAxis if that answers some questions how much trouble I've dug with eulers
whats the problem tho?
I forgot it include it mb, the door can open, but when it's opened, it won't close.
Oh yea AngleAxis exists too
considering you claim you have a math major, could you maybe see if there is a simpler approach to something after all? I have 3 points, being point A (initial pos) point B (target pos) and the gravity vector, and I want to orient all of these points in such a way that A is at the origin, and the gravity vector (normalized) is equal to Vector3.down, I just need the transformed location of point B
please ask away as I seem to be terrible at clarifying stuff
how to you set Open/Close show interact script, send it in a link plz
also SS Animator states/transitions
one second
wait I'm so stupid, I forgot to make the variables change in the function(). Sorry for waisting ur time.
public void Open()
{
OpenSound.Play();
animator.SetBool("Open", true);
IsOpen = true;
}
public void Close()
{
CloseSound.Play();
animator.SetBool("Open", false);
IsOpen = false;
}
at least its working now 😛
hey bawsi would you have an idea of how to approach this maybe?
not for long because now I'm making it open differently if opened from the back.
thats pretty normal to do
dot product is the easiest though
So basically launch an object, and account for gravity so that it lands at a exact destination?
well my 1st attempt failed
...yes, but I did all the trajectory calculation for that, and I would rather stick with what I have for now, its this
more so
yea why's that ?
I don't even know myself. it just wouldn't close when opened from the front.
Unless you are changing gravity direction in your game, then you dont really need to have it as a vector. There are trajectory calculator tutorials online as well for unity. I'm not on my pc at the moment so it's hard to share resources, but googling "unity trajectory calculator" should be fine for whatever the first/popular result is.
Theres also more to consider because you can launch an object at different heights and still achieve the same result. So its up to you to decide what trajectory height you want
yes I would like to change gravity
and I accounted for this, there are 2 trajectories, and they can be controlled by a bool to the input function