#💻┃code-beginner
1 messages · Page 365 of 1
with what method
honestly, if you're not shooting projectiles at 50+ units a second you can use either
I was changing the transform of the player, which held the camera, and then I set the camera to the correct rotation. They conflicted with each other it seems.
Someone gotta write that down.
anyways, is there a way i can have a float[] with multiple slider like this?
in editor
Usually late update solves those issues, but perhaps you were also rotating more in late update
I also got a lighting problem that only occurs in the Build.
so then you probably* had some race conditions on the execution ordering
oop
Yea if you create or find an asset which does this
How should i modify this alpha value?
renderer.material.color = new Color(renderer.material.color.r, renderer.material.color.g, renderer.material.color.b, newAlpha);
Is anyone available for like 3 min? that knows about A* Pathfinding, Ill share screen to make this faster, but I am having an issue where if i have multiple units, and they collide (40 units) they start floating, Im also usin a rigidbody for the colliders
How do I avoid using a RigidBody2D for my TileMap?
private void CheckForEncounters()
{
if (Physics2D.OverlapCircle(transform.position, 0.2f, grassLayer))
{
if (Random.Range(1, 101) <= 10)
{
Debug.Log("Encountered a wild pokemon");
}
}
}
So I can run through the grass as intended, instead of being blocked by the RigidBody
This works, it changes the alpha but the zombie material itself doesnt actually become transparent?
the alpha value 0 means transparent.
Yes the code works gbut the zombie doesnt become trasnaprent
Alpha is 0 but its still visible
post the code so that others can try too.
Could you not just disable the mesh renderer?
I want a smooth fade out
But even in the inspector, changing the alpha does nothing
It would have to be transparent but there are other issues if you make it transparent. Like you'll see the arm render through the body
Well yea there are issues with making it transparent, as I said. Look into other methods like possibly dithering
This would be more of a shader solution
Its really this hard just to make something fade out 😭
I wouldnt call this hard, considering it's just the first thing you tried that didnt work.
what is the rendering mode.
Tried a shader graph too
Transparent
change it to fade.
Rendering Mode? Thought you meant surface type
🤷♂️ well dithering is a common technique. Try again then. Cant really say much based off so little information
i dont know where rendering mode is
apply a standard shader and change it to fade
im in URP
is 20-30k batches a lot
This is a coding channel
Would a coyote timer best be put into void Update()?
Coyote timer is when the player still is able to jump for a few milliseconds after falling from a cliff?
Then yes, you can put it into Update
Gotcha. Still getting acclimated to the Unity API again. Been a hot minute.
it could also be a coroutine
Update makes the most sense though for something like that imo
Shouldnt really matter what you do as long as the solution works. You could even have a float which you store a time which is last valid for a jump.
Actually, I would
- Start a
Coroutinewhen falling from a cliff, which waits for the specific period of time. Once the time has passed, thebool canJumpis updated tofalse - When the player enters the ground, the
Coroutineis stopped andcanJumpis updated totrue
Gotcha. Yeah doing something simple. 0.0 on ground with += Time.deltaTime and then a check for amount of time passed.
I really wouldnt go with a coroutine here. You're likely checking if the player is grounded anyways, during this same check you can just store a float saying what time is still valid to jump. Like Time.time + someAmount.
Ye. I like that approach because it's pretty universal and not spaghetti.
Coroutines are never spaghetti 
hey can someone please help?
It's a static method
Wasn't referring to courtines specifically. I respect what they bring to the table.
meaning?
so you just do Color.HSVToRGB(...)
new Color() is to create a Color object
you don't want to do that
you just want to call a static method
ohh so no new needed
new is only for creating objects
hmm im getting this error now
() ?
Static methods don't have an instance of the class created. Instead, reference the class to access them directly
I showed example here
sorry im very very new
Now you're kinda stuck between accessing a static and non-static variable
I'm mostly rubber-ducking here but I think this would be the spot where I run the check for the coyote timer, yeah? Not currently worrying about double jumps at the moment for it, just my jump count leaving a ledge. If jump count = 0 and coyote timer is not equal or greater than "insert value here"?
if is a control flow statement for making decisions based on conditions, while boolean is a data type representing true or false values.
An if statement evaluates a condition. That evaluation returns a bool (true or false value). if it is true, it executes the code in its body. If not, it does not
in other words boolean is a variable if is a statement
you should do some c# basics tutorial, outside of a unity context. Theres good resources out there like the microsoft learn site or really anything free. This is stuff you'd really wanna do hands on work with to experiment what they do
Yeah i was looking at some Code Tutorials haven’t really got experience with unity
But i want to become Game dev
I learned Blender past 2 months
Now coding 💀
theres a decent amount of learning that needs to come before just doing unity, yet a lot of people skip the basics and suffer the same. Id say once you're familiar with classes and can solve basic data problems, you probably have enough of the basics.
just so i can put it into perspective, a blender comparison would be giving someone whos never used a computer blender and told them to make a full character model.
Which. Videos do you recommend
For starting
I know the ui and Where i Can find all the stuff
Know some of the small basics
That’s Hard XD first thing i tried and then i realised you Need to start small
And That’s how i started
Havent seen a beginner tutorial in probably 8 years by now. for c#, microsoft has a lot of videos but i havent seen them, they are recommended a lot. https://dotnet.microsoft.com/en-us/learn/csharp
w3 schools is decent and has an interactive website. Very small "lessons" per page too https://www.w3schools.com/cs/index.php
otherwise for unity specific, there is the !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Oh really?!
Didn’t Even know that
I am going to take a look but it is early so i am first going to eat lmao
The Junior programmer coarse:O
Hey guys , what's the best free course for unity LTS
Just start with the courses pinned in the top right.
Color does not have an empty constructor. https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Color.cs#L36
You want to use the static method like they specified: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Color.cs#L303
Alternatively use a constructor that takes the correct arguments. This does not work properly for your use case due to convertion, though.
Next time you encounter an error when you expect it to work, you can often Google Unity's source code like with this
Doesn't apply to everything, though
i'm following Brackey's tutorial on the first person camera movement, this Mathf.Clamp here is setting my camera rotation to 90 whenever i start the game, this means that the camera will look down.
If i start moving my mouse then the script will work as intended but i need a way for the camera rotation to start on 0 and not 90
you want it to not move at all?
i need the x rotation to START on 0, sorry
ok then just change that in the inspector? also remove the * Time.deltaTime
nope, won't do, because in the very first frame the rotation gets set from 0 to 90
try removing the deltaTime and see if that changes anything
didn't change anything
ah actually, maybe its that line where you set the rotation do = Quaternion.Euler(0, 0, 0); instead
in Start
i added it hoping it would fix it, but no, it's useless actually, because even if the rotation gets set to 0 in start, t will be set to 90 in the first update loop
Does your object have parent?
code looks fine i guess, how is the hierarchy setup? maybe something wrong with that
I don’t think that will clamp to 90
Maybe just look into using cinemachine which is a premade camera controller and will be miles better than anything any of us write. Brackeys code is very.. not good.
ok, found the solution... this might be an editor only issue, if you start the game in the editor and keep the mouse pointer above the game windows, then the rotation will be ABOVE 0
this means that the starting rotation of the camera is dependant on the mouse cursor position
Theres definitely more issues than just that, if what you described is one.
alright, sounds like a solid idea
Just a side note, mouse input shouldnt be multiplied by delta time. And same as what gr4ss said above, you shouldnt be directly setting values xyzw of a quaternion (which was done in start) These arent euler angles, so the quaternion you had there was actually invalid
alright, i see
Hi my name is ikmal .. can you help me solve this problem ? im using playerprefs to save and load stoned to others scene .. this game have 5 level and need to collect 1 stone from each level before can colllect the stone player must collect all the calorie then the stone can be collect and go to next level .. after collecting the stone player can see all the stone at others scene name "pyramid stoned" the problem is only 1 stone level 1 save and appear at scene pyramid stoned the rest dont appear .. in debug say the state is same for all stone ..how to solve this?
You can see the script below
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.
Can you show the logs?
Put a comma and the variable stone after the logs in set stone visibility.cs Debug.Log("...", stone);//Example
Then click on the messages in the console and see which objects in the scene are highlighted.
Single click
FYI PlayerPrefs persists across your levels
It’s not like they have separate save per scene
Do i need to separate save each level so they can display all collected stone?
If you want to save per-level per-stone then you need unique key as combo of those
Or make proper save file system
PlayerPrefs are not for savefiles in the first place
hi, I want to ask for help I am trying to add some kind of recoil to my script so the bullets dont travel in the same direction, any ideas on how to add random offset to the bullet so it goes a little bit to the right or left(that would depend on randomization) https://hatebin.com/aadainnaea
You have to fix all compiler errors before it appears
Find what?
Open the console
The script is missing the using UnityEngine.SceneManagement; statement
Configure the !IDE so that it shows the errors while you're writing the script
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
hi guys, i have this script which is attached to my coin prefab which gets spawned with my "Spawner" empty GameObject, which is executed every two seconds, the script is meant to destroy the Coin everytime it collides with an object with the tag "Player" but does not work.
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class collisionCheck : MonoBehaviour
{
public GameObject coin;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Destroy(coin);
}
}
}
nevermind, turns out isTrigger wasn't on
works now
If this script is on the coin you can just do Destroy(gameObject)
it gives me an error everytime i do that, so i just did what i did instead
I have a 2d enemy sprite navmesh, how would i make them jump over a gap instead of just gliding over the gap? No special animations, just up and down
I want to see them go up and down rather than just 'walking' over the gap
What's a sprite navmesh?🤔
What? A character is a navmesh??🤯
Do you mean a "navmesh agent" perhaps? Because navmesh is the thing that it walks on.
Yeah
Ok, well, you could use trigger colliders to detect when you character gets close to the gap and execute a jumping animation.
its possible to change size of cube to match camera viewport size? what I want to cube always be inside viewport facing only one side
match size of face 1 with camera viewport on 2
Hey guys! Trying out the unity beginner course and decided to mess around with the prototypes given, but I keep coming into some clipping issues with the boxes. I was just wondering why this happens and how to avoid it in future endeavors.
Apologies for the lack of a gif or video, I have no idea how to record, fit and upload that onto discord
My guess is that you move the truck without the Physics methods, but without code its hard to tell.
Can you post the !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 did indeed, I just put a simple transform script without a physics method since I didn't know how to use one and wasn't shown on the course. I shall go ahead and look up how to do that! Thanks a bunch
Transform scripts don't work well with physics. You need to use the physics methods otherwise you get things like this. Or bullets that go through walls, stuff like that.
Gotcha, I have no idea on where to start understanding physics methods but I shall try my best! Any advice on where I can start learning them?
just look at the documentation for Rigidbody.velocity/Rigidbody.AddForce
https://learn.unity.com/tutorial/intro-to-the-unity-physics-engine# for some background info. But yeah, those Add Force/Impulse etc methods are what I meant.
Thanks a bunch!
is it super hard to add a save game function
Yes, it's possible to change the size of the GameObject to match the camera's viewport size.
Orthographic
For an orthographic camera simply calculate the height by multiplying the orthographicSize by 2, as this is the camera's half-height. Then calculate the width by multiplying the height by the camera's aspect ratio.
As you may notice from using the orthographicSize, this won't work properly with a perspective camera.
float height = camera.orthographicSize * 2,
width = height * Screen.width / Screen.height;
transform.localScale = new(width, height);
Orthographic & Perspective
To calculate the perspective camera's size, which also works properly for an orthographic one, you have to simply calculate the difference between the world space points and use some mathematical multiplication formula you should have learned at school, which tells you a - b | x - y => a = b * x / y. In our case a is the world space scale you want to get, and the division by y is not required, as this is simply Vector2.one - Vector2.zero = Vector2.one in space coordinates.
float cameraDis = transform.position.z - camera.transform.position.z;
Vector2 dis = GetPoint(Vector2.one) - GetPoint(Vector2.zero);
value.localScale = new(dis.x * Screen.width * sizeMutliplier.x,
dis.y * Screen.height * sizeMutliplier.y);
Vector2 GetPoint(Vector2 value) =>
camera.ScreenToWorldPoint(new(value.x, value.y, cameraDis));
You can also create a static method in some Extension class in your script, and access it when required.
SetCameraSize(transform, Camera.main, Vector2.one * .5f);
In this case, transform's localScale is modified according to the Camera.main's viewport, and it fits 50% of it. In your case, it should be 100%. You can also extend the method by adding overloads.
it's as hard as you make it. At a minimum it's 2 lines of code
herm
private void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (!isJumping && distance <= lookRadius)
{
if (!NeedsToJump())
{
StartCoroutine(JumpAcrossGap());
}
else
{
agent.enabled = true;
agent.SetDestination(target.position);
}
}
}
private bool NeedsToJump()
{
RaycastHit hit;
bool isGroundBelow = Physics.Raycast(transform.position, Vector3.down, out hit, groundCheckDistance, whatIsGround);
return isGroundBelow;
}
what in this code would cause my enemy to continously jump?
show code for JumpAcrossGap
private IEnumerator JumpAcrossGap()
{
isJumping = true;
agent.enabled = false;
Vector3 startPos = transform.position;
Vector3 endPos = startPos + transform.forward * jumpDistance;
float elapsedTime = 0f;
while (elapsedTime < jumpDuration)
{
float progress = elapsedTime / jumpDuration;
float height = Mathf.Sin(Mathf.PI * progress) * jumpHeight;
transform.position = Vector3.Lerp(startPos, endPos, progress) + new Vector3(0, height, 0);
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = endPos;
isJumping = false;
agent.enabled = true;
agent.SetDestination(target.position);
}
I don't know if it's just bad naming, but now it reads "if the enemy doesn't need to jump, jump across gap"
It is bad naming, needstojump returns whether there is ground below and !NeedsToJump is if there is no ground below
Poor naming
how about calling it IsGrounded?
if (!IsGrounded()) {
// Jump!
}```
Just did that now
But still need to figure out why its constantly jumping
you can mix them. performance depends on how the code or visual script is written/setup and its complexity. you won't know until it happens. then you profile and optimize when needed . . .
What exactly is the situation where it's jumping when it should not? The code tells it to keep jumping as long as it's within lookRadius and there's no ground below
so it's constantly jumping across gaps?
Im just writing code to make it jump across a gap, so when there isnt ground below it should be jumping across the gap
Just constantly jumping, not just across gaps its just bouncing
Have you checked what NeedsToJump returns when it's not on a gap?
Why it is throwing this error??
please do not post photos, use screenshots
Ok
this is terribly hard to see or read. please use a screenshot . . .
Okk
Because there is even no condition
is not a condition
Use at least true or false
ifn't
It's error about )
yes, because that's bogus syntax
you are not permitted to write an if statement with no expression inside of it
look at a tutorial for "c# if statement" and you'll learn why . . .
the compiler sees if followed by a (, so it's now expecting an expression, like true or 3 < 5. but you just gave it a ), which is not a valid expression.
I have written
As people been telling you if() isn't valid code. You need to learn how to do if statements in C#.
did you read any of the messages that everyone responded with? they explained what the problem is . . .
Sorry
You can always look at the documentation to see examples too:
https://docs.unity3d.com/ScriptReference/Input.html
but the screenshot is great. very acceptable over a phone grab . . .
Ok I got this now
Im gonna switch to using colliders instead of raycasts, feel it'll be easier
if you want to check for ground colliders in a volume, use a Check* query
like Physics.CheckBox
this will be significantly simpler than responding to collision or trigger messages
Could you explain a bit? I dont understand
Nevermind there is a far easier way to do this jump thing
Which you haven't even explained
Well.. I got it working
i want to make it so when im dragging a object it can build momentum and would get flung when let go any ideas?
My player has some animations. When I move or run or crouch the animations affect the camera as well. How can I make it so the camera still follows the player but isn't affected by the animations? My game is a FPS btw some one please help.
i dont know hookes law
i thought that was for like suspension
im a bit confused on k
im going to send my code so you know what im working with
!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.
A spring applies more force as you stretch it further
If you double the stretch, you double the force
Does this object have a rigidbody on it?
ah, it does, given the code
yes
rb2d.AddForce((mousePos - heldObject.position) * 6f);
rb2d.velocity = ((mousePos - heldObject.position) * rb2d.mass);
Just get rid of the velocity assignment and this should be fine
This applies more and more force as the object gets further away
you're currently setting the velocity every frame (using the mass for some reason?)
so the force you apply doesn't do very much
Also, consider moving this into FixedUpdate.
wait should i move all the code into fixed update?
At least the part that is applying forces.
I would keep the part where you check if the mouse is clicked in Update, so that it runs every frame.
ok will this work even with me moving the held object to the cursor
Physics2D.Raycast(mousePos, mousePos);
this doesn't make any sense
this is shooting a ray from mousePos...in the direction of mousePos
so it'll shoot a ray away from the center of the screen
Use Physics2D.OverlapPoint to check if your mouse is over something.
Also, this code checks for the object every frame, so you'll lose your grip on the object if your mouse goes off of it
You can use Input.GetMouseButtonDown(0) to check if the mouse was clicked this frame
i dont really know to make it head towards the center
you shouldn't be using a raycast at all
Hello, I am looking for advice on programming a capture-the-flag, strategy type AI. Been researching into behavior trees, FSMs, utility AI and a couple of others, any advice on which the "best" or generally most accepted one is? thx
You will want to give the rigidbody some drag, yes
Otherwise it'll oscillate back and forth forever
I guess there isn't a best, but could you please review these
Have you used them before?
How did you implement them?
Unity doesn't have a behavior tree system
Animator?
I imagine there are third party packages, though
I, not so long along made a capture the flag RTS using Unity ML agents. The results were amazing
ML agents? Sorry I don't know what that is
The first thing that comes to mind is a state machine to control high-level ideas (going for the enemy flag, attacking the enemy flag carrier, defending the flag) and then behavior trees to implement those ideas
It's the Unity Machine Learning system
Also how would I implement behavior trees?
I haven't done them in Unity (yet). I am actually looking at that right now though.
what should i do instead of a raycast to find the object to hold
Didn't know that existed, cool. How long did it take you to cover the API and program it?
actually, this is wrong
i forgot about Muse Behavior!
(which is only loosely tied to Unity's generative-AI Muse ecosystem)
the name is very unclear
use Physics2D.OverlapPoint
honestly, 5 minutes. To get it to 'learn' what I wanted it to learn in the way I wanted, months
a raycast is unnecessary to detect if you have clicked on an object in 2D physics
Super cool, I'll look into it thanks
you aren't shooting a ray from the camera at the object. it's a 2D system.
yeah
What is Muse Behaviour?
Can't find info on it
It's pretty new.
Is it an extension?
(and it's remarkably hard to find it when searching...)
so uhhh
the thing is that it's barely tied to Muse
you can just ask it to (try to) generate tree elements
by not setting the velocity every frame...
That's cool, thanks. As for the behaviour trees, how do you implement the pattern?
if you don't want gravity, turn off gravity
wait really? physics2d.overlappoint should be used instead? what is the difference?
i kinda want it to be like the potioncraft drag system
Is it switches/if statements
a 2D raycast is not fired from the camera into the scene
no i like the gravity i mainly want it so i can like fling it across the screen
Increase the amount of force you apply.
A behavior tree is basically a sequence of operations
The tree is evaluated from left to right.
but what im doing is im setting it to a position over and over?
Yep, this is what worries me, sounds like it would be unreadable by the end of it
so a very simple tree could be:
- move to target
- attack target
The first action runs until it succeeds, then the second action runs
but is there any benefit to using one over the other? either functionaility or performance wise
At least with a FSM or Utility system it's very organised in a sense
Show your current code.
they're two completely different concepts
a OverlapPoint finds all of the colliders that touch a point
Raycast2D is finding all colliders along a line
I don't know how Raycast2D behaves if you give it a length of zero
heldObject.transform.position = mousePos;
well, don't do that
which is why you're applying force
to move the rigidbody
Hello, i have a script in ZoneTime and I want to collect the boolean in the scrpit in Paterne Hole & Enemy 1. Do you know how to do ?
You need to reference the component on ZoneTime
i always thought to click on objects in 2d you just fire a 2d raycast from the camera like you would in 3d. what if your objects have different z values, does overlappoint get the one in the front like a raycast would?
How would you fire a 2D raycast from the camera?
a 2D raycast has no Z direction
the raycast is entirely in the XY plane in which 2D physics is being simulated
its not going directly to the mouse tho
sure, because you have gravity turned on
so it falls down
@summer stump You reacted to my message, so anything to add to what I said? Truthfully I don't really understand how to implmenent a clean, behaviour tree in Unity, asking here before I delve to research. Any advice?
wait what happends if i turn off gravity
cause like i like the falling
Pretty much nothing comes up when I search Unity behaviour tree
i want the gravity tho
My player has some animations. When I move or run or crouch the animations affect the camera as well. How can I make it so the camera still follows the player but isn't affected by the animations? My game is a FPS btw some one please help.
then don't turn it off
Behaviour trees can be organized cleanly, and one of the issues with FSMs is that when you increase the number of states it gets very complex fast with all the transitions.
That is a reasonable idea.
it doesn't work even with 0 gravity
Yep, agreed. They are very finite indeed xD
You're going to need to be much more specific than "it doesn't work"
Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
this does not fire a raycast from the camera
a 2D Raycast does hit colliders that it starts inside of
so this will probably work
oh, i thought it did because it looks almost exactly like the 3d raycast function, which does 🤯
both of them fire a ray from wherever you ask them to
notice how you're not using the camera's direction at all here
yeah you're right, in 3d it would be transform.forward or something instead of vector2.zero
you're immediately dropping the object
as I said earlier: you should use GetMouseButtonDown to check for an object when you click
im holding the mouse button tho
by getting rid of it
done its gone
https://ktmarine1999.medium.com/behavior-trees-in-unity-20a738b5508c
Opinions on this implmentation?
how would i do that
Seem complicated and an effort to learn, so making sure it's worthwhile
wait so if your objects can have different z values in 2d, do neither methods work? because they both check z 0 only?
Collider2D hit = Physics2D.OverlapPoint(mousePos);
that's it.
2D physics mostly ignores the Z position of objects
I know that you can use depth to do filtering
I haven't used that before.
Although the Z axis is not relevant for rendering or collisions in 2D, you can use the minDepth and maxDepth parameters to filter objects based on their Z coordinate. If more than one Collider overlaps the point then the one returned will be the one with the lowest Z coordinate value. Null is returned if there are no Colliders over the point.
oh ok, so by default it always returns the object with the lowest z like i expected it to, thats good
yeah making a behaviour tree is worthwhile for any game.
okay so ive changed the raycast to the overlap point
and changed where i use the raycast collider to overlappoint
Any advantages to the other apporaches?
but i like the gravity
FSM, Utility AI
fine
it depends upon how you will make that tree.
so when its being held
Well that's the point of me asking here. I was asking about implementation, never done this pattern before and I would like suggestions on how to achieve a good implementation
do you know what a behavior tree is
Don't forget Goap and HTNs, if you're gonna include Utility
i know fen. its used for Enemy AI.
GOAP mentioned 🗣️
how do i enable gravity when its done being held
hi! how do i make a reference to a prefab on a script which isnt instantiated at the start of playtime?
it depends upon your programming thats what i can say.
You need to store that reference when you instantiate the prefab
then give it to whoever needs it
By dragging it in? A prefab can be referenced by another prefab
or if you're trying to reference the original prefab, then yeah
just drag it in
the script isnt on a gameobject either, both are just chilling in assets
I believe my programming is fine, especially when I have a good idea of what I am supposed to be programming; hence my question and purpose of why I am here
i know how i just think i need to move some things
I haven't heard of HTNs before. It looks like GOAP with some extra finesse
now that I think about it why doesn't unity discern between prefab and gameobject?
Ooh, I like the look of this
they should make prefab inherit from gameobject
prefabs are game objects
they're an asset that stores a game object
prefabs don't exist in the built game at all
Because I find very little resources on Behavior Trees in my searches, it's supposed to be "the most versatile" solution yet it seems no information I can find is credible and no one here really knows much about it either
what i mean by this is that i cant drag it in because this is how the inspector looks
prefabs aren't attached to a scene, gameobjects are
This is not a prefab
This is a script asset.
which is a difference
It is not the most versatile solution
so perhaps prefabs aren't fully gameobjects and could be abstracted
Hello guys I need help, I have this patrolling script in which enemy will go from point to point and when it comes to last point it will just stop. I want my enemy to go back to the first point and start looping and I also want my enemy to face where the point is because now he will just walk backwards to the point that is at the back of him for example. This is script: https://hastebin.com/share/abuwegolov.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Prefabs are literally an asset that contains a game object, so...
I'd agree, I read that on a reddit post comparing them. Again, rubbish source of info
The .prefab asset file contains a gameobject
i know, i want to make a reference to a prefab inside this script asset that isnt in a prefab, thats what i meant, srry if i explained it wrong
it would reduce confusion for many if prefabs were different from gameobject
You shouldn't be assigning anything here at all
That makes no sense honestly
Prefab is a file extension
a lot of people I helped kept trying to change the position of a prefab rather than the gameobject they instantiate
The default values here are strictly used to give default references when adding a component
@summer stump @swift crag Thanks both of you still, for giving me leads like GOAP and HTN
If you have any other buzzwords lmk
plus I don't understand why someone would instantiate an object already in a scene
because you want to copy it?
you can instantiate any unity object
ima go
what do you mean by default values?
You are inspecting the script asset itself. This is not an actual component. It's the blueprint your components are made from.
Behaviour tree is simpler than the others, but a bit more versatile than an fsm.
Once you get to utilitit, goap, htn, it is a lot more complex and difficult to set up.
That is what I would say about it. Behaviour tree has the benefit of simplicity but still quite versatile and allowing complex behaviour
GOAP took me several tries to "get"
I am very interested in this HTN idea now...
oh i just totally missed the bubble reference, i dont know how i didnt see it
so instead of every task being a primitive, atomic thing, you can have tasks that expand into several sub-tasks
ty fen and aethenosity!
Currently, most of my atsks are just activities you can perform
like, literal one-to-one correspondence with buttons the player can push to trigger actions
save for "move to entity" and "move to position"
Utility AI seems more simple, relies a lot of having numerical values to determine the priority of tasks. I feel like that could work well with an overarching FSM, so you have States like "Fleeing", "Engaged", "Advancing", then Utility AI inside those states to priorities tasks
goap was lot interesting few years ago.
yeah, it's what I was using previously
I decided to try GOAP beacuse of a very obnoxious situation
I accidentally made it so that the enemy was more interested in approaching the player than attacking the player
So they'd just get up in your face and...stand there.
with GOAP, the enemy approaches you as part of a plan to hurt you
Lmao, so basically it didn't work, GOAP is the solution I should look for?
did you use GOAP with the FSM/Utility or rewrote it
Hello guys I need help, I have this patrolling script in which enemy will go from point to point and when it comes to last point it will just stop. I want my enemy to go back to the first point and start looping and I also want my enemy to face where the point is because now he will just walk backwards to the point that is at the back of him for example. This is script: https://hastebin.com/share/abuwegolov.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey, is there a way to create preset for textmesh font settings? Such as size.
I want to make few for Header/body/footer for example
It is definitely not hahaha. I promise you
Edit: oh, missed the thread.
just make prefabs
I guess that kinda makes sense, but I found that there is a setting menu with default font size, but it seems to be per font file.
Come join us!
I just followed tutorial
https://i.gyazo.com/a1d89836b73a0ddd9297c930b521cf49.png
Do you know how to use those?
It's basically what I want, without having to make prefabs
ah its a dropdown under text field
not used them but they are obviously scriptable objects so you use them that same way
it looks like a scriptable object.
you are missing a class declaration
where does the word class normally appear in a script?
have you tried actually putting these methods inside a class 😐
time to do basic c#
methods belong in classes/structs
did anyone tried goap before other than @swift crag
im trying to make a reference to a prefab inside of a script asset that isnt atached to anything at the start of runtime but whenever i try to instantiate it, it says that the object is null
the left screenshot is for reference of what it looks like, completely different to this scripts for example
you can do something bubble =instantiate(someprefab);
in start
don't randomly tag someone not in active conversation
hi navarone!
right novarone.
what do you mean by this?
dont change the values on original Prefab
change the copy you get from Instantiate
but you are
where?
make a gameolbject for prefab also.
i alr have it
i mean in code.
@queen adder <@&502884371011731486> is spamming nsfw invite links, but it got deleted might want to keep an eye on this account though
[serializedfield] private gameobject prefab;
Yep, bot autodeletes them. Just not always as fast.
i think i dont since its a script that should get added to the player once certain ifs are met
did you read what I wrote
search the hierarchy to make sure
t:BubbleScript
hows this change anything?
and use bubble for instantiate
they literally instantiating a Null object
more likely its a copy with prefab not assigned
what is t:BubbleScript
its like you are not instantiate null but using the object for instantiating prefabs
i checked and i didnt found a copy of the script nowhere
searching for t:foo finds everything with a foo component on it
hi could anyone help me, how do I delete an enemy when I run over them for context my game is a small car that is drifting and waves of enemies come but only way to kill them is by getting them ran over
show where you put this script on, the object
it will not give null refence
instantiating a prefab that isn't assigned should surely give a Null ref
first define what it means to be "inMotion" to kill enemy
on the player
yea thats the difference making the object not null in start and using the object for instantiation thats what i mean did you understood.
but only after this:
screenshot it
for now I only want the enemies to get killed when the car hits their collision box
so whats the problem ?
seriously lol
did this but does not work
You dont see anything wrong here?
i see that bubble is none
but thats my problem since the start
i dont know how to reference it
The Three Commandments of OnCollisionEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt not tick
isTriggeron either - Thou Shalt have a 2D Rigidbody on at least one of them
drag n drop the reference in the slot
aint that diffcult
but i can only do that in run time
why
why
why are you doing anything other than trying to drag the reference in
because it isnt atached to anything until some ifs are met in runtime
what isn't "attached to anything"?
the script
the prefab that Bubble Script is on?
A prefab always exists
so what? prefabs can reference other prefabs, as you've been told already
You're trying to reference a prefab, right?
no, the script nor the bubble
yes
inside a script that isnt atached to anything
if you want it to be done runtime then create a gameobject with find search tag.
So then how is it doing anything at all
youcan put prefabs inside, they are just assets that live on your HDD
You need to show us exactly what "a script that isnt attached to anything" means, because I don't understand what you're talking about
love this explanation thanks only problem now is that the object that gets destroyed is my car not the enemies but imma fix that in a sec and come back if im dumb and did not manage that
because it gets atached to a gameobject when certain ifs are met
You cannot find a prefab with a tag
please refrain from giving random suggestions that have nothing to do with the problem at hand
Ah, okay. So then you'd want this script to reference the prefab you want, and pass that to the script you've just added
Right.
That makes sense now.
You'll be instantiating the prefab with the BubbleScript on it (and parenting it to the player)
srry im not english native so i may not use the best words to formulate my phrases
the prefab has a script that makes it destroy after 10 seconds
You will have two prefabs.
- A prefab with a BubbleScript on it
- The bubble prefab
also why are you calling BubbleProtect with a string
isnt it a coroutine name?
(you can just do StartCoroutine(BubbleProtect()))
ohhh
its like i am lazy of typing entire code.
This script should have a public field for the bubble prefab.
When you add the BubbleScript component to the player, also set that component's bubble to the prefab you assigned in the previous step.
Calling BubbleProtect() does nothing on its own. It just gives you an object that you can then run as a coroutine.
No one's asking you to type code they're asking you to just stop vomiting alphabet soup that has nothing to do with the problem at hand
no one needs entire code, nor to they need to be led astray with irrelevant suggestions. Its counter-productive
This is also a good idea.
Is this how to link an anonymous account? Getting an error
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
var token = AuthenticationService.Instance.AccessToken;
await SignInWithUnityAsync(token);
okay i can try that, it makes sense
You dont sign in with the Anonymous token
What do you mean?
SignInWithUnityAsync gets the Token from the browser response
fistly assifn something to that gameobject in the start and use it generate instantiation.
[Authentication]: Request failed: 401, {"detail":"unable to validate token","details":[],"status":401,"title":"PERMISSION_DENIED"}, request-id: 786fb2e8-193d-4b97-b5c8-47ee1db55f26
exactly
So what do I do instead?
Please just stop saying random things
You're only confusing people
and that is def against the rules
do it properly ?
It's okay to throw out a guess when you don't know as long as:
A) You acknowledge it's a guess
B) They're not actively being helped by someone who does know
where did you follow this wrong instruction from @weary egret
Yes, that's what I'm asking. What is doing it properly?
I didn't know where it was pulling the token from.
i am lazy in typing.
synnergy
Then why type unrelated things at all instead of just not typing
then be even lazier and don’t post
I have a video on this exact login mode if you want to use that
teamwork
hegemony
core competencies
Am I helping yet?
Sure, that'd be great.
thought of helping that guy.
Then why post something that has absolutely nothing to do with the problem and is not even remotely a solution
it will give null refence untill you assign something in the start.
Oh I started using that tutorial, but I couldn't get my setup to recognize PlayerAccountService and I couldn't add using Unity.Services.Authentication.PlayerAccounts at the top. I have the latest version of the Authentication package.
You did not
interesting, which version of Unity and Auth are you using ?
Auth 3.3.1, Unity 2022.3.20f1
also is your IDE properly configured
ok.
something like this worked
As far as I know. I'm pretty deep into a project and we are just implementing a persistent log in on top of an existing game.
Thanks to everyone that helped me!
good now I kill the enemies but i sometimes get stuck in them
i think i was telling you this.
and ty for your patience!
Oh okay because it should recognize PlayerAccountService
i dont know, what you were writting sounded very ambiguous
but still ty for helping!
No, you were saying some random waffle about using findWithTag to reference a prefab
i think he understood and found a solution. its not the way all others understand but if have that thinking you can understand.
he understood after digi has explained it to them
you didnt understood.
They understood other people despite your nonsense, not because of it
anyways. thats it. someone got a solution
No one could understand. It was ambiguous to the point of nonsense
because it was nonsense.
i really dont like typping. i mean typing the entire code for explaining.
Then don't
how do I take the velocity from the carcontroller and check in another code if the velocity is above a certain number to kill monsters or else to not kill
then refrain from doing so by giving incorrect suggestions
Please please stop then
You can get the Rigidbody component from the object, and check the magnitude of its velocity
Yeah, VS2022 didn't like it. VS Code is cool with it. Getting a new error.
WebRequestException: {"detail":"external token not provided","details":[],"status":400,"title":"INVALID_PARAMETERS"}
seems you haven't provided the token now
did you get the Web browser prompt ?
i will type.
i will not.
Yes, you will, thanks.
Stop trying to answer questions you don't understand when someone is currently being helped. You just make things more confusing for them because they haven't been here long enough to know that you have no idea what you're talking about
this seems right to you?
~~if you're using OnCollisionEnter you can use other.relativeVelocity to find the hit velocity. ~~
Oh nvm you're using Trigger
nevermind it kid just understand the concept behind.
You need to get the Rigidbody component from the collided object, but if you're specifically checking on OnCollisionEnter then navarone pointed out the shortcut to getting that speed that'll also take this object's speed into account, you should use that instead ^
Why do you insist on harming others?
ight lemme try that out
if(other.attachedRigidbody.velocity.magnitude > minAmount)
{
// do stuff
}```
if you need trigger i guess
🥳
idk what is happening here but just stop the beef, i understand both points of view since Ninja_dude just wants to help (or so it seems), and i can understand the point of navarone digi aethenosity and fern because he just confuses the matter more, either way i think there is no real benefit on getting so defensive Ninja_dude to the point where you are just saying childish things like i will type or i dont like to type. besides everything thanks to you all for the help and think about the fact that there is no point in being childish or rude
just gotta change the value from 10 to like 15 or something
the enemies can jump on me and throw the car away xD when I stay still
don't use magic numbers, make a variable in the insector so you can change it at runtime
or move me around
ye ur right
are they Navmesh agents?
how do they move though ?
wanna see their code?
sure, just seeing if they move with transform
photo or code
ok
but if they move transform , they will inherently push rigidbodies out of the way
{
public GameObject car;
public float speed;
private float distance;
// Start is called before the first frame update
private void Awake()
{
car = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
distance = Vector2.Distance(transform.position, car.transform.position);
Vector2 direction = car.transform.position - transform.position;
direction.Normalize();
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.position = Vector2.MoveTowards(this.transform.position, car.transform.position, speed * Time.deltaTime);
transform.rotation = Quaternion.Euler(Vector3.forward * angle);
}
}
yea MoveTowards will just kinda bulldoze its way through anything
no its not childish but i think i should not help over here probably. just watch.
Maybe use a rigidbody so you can make them be hit /stopped by the car
they got one
then don't use transform.position = to move
i dont know, its your choice!
or wait nvm
https://gdl.space/qonibakecu.cpp the player seems to be still moving when i presses something or when i jump even though i have the time scale on 0
mb they only have a box collider within the inspector
timescale 0 doesn't stop Update nor does it Stop key Presses or would it affect any of that
ive added a rb to every mob
You may need to show where you're flipping the character
You need to just disable the movement script @hushed hinge
ideally you make GamePaused a static event
My Movement is extremly stuttery, I use the character Controller to move in Update() and My camera updates in LateUpdate()
we cannot know for sure why if you don't provide the rest of the info. How is the character moved
PauseGame to become a static event?
Events can call methods when they're invoked
So you could have an event called OnGamePaused.
You could then add things to it to have them run when the game pauses
A static event would just be..static!
I mean have an event so your movement script can be disabled/enabled on pause/unpause
public class GameController : MonoBehaviour {
public static event System.Action<bool> OnGamePaused;
}
then...
Sure
character Controller this is the Code:
The function gets called every frame in Update
https://pastecode.io/s/1bfxzb4n
That is a nice way to do it
public class Something : MonoBehaviour {
private bool moving = true;
void Awake() {
GameController.OnGamePaused += HandlePause;
}
void HandlePause(bool paused) {
moving = !paused;
}
}
something like this
have you tried using Cinemachine instead ?
What is this?
wait no why are you turning everything static
You would then invoke the event like so:
whats cinemachine?
public void SetPaused(bool paused) {
OnGamePaused?.Invoke(paused);
}
(this would go in GameController)
A package from unity
its a Much better Camera package
Every method that has been added to the event will run
A package that basically makes cameras "Just Work™️" with very little effort:
https://unity.com/unity/features/editor/art-and-design/cinemachine
But its not the camera that stutters its the player you can see this stuttery thing also in the scene window
how do you know?
It could be either, since the camera is moving around
also you should only call .Move once
uhh.. is this a separate script?
Yeah but I mean the scene view is a static camera
I showed you two different classes, yes.
GameController decides when to invoke the event.
Something is a class that subscribed to the event.
Something can be your player movement script for example
You may want to combine the two Move calls, and the lerp is not really how you would want to write it. Keeping a static t parameter is just the same as looking at an offset, but if that's what you want it's fine
but that doesnt explain why it stutters so much does it?
but it's red underline on gamecontroller
well, yes, you'd have to actually have a GameController class
The two move calls might be a contributing factor
you can't just copy random chunks of my example into your game
Oh god tell me you're pasting stuff without understanding it
Ok I will try to combine them
no, I always had this pause script
The same as always, you cannot ever copy paste from here
You cannot do that every time we show you an example, you have to attempt to adapt it to your use case
Then what is gamecontroller?
if pause is your pausing script then put the event in there, simple as that
the other scripts just "subscribe" if they need to know game was paused
Pause is my pausing script
Ok I combined them and nothing changed
alright so put the static event in there
look at the examples Fen wrote
GameController is pause
Something is your PlayerMovement script for example
Now I did. It goes through and logs me in. The final piece - it asks me to log in every time in Unity editor. Is this okay (like is it an editor only thing) or do I need to check to see if I'm logged into Unity Player Accounts first? If so, how do I do so?
Ok, well, I don't see much of an issue from the code. Can you share a video of it? .mp4 embeds here
when you sign in a player for the first time, their Token and Cached data is stored inside PlayerPrefs
I allready did here:
You can sign in an already Cached user without signing in again if they already signed in @weary egret
I can make the camera to follow the player without lerping so one can see better if its the camera or the playe
it should still be something you should do, regardless.
Did you use cinemachine yet
public async Task InitSignIn()
{
await UnityServices.InitializeAsync();
await PlayerAccountService.Instance.StartSignInAsync();
}
Would I do this instead of StartSignInAsync?
no i didnt because I cant imagine that it cant work with the normal camera
I see it, just the slight hiccups every so often.
it can be if camera follow wasnt poorly coded
hmm... the Player2D script do havet he movement script,
Something = Player2D?
the movement script only care about the event
its static so you dont need any references, you can directly subscribe to it
like pause.OnGamePaused += GamePaused
@rich adder
public async Task InitSignIn()
{
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.SessionTokenExists)
{
// if not, then do nothing
return;
}
await PlayerAccountService.Instance.StartSignInAsync();
}
If I understand right, this covers what you're talking about here?
from the docs
If a cached player exists on the SDK, you can link the cached player to the Unity Player Account.
Sign into the cached player's account using SignInAnonymouslyAsync. Link the cached player's account to the Unity Player account with LinkWithUnityAsync.For more information about cached players, refer to Sign In a Cached User.
ops here
hang on, i was doing something, what do you think?
Show OnGamePaused
first of all did you add OnGamePaused inside pause script ?
also you dont need public pause Pause
static members live on the class itself not any instances
Yes, but how do I check if they are connected to Unity Player Accounts or not first?
pretty sure you can use the token already found to use that
so if token was found use that inside SignInWithUnityAsync
hmmm... no? (i've been searching it up) I have the PauseGame
searching what up
about OnGamePaused
there is nothing to search, you're literally adding 2 things
You can literally call it Waffles
names dont matter
did you add a STATIC event inside your pause script
what did you call it
this is when pausing the game when you press P. PauseGame
i dont care about that
did you add the event to invoke first
#💻┃code-beginner message
how can i fix that?
fix what , what am i looking at
This is ongamepaused
It is something YOU make. There is nothing to search
If you want to search something, look up events
the spawn its so random at axle y
right now
I guess what I am asking is, if I wanted to conditionally have a "Link" button, how do I determine whether the current user is actually linked to Unity Player Accounts or not yet.
Why are you showing me this?
That is not how you do it at all
why are you putting the event inside the movement script
Put the event in the pause script
you only SUBSCRIBE to it from the movement
isn't Something = Player2D?
you dont Define it inside the movement script
What does that even mean?
@hushed hinge make a thread
seriously how did you get this far and dont know you're obviously missing it inside the pause script
thats why its red..
Pause
anyone know how to do jump through platforms?
I'm using an existing project as a template to get started, and I'm at a loss for why they have basically 3 different coordinates/locations stored for entities. the built in transform.location, then another separate Vector3, and then worldX/worldY ints. Is this just straight up bad code or is there a possible reason why? It's a paid asset so I dont think I can share the code. Its simple though, nothing crazy going on.
i was working on an example I can show you idk if its the best way to do it though
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Ignore platform colliders above you, un-ignore platform colliders below you
interesting method digi suggested, should try that. (oh actually I had it in the code but for some reason commented out lol)
I'm basically using Dot product though, so might not be the most reliable
Do you use a physics query to look for "relevant" colliders?
i guess i'd check a sphere that's a bit larger than the player
thats what I do, but my method is not good now that I think about it. it makes whole platform trigger which is bad for others standing on it
if(currentPlatform == null)
{
var hits = Physics.OverlapSphereNonAlloc(transform.position + headOffset, radiusCheck, hitCols, platformLayers);
if (hits == 0) return;
currentPlatform = hitCols[0];
currentPlatform.isTrigger = true;
}```
I wonder what the cost of IgnoreCollision is. It can't be as fast as a layer mask!
(not that it's a problem; i'm just curious)
public bool IsColliderValidForCollisions(Collider coll)
{
i feel like i could use this from the kinematic character controller
Since it's for a Smash-like, I actually had the Stage object that had a list of all of it's pass-through colliders and their bounds. After the character moves, I just ran a check that looped through the list of pass-throughable platforms for ones whos tops were below the player's bottom and enabled collision, and vice-versa for ones whos bottoms are above the player's bottom
i feel like KCC has an example on jump through platforms no ?
actually maybe, i havent checked
how can i check what layer a collider is on?
grab the layer property from its gameobject
note that this is a layer index, not a layer mask
thats fine
oh thats good actually i have a ground layermask on this script anyway
i'll just use that
how do they turn a layermask into an int
Update Function --> https://hatebin.com/piwccqgoqu
So the trampoline is not getting detected, even with is Trampoline and other things gpt and intelli suggested. What am I getting wrong here?
Try logging onGround and what object the raycast hit to find out what isn't happening that you're expecting to happen
ok, one sec
ooooh
it detects the literal object
not the wrapper
so TrampolineObj. Do I just change the name?
how would I even check if that got detected
a Collider can never be a TrampolineObj
the is operator is used to check if an object could be assigned to a variable of a specific type
do I just give the trampoline object itself a collider??
TrampolineObj isn't even a type here. It's the name of an object in your scene
what's the best way to do this
you would still have the same problem, since this code doesn't make sense
What is the relationship between the object with the collider and the object with the component you want
what you can do is check if the object you hit has a component
+ change the code
Does on Trigger Enter require a rigidbody
apply the script to the trampoline obj, yes?
It requires one somewhere
If you put the collider on the same object as the Trampoline component, you can do this:
if (groundHitInfo.collider.TryGetComponent(out Trampoline trampoline)) {
// do stuff with the trampoline variable
}
if i have one rigidbody on the root object, do i need one for the colliders of children in that object?
No. A Rigidbody makes use of all of the colliders on objects that are parented to it.
okay, thank you
Note that for triggers, OnTriggerEnter is sent to both the object with the collider and the object with the rigidbody
This isn't the case for collisions. OnCollisionEnter is sent to only the object with the rigidbody
thats fine, thank you
alright, worked. Thanks guys
might help to have an explanation in case people can't see what the problem is . . .
z fighting maybe?
huh
i see moving back and forth while trying to look at a screen?
try putting the text slightly more forward than screen
same thing unless i look at certain angle
Can you show the hierarchy?
whenever you pop that multiplayer image thats when issue occurs
oh yes
when i disable it everything works fine
but i need the image
:(
well now you know where to check for problem area, narrow down the issue
wouldn't it just be easier to use World Canvas ?
huh
With panels and the image on it
A canvas set to worldspace
it is
its not , at least not the text you have selected there
that looks like a sprite/mesh
the image is a sprite.....
then why are you mixing Sprite Renderer sprite and UI
ui uses Image component
sprite renderer uses meshes with sprite
if you're creating any type of UI, use a canvas . . .
i have a canvas
i am using that
let me see the inspector
i kinda deleted it already and made a plane with image :3
too late!!!!
but thanks!!!
i made it so there are colliders in each limb. problem is now, each limb detects their own hit, so how can i stop this from happening?
Hit from what
if you mean colliders hitting each other use layers
make so same layers dont collide
Well if they're part of the Same Rigidbody they won't collide with one another no matter what
from another player,
they arent hitting each other
Use a separate collider for inter-player interaction
Use layers to separate everything
And layer based collisiona
wdym? the colliders arent hitting each other, the problem is collisions from another players move hitbox. I seperated out the colliders into seperate limbs to make the collisions feel more accurate and tight
Yes and you need to use layers to make those things not interact
The move hotboxes and these colliders should go on different layers and not be set to collide in the matrix
If you have single rigidbody it should report collision once tho?
Maybe I'm not understanding the problem
Is the problem that you're getting multiple collisions? Or is it that you're getting any collisions on these at all
You'll get one OnCollisionEnter per collider pair that touch
Rigidbody pair no?
hold on i'll get a screenshot, unity just crashed
I don't know what happens if you have multiple trigger colliders under a rigidbody
You'd get additional info in contacts in Collision if multiple contact between same rigidbodies
Not sure if that triggers event methods, hm
oh, wait, that's the problem :p
so I dealt with something like this while working on a soulslike
problem is im getting multiple collisions under one rigidbody, i just want one
You can't avoid multiple collisions. You can change how you respond to them, though!
That's for multiple contact points in the same Collider pair. Otherwise how would this work https://docs.unity3d.com/ScriptReference/Collision-collider.html
I made Hitbox and Hurtbox components that report impacts to the entity
Then disambiguate it in your code
If you are already touching the Rigidbody ignore the collision
the entity would ignore hits that were not stronger than a previous hit
Just track which bodies you're touching.
er, or did I do that on the weapon side? I might have done that on the weapon side
unity crashed again bruh
I did it from the weapon side, and you can simply store the rigidbody in a hashset to know if you've already hit the object.
Clear the hashset everytime you want a new instance or tick of damage
yep, that's what I was doing
the weapon knew "hey, I already got a hit of quality 0.75, so this new 0.5 quality hit shouldn't even do anything"
and a 1.0 quality hit would produce another 0.25 damage
that way, clipping an enemy's "weak" hurtbox before whacking their "strong" hurtbox wouldn't make you deal more or less damage than just hitting the "strong" hurtbox
basically imagine a move hitbox that was about this size. all the overlapping body colliders recognise it and all tick the same damage
lest you wind up with a dog that deals 11,640 damage per second
i just want it to tick the damage once
yeah, so you need to abstract this
Each collider should not be directly causing damage to be taken
public class LimbCollider : MonoBehaviour
{
[SerializeField] private PlayerHit _hit;
private void Awake()
{
_hit = transform.root.GetComponentInChildren<PlayerHit>();
}
private void OnTriggerEnter(Collider other)
{
_hit.HandleCollision(other);
}
}
each collider has this script on it
Read the convo slightly above that image on a solution. Your colliders shouldnt be looking for things that damage it. It should be told it's taking damage
Seems right, got confused since each contact also has Collider info
Looks like that is in fact just duplicated info lol
what does disambiguate mean in this context?
Just ref-count your collisions
to get rid of an ambiguous situation
if you get four trigger overlaps, it's unclear how much damage should actually be taken
the individual LimbColliders cannot make this decision
hello, if I make a new scene in unity and have a camera displayed for that scene in a different scene through a render texture would this work ?
can anyone explain to me what that thing means and does exactly?
() => is lambda expression and += is subscribing to the event
what makes this decision then? should it be like a collision manager in this object, or should it be the other player making that damage decision?
okay thanks
see the above conversation
okay
shouldnt be too hard to refactor
this whole time cus i had a single collider i was making the decision from the victim
Alleviate the uncertainty that comes from multiple collision callbacks
For completeness, lambda expressions are methods (like void Start()) which don't have a name and can be declared in-place.
Your code is an equivalent of:
button_exit.clicked += ExitGame;
// later...
void ExitGame()
{
SceneManager.GameExit();
}
thanks now im slightly less stupid :>
I'm trying to move the camera forward the direction it's facing, but when it's tilted up/down, it will move on the Y axis - how can I get that to stop happening? I found a forum that said to use Normalize()
transform.Translate(Vector3.Normalize(new Vector3(Camera.main.transform.forward.x, 0f, Camera.main.transform.forward.z)));
So, you can subscribe to the event only if the method you're subscribing has the same number and type of parameters as the event.
public Action OnSomething;
OnSomething += Update; // works
public Action<string> OnSomething;
OnSomething += Update; // error
OnSomething += _ => Update(); // works
public Action<string, string, string> OnSomething;
OnSomething += Update; // error
OnSomething += _ => Update(); // error
OnSomething += (_, _, _) => Update(); // works
Note that the lambda subscriptions cannot be unsubscribed.
Normalizing just scales the vector so it's magnitude is 1. The forward should already be normalized. Add some debug drawrays to see where it's trying to move because this code looks fine if you want 0 y movement
Oh actually you might need to use Space.world in the 2nd paramter, I believe it might be using local space here
transform.forward moves the transform in the forward direction they're currently facing. Yes, if it's tilted up/down, your forward is going to be up / down.
If you want to move the camera forward regardless of their direction, use Vector3.forward
hey guys i was wondering, how do i detect the force applied to a gameobject?
Normalizing without Y is fine, though not in readability wise.
However Transform.Translate is local space by default but you are dealing with world space coords