#💻┃code-beginner
1 messages · Page 584 of 1
like above?
yeah that should work
nice, why when i search how to find the feild of view view cone in unity, it sends me down a trigonomic path instead of this simple way?
Because people don't know how to think in vectors and quaternions
they fall back to what they learned in 7th grade - which isn't necessarily a bad thing but there are better ways.
*solved
why is this function only working sometimes? when it's not workign it's either; 1. not drawing a line, 2. drawing a line when it's behind the transform.
private void IsObjectInViewCone(float radius, float angle) {
var snakePosition = snakeBrain.position;
var targetPosition = _targetTransform.position;
var distance = Vector3.Distance(snakePosition, targetPosition);
if(distance > radius) return;
var directionToTarget = (targetPosition - snakePosition).normalized;
var angleToTarget = Vector3.Angle(transform.up, directionToTarget);
if(angleToTarget <= angle / 2f) DrawDebug.Line(snakePosition, targetPosition, Color.red);
}
Anyone know why when I add 3 players to the input system using .instantiate() it creates a 4th box
How do I fix this
Each player object im instantiating has an input system component and a camera child object
show code, and be more descriptive about what you mean. what "4th box" are you referring to
how many boxes do you start off with?
What's a box?
Hi, im still struggling to make this work, for an strange reason when the player shoots it proyectiles and moves, the shooting speed gets weird, this is of what im talking about (ignore the glitched animation)
this is the script
{
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);
riflebullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed;
}```
💀 mb
i meant these boxes:
nothing weird about it
that's the Doppler effect in action
i added the white lines
Each animal is a player object with an input system component
the 1st 2nd and 3rd boxes correspond with a chracter, the 4th does
this is how i instantiate the player objects
the boxes are a split screen from the input system
the fourth one does not appear to be a separate viewport, but rather is what the main camera is actually seeing, but the other three viewports are overlayed on top of that
yep - disable the main camera you'll see that go dark
that's a problem
would it be possible to have 3 players be horizontal thirds and 2 and 4 players be the default with halves and quadrants respectively
anything is possible
YOu just have to write the code
I take it you're using PlayerInputManager's built-in split screen feature though?
it didnt go dark, instead it's displaying the camera from a previou scene
yup
Yeah it's probably not that customizable
if you want what you said you'll have to write it yourself
uhh so how would I do that
By writing code that sets the camera viewports:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Camera-rect.html
so when there are 2 or 4 players use split screen, and when there are 3, split it myself?
That seems pretty easy
I would just always split it myself
the logic is not that hard
you could have a switch statement for the number of players and the code that assigns rects to the cameras.
is there any benefit, since I already have the split screen code and it's extra work to write it for 3 playes
plus im getting contradicting information, some people say split screen using the built in input manager is better than manual
but the issue is, how i get rid of it? The proyectiles must have a constant speed no matter how fast the player moves
cuz the player is supossed to move like crazy and shoot
Yes the benefit is you get to split the screen as you want instead of the way Unity decided it should be.
Those two statements are contradictory
wat
If you want them to always appear on screen with the same spacing etc, you would add the player's velocity to the bullets
if the player is moving and the bullets are moving, you will get these spacing artifacts
oh
it's just the nature of what you're doing
alr thanks
wait, the character is that fast that outspeeds the mf bullets?
dang, then i have to speed up the bullets?
has nothi9ng to do with "outspeeding" them
if you run in the same direction you're shooting, they're going to appear compressed
but i feel like shouldnt be like that
Again it's similar to the doppler effect:
Well... the world doesn't work according to your feelings unfortunately...
that's up to you as the game designer
i mean cuz thats whats making me feel anxious, if this is normal as physics say, then doesnt matter?
And yes if the bullet was significantly faster than the player, the effect would be less noticable
I can't answer that, only you can answer that
it's your game
ok...
but i mean, i dont want that effect to happen
cuz i feel doesnt look too good?
idk
ok, well, thanks
how do i do that specifictly?
im pretty new at coding...
add vectors with the + operator
what do u mean?
hi i am trying to make a jumpscare if someone presses a button but the animation simply wont show. i used the debugger which showed me that the button got triggerd so it must be an animation error but i cant get behind it any help?
how can i do something like this without edge cases or any errors with storing a quick access to a list of colliders: (im going ot remove irrelivant code )
private Collider2D[] _collidersInFOV;
private void IsObjectInViewCone(float radius, float angle) {
var overlapObjects = _enemyManager.GetAllObjectsInRadius(snakeBrain.position, radius);
var colliders = new List<Collider2D>();
foreach(var enemy in overlapObjects) {
if(angleToTarget <= angle / 2f) colliders.Add(enemy);
}
_collidersInFOV = null;
_collidersInFOV = colliders.ToArray();
}```
in other words... i can't seem to find out the correct way to make an array (with objs in it ) to change entirely into another array (with new objs of same type )
That's how physics works in real life. If you fire a gun while standing on a train, the bullet is moving faster than if you were standing still
If you want your bullets to move at a constant speed, they will be closer together if you move in the direction you fire
Adding the player's velocity into the velocity of the bullet would be done with the+ operator
It wouldn't remove the Doppler effect though. The reason why the bullets appear closer is because you're walking in the same direction as the fired bullets. Spawning the next bullet closer to the previous by running in the same direction. If the bullets are super fast, it'll not be as noticeable.
If you want them moving relative to the player or the screen rather than the world, you could perhaps child the bullet to the player so that when moving and firing, the bullet would "look" consistent in speed (they'll always take a certain amount of time to leave the screen because they would be displaced relative to the parent - with the camera following the player)
hello, i've set up two box collider 2d's to keep track of which side my player touches the wall on, is there a way to differentiate them in code? or is there a better way of doing it than what i'm doing?
Checking the normal of contact point
Folks, I have a tilemap 2D. I want to make Enemy AI. Which approach can i go with?
how? not enough info
hello so I have this code and basically I want to display idle sprite upon start or entry https://paste.ofcode.org/34nmY3HFYZL6WU4p35JbSy8
Why do my variables behave wierd? In this instance, sometimes when i switch objects in game hierarchy it feels like all my variables operate "faster" or increment differently than they should. This also happens when the tab is maximized. What can i do?
void PlaneMove()
{
//constant Speed
transform.position += transform.right * Time.deltaTime * Speed;
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(new Vector3(0, 0, 1) * sway);
}
if (Input.GetKey(KeyCode.D))
{
transform.Rotate(new Vector3(0, 0, -1) * sway);
}
sway is supposed to control the Plane A/D movement, as shown in the Video, and with my testing, this variable is not changed.
You have to apply deltaTime to the sway as well
Thank you!
Best option is to make each collider a child object. You can assign two colliders in the code with each their own name, but as far as I know, OnTriggerEnter will trigger both colliders. Best approach is to seperate them into child objects
quick question, does a raycast also rotate with the GameObject's rotation? Say a cube rotating every frame, a raycast set on one of the faces. Does the raycast also rotate with the cube's tranform rotation?
also does the raycast also rotate if the cube were to rotate via the animator?
raycast does not "rotate", it casts a ray in a specified direction. so you need to be using the object's rotation to determine the direction you cast the ray
in a way, the raycast is stuck onto the side of the cube. Whatever transformations are applied to that cube's side will also affect the raycast. Did i get that right?
no because a raycast is not an object in the scene and has nothing to do with the object you call the method from. it is entirely dependent on the data you pass to the method
so if i were to match the raycast's rotation with the cube's side, i'd have to pass direction to the raycast?
yes, you always have to specify a direction for the raycast
""" bool raycastUp = Physics.Raycast(transform.position, moveDir, 20f);
"""
somewhat like this, got it
how do you get the value of moveDir
from the direction the player is currently bound to move
how
okay i'm not going to play this game where i have to keep asking for more and more information. i am not familiar with the rest of your code, i do not know where these values you use come from, so naturally i don't know where targetAngle comes from and have no way of determining whether this will be relative to world space or the object's rotation
if the information i've provided thus far is not sufficient for you to understand how the raycast works then maybe someone else will come along and help you
int x;
private void Awake() {
Pools = new IObjectPool<GameObject>[projectiles.Count];
for(int i = 0; i < projectiles.Count; i++){
x = i;
Pools[x] = new ObjectPool<GameObject>(() => CreatePooledItem(x),
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 50);
}
Instance = this;
}
GameObject CreatePooledItem(int i)
{
GameObject newPooledObject = Instantiate(projectiles[i]);
newPooledObject.GetComponent<BasicBullet>().pool = Pools[i];
return newPooledObject;
}```
so for some reason, x is always equal to projectiles.Count - 1, no matter what I do
I try to get items from pool number 0, and it always takes one from pool number 1, no matter what
I tried having a list of object pools so I don't have to create a new one for each different type of projectile
I want to implement a game where I will have many characters. None of them share common characteristics, but many of them could share common abilities. For example, many could move with a basic movement, some could jump, some could control gravity, some could fly, and so on. To achieve this, I thought of creating components, like the PlayerMovement class, the PlayerJump class, the PlayerGravity class, where I will define parameters and methods. Then, for each type of cube (or player), I will use GetComponent and use the methods from these classes. For example, in the Player1 class, I will get the jump movement component, while in Player2, I will get the component and then use the methods from these classes
Each player will have different animations, but I could implement them in each script, for example in PlayerMovement, like this. I couldn’t create a separate animation script unless it's a different one for each player, or I could implement it directly in their respective controller.
Could someone give me some advjse??
"implement a game"
"none of them share common characteristics, but they share common abilities"
what.
if they share abilities they share characteristics
also, just use an animator
i wanted just to say that i cant use inheritance but composition
but its good to create some classes with only methods that i can acces from a controller ??
why not just have each of the components have a reference to an animator, and animate your characters like that?
you dont need inheritance for that
just manually set the reference to the animator
declare x within awake instead, or use a new variable if x is used elsewhere for some reason
for(int i = 0; i < projectiles.Count; i++){
int x = i;
yeah i can but it s a ripetition of code
you saved me, thank you!
I know lambda expressions pass by reference basically
but ive been told back then to do this, where I declare x globally, and didnt check if it works for a non-1 array
hello so I have this code and basically I want to display idle sprite upon start or entry https://paste.ofcode.org/34nmY3HFYZL6WU4p35JbSy8
And what is happening instead?
Walk animation is played
I have I fixed everything else
All code runs well now like everything I desired I can even change directions I do still suspect that the animation frames are the problem and I should try modifying then perhaps
You could just Debug.Log something every time you change the current frame
This way you can check what is setting the walk animation at the start
I'm curious if GetAxisRaw really returns 0 and not just some very small number.
Instead of checking if it's greater than 0, perhaps try checking if it's greater than 0.05f, or try GetAxis instead of GetAxisRaw.
I highly suggest going over to the new input system anyways.
hey osmal I have a glitch now literally like all other directions work exactly fine except left Idk why I literally tried replacing it with other sprites and double and thriple checked that it wasn't empty but it isn't here is the code I even debugged it properlyhttps://paste.ofcode.org/MGyaAMV5LfN3rKtrT337Vg
I don't see any debug.logs, did you use the IDE debugger?
Just checking, you removed the animator component right?
Yeah
so what do you think?
Show the inspector of this component with all of the animations visible
sure
see
Okay well that doesn't tell me much, i'll just assume you assigned them correctly
So what debugging steps did you take?
Because I don't see any trace of debugging in your code
I checked all the frames that were toggled
I guess, the frames you have are just being mirrored because of frame 6, 11 and 3 are in there two times?
yeah I erased it as it was kinda useless
yes they are used for the walk animation's frames and only left doesn't work all other directions work well
What happens instead?
in left direction?
yes, I did not read the whole conversation, sorry if you have to say it again
yeah so basically the walk animation iterates through its frames and also has a consistent walking system when key is pressed for some time let me show it to you
see
so you can see that the left animation doesn't work like the other directions
What's with all those anyKeyDown and anyKey checks
The logic is really hard to follow
I have really brute forced the methods in order for the script to work properly
Also just replace all Input.GetKey(Keycode.z) with isRunning
Using bandaids like that will likely cause more problems down the line
(Like now)
no it cannot happen as when I do that many unexpected errors come
but I don't think that is the problem as it worked fine earlier it just got this recently
else if (isRunning)
{
// Show idle sprite when Z is held and no movement
spriteRenderer.sprite = GetIdleSprite();
}
else if (Input.GetKey(KeyCode.Z) && !Input.anyKeyDown && !Input.anyKey)
{
spriteRenderer.sprite = GetIdleSprite();
}```
How can the second ``else if`` be true here? Z key can't be pressed since isRunning is false
yeah that's why it didn't work but this works
else if (Input.GetKeyUp(KeyCode.Z) || Input.GetButtonUp("Run"))
{
// Transition from running to walking: force first walk frame
currentFrames = GetFramesByDirection(false); // Get walk frames
currentFrame = 0; // Set to first walk frame
spriteRenderer.sprite = currentFrames[currentFrame];
frameTimer = 0f; // Reset animation timing
keyPressTimer = 0f; // Reset key press timer
return;
}
I think you should use some kind of state machine. This is a mess
I tried earlier but it was a lot more big mess
I just want to fix this last thing now
Thx
so how to fix then?
You were told many times to debug the input and other variables. Make sure they are what you expect them to be when certain keys are pressed
they do play just the currentFrame is not played
Show the results and don't delete the debug.logs from your code when you show it
ok so in every direction the currentFrame is changed but in left the currentFrame is not changed @verbal dome
First go away of chaining if statements like you do. Get your input, set the booleans correctly with that input and then assign your frames correctly.
im trying to make a walljumping script and it works. but if im holding the same direction of movement against the wall that im jump off. then it cancels the wall jump after 1 frame.
Am I dumb or this should be returning an error cause they are not the same thing???
IndexOutOfRangeException: Index was outside the bounds of the array.
PlayerMovement.AnimateSprite () (at Assets/PlayerMovement.cs:107)
PlayerMovement.Update () (at Assets/PlayerMovement.cs:56)
You'll probably have to explain a bit more what you mean
Oh, no, never mind, I am fucking dumb indeed
What error are you expecting?
Oh, chat just updated (for me) . . .
Welcome back
You are accessing an index that is not in your collection . . .
Hey osmal I tried the same script and player in another unity project and it works how does that happen?????/
yeah I fixed that I apparently forgot to add the sprites
guys, need help with something
i got a couple of objects that i apply a variable called pointValue and i have the OnMouseDown function to destroy the game object i click in and add a point using a function from a singleton, however, i can't seem to understand how i'd make it so that the bad objects you can't click in doesn't subtract from your points? i've tried checking to see which was the tag of the object that activated the OnTriggerEnter function and it still made my player lose a point
not sure if i explained it correctly but i'll answer any questions
I am just feel I am superentangling a thing that should be supereasy
Just cause I am connecting so many scripts and I am not even sure why I am doing that
So my mind went totally Ploof
If you are not sure why you are doing something with your code, you def. gotta take a step back and write down your entire flow of data and method calls
Well, I know I have to split them cause else is gonna be a nightmare later, but not sure what I am gonna be adding later
Can someone help me please? My unit has a rigid body and a collider. My terrain has a terrain collider. Howeever, my unit goes through the terrain.
Show the inspectors of both objects
Like rn, main issue is I have an EnemyAggro that should be telling who should this be focusing as a target, then I have the GeneralistAbilityManager, that tells with what should be using on that target (this should be a superclass and be different for each one later on, but rn, they only do the basicAttack). But the thing is, I need the NavMeshTargetSetter to have a target for the NavMeshAgent to tell it where should it be standing, which is not the same as where should it be focusing UNLESS they have no actual explicitly assigned Waypoint, then it's pretty much the same and it would try to stay at the point that need less movement and it's within range of whatever ability it's using....
This amount of abstracts references is kinda melting my mind....
I figured out the problem my run button had a negative parameter of left which caused the issue
your rigidbody is kinematic
that mens you're controlling the movement entirely through script
and that colliders are not going to stop it.
im trying to make a walljumping script and it works. but if im holding the same direction of movement against the wall that im jump off. then it cancels the wall jump after 1 frame. can someone help me fix this.
yes, that's right
If you want collision you'd need to be using a dynamic Rigidbody
(non kinematic)
,with a kinematic body you'll need to handle collision yourself with BoxCasts
What did you learn from this
okay, thanks, will research it
you should cancel movement or don't track/store it while wall jumping to avoid it from overriding the wall jump . . .
sometimes some small things cause big problems
Well that too but mostly that you should just confirm that your values (input in this case) is exactly what you expect it to be
Hey, just wondering, how could i add an audio proximity feature to my 2D game. So for example, when im near a game object, then a sound starts to play louder, and whenever i move away, its gets quieter and then silent
use a trigger collider
i believe im already doing that with this in my fixed update and this on my walljump
but that would just work for when i trigger the collider, but not when im closer the louder it gets no?
the trigger collider is for detecting when you enter and exit the zone
while you are in the zone you would check the distance to the thing each frame
although now that we're discussing it
you don't need any of this really
as what you are describing is the built-in behavior of the AudioSource component
See how you can configure the volume falloff and everything
one thing you might still want a trigger for is if you want to specifically start the sound when the player gets to a certain distance.
Simulating a some kind of hyperbolic geometrically shaped room that has perfect resonance zones where the sound waves get reinforced perfectly?
idk lol
or sound in non-euclidean space?
Oh I thought it was from something you are making
Kekl
The use case is really "look you can do all kinds of crazy things with the AnimationCurve!"
ahhh okayy Thank you very much, I think i wanna use the trigger collider anyways, because its for a school project, and i need to discuss the code so it would be easier that way rather than using an inbuilt feature.
im trying to make a walljumping script and it works. but if im holding the same direction of movement against the wall that im jump off. then it cancels the wall jump after 1 frame
ive tried debug.log on all the numbers in the calculation of the jump both when the jump fails and when it succeeds and the numbers are the same
i have it set currently in my fixed update that the player should only be allowed to move when im not walljumping through a boolean that activates as soon as i press jump while on a wall.
I am confused as to what is causing this.
You need to show your code
A tool for sharing your source code with the world!
152-196 should be the important part
Where does it cancel it?
if im pressing wall jump while holding in the same direction as the wall it doesnt cancel it entirely but instead of sending me away from the wall like its supposed to it just sends me straight up.
same direction as the wall
So into or out of the wall?
I'm trying to use OverlapSphere to detect if there is a GameObject where my cursor is hovering. all of the GameObjects in question have colliders, but it is not detecting any colliders
I do not see any debug.logs on the important parts. So you should check your if statements and be sure, your directino is correct and not in the wrong one so forces try to push you in that direction (against the wall) resulting in up pushes
directino
I read this in an italian accent
show your !code 🙂
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Vector3 cursorPosition = Input.mousePosition;
LayerMask mask = LayerMask.GetMask("Default");
Collider[] intersecting = Physics.OverlapSphere(cursorPosition, 0.01f, mask);
Debug.Log(intersecting.Length);
if (intersecting.Length != 0)
{
foreach (Collider thingToDestroy in intersecting)
{
float dist = Vector3.Distance(cursorPosition, thingToDestroy.transform.position);
if (dist < 0.5f)
{
Debug.Log("There is an object within 0.5 here");
Destroy(thingToDestroy);
}
}
}```
It's only reaching the first Debug.Log() where intersecting.Length == 0.
if im moving into the wall
Do you maybe hit "yourself" and deleting the object holding this script?
Ive removed them after testing but the direction is correct even when the jump just sends me up
nope
the GameObjects are all in the same layer and stuff as well
So you are not logging, what you hitting and not logging the length. Are you sure your length is > 1?
that's my point, i'm logging the length and i'm getting 0, it doesn't seem to be colliding with anything
what i think is happening is that when i jump it decides to jump for 1 fram and then the input of movement happens after that somehow before its been told its not allowed to move and therefore cancels the horizontal movement aspect of the jump but not the vertical aspect. But i dont know why
ohhh, so you never get the debug.log from the if loop, but only the length before that? Misunderstood that for sure
yes
so you might be overriding your movement with the default movement again?
the loop isn't running because it's not detecting any colliders, and i have no idea why
yes i think so but i dont know why
do you check with some debug.draw spehres or lines that your position and radius are correct to hit somethign at all?
my game is 2d, could this be a problem?
I haven't tried that, I'll do that now, but i'm just checking if my cursor is hovering over a GameObject in a 2d plane
ohhh 😄
if you want to use physics in 2d, stick to physics2d 🙂 https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics2D.OverlapCircle.html
oh my
cause you set it every fixed frame back to input
if (!isWallJumping)
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
Hey i have a question what is damping and what are its uses? i keep seeing linear damping angular damping and i dont know what those are
On rigidbodies?
but as soon as the wall jump occurs isWallJumping is set to true which means the inputs shouldnt be allowed until the wall jump is finished? or am i misunderstanding.
Use: Moves a value towards another without overshooting (smoothdamp that is)
Example: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.SmoothDamp.html
yes
i didn't even realise this was a thing, so thank you for that. Although it still doesn't work 😢, it's still not detecting any GameObjects
Be sure to use the right colliders and collider components. they all have 2D
and Collider2D does not inherit from Collider, so your check has to be right to return the correct array type
but why would you use damping instead of just decreasing the value over time with a while or smth like that , what are the advantages
decrease what value? The damping takes into account the physics system.
oh ok thanks
You could do it manually by modifying the velocity each fixedupdate
Using linearDamping is convenient in most situtations though
Show your current code
is there another way i should be doing turning off the inputs temporarily?
hey i have a quick question. how do you rotate an object around a point in the scene view?
You could add a cooldown timer that starts when you walljump
When that timer is active, stop modifying movement velocity, or use AddForce if you want to mix the two
but isnt that kind of already what i did.
i use the boolean to turn off movement and then Im using the wallJumpingDuration as a cooldown timer that invokes a method that turns a boolean off
A dirty way is to add it as a child of a parent at that point and rotate the parent
Would be cool to have something like blender's 3D cursor in unity though
i tried to do that but the parent object changed its center to the center of the child object
I didn't read it thoroughly tbh, I'll take a look
Oh you need to make sure your gizmos are in Pivot not Center mode
oh thanks mate
Uhh what is bootsigil
It's hard to follow the logic here
its what allows me to choose if the player has unlocked the wall jump or not but in this case its always gonna be 4.
(if its set to 5 its a double jump if its 4 its wall jump etc)
Are you sure that you aren't entering wallsliding mode when it happens?
if (IsWalledL() && !IsGrounded() && horizontal != 0f) this could be still true shortly after walljumping, right?
ty
It's like a while loop that executes at least once before it checks the condition
Can someone give an advice please. I am making an arcade racing multiplayer game (similar to Star Wars Episode I: Racer). Is it better to use unity physics system (non kinematic rigid body) with collision or code collision myself?
i think ur right. but how do i word it then so that i leave wallsliding mode when i jump.
Thanks a lot for making me aware of all of that. I have sorted it all out now, I had to make it a world point too, now it's actually intersecting with things and works!!!!!!
You probably want to return early from the wallSliding method if isWallJumping is true
I tried something and it worked. Tyvm that was the issue.
For future: you would've noticed this yourself if you put logs in the code or used the debugger
ur right. i did put logs in the code but i didnt think wallslide had anything to do with the problem so thats why i put no logs there. its entirely my own fault for making that assumption though.
hey, does someone got a tip for me what term i should search to load tiles at runtime / game start ? My goal is to allow inserting new tiles and then use them in game. Maybe load a tsx file and then the png
why tsx?
just as example, i think its generated by Tiled
i searched for hours, but maybe i found smth : https://discussions.unity.com/t/run-through-a-folder-and-make-a-list-of-tilebase/935358
ofc after asking here
it sounds like you're looking to offer basic modding support, so you could look for resources on that
yea basically that 😄
basically you'd pick a place that you try to load user-tiles from and check there for any overrides
Resources.Load<TileBase>("Assets/Tiles/Sprites/" + tileSpriteName) i think thats the line i was looking for
so check for json files, parse them and then load the tiles based on json
I don't think these would be Resources since they're being included by your users, not as part of your build, right?
mhm true
what is a more begginer friendly way for an enemy to move twards the player without using pathfinding i tried watching a tutorial but all of that is way out of my league atm
you can just move naively towards the player's location but you will get stuck on stuff
then you probably want some kind of pathfinding 
anything else will end up pretty silly
you could try functioning how the robo-vacs without mapping do and bounce cleverly but unless your game is about fighting robo-vacs it's going to be weird
my game is just a square with a weapon that has to beat zombies and when the zombies spawn they have to fallow him
pathfinding with the nav mesh is about as simple as it gets so it's worth figuring that out
thanks i will try to undestand that
System.IO.Directory.GetCurrentDirectory() + "/GameData/"
Should do the trick
how do i make when the enemy dies, it will just drop and disappear while blinking in 3d
We talking sprites?
ah I guess 3D is a give away, not that 2.5d sprites arent a thing
i have a 3d object (a capsule), when player shoots i want it to drop on the floor and disappear after blinking
okay i made a mistake. Resources.Load has the generic. I think passing the correct path wont work
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Material.SetColor.html
So easiest way here is to just change the material property, but this would change it for all mesh's that use this same instance. It's actually a little technical so if you're new to Unity you may need to read up on materials and how shaders work.
Resource would imply it's in the resource folder, which users would not have access to? (a part of the build etc)
Perhaps you're wanting streamable assets or something.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
found this
gonna try this
i cant figure out how i can drop it. i tried using animation but this doesn't work. when enemy starts to fall then immediately stands up.
what you can do is add some physics to it and let unity handle it by throwing on a rigidbody and de-parenting it from your player
its kind of getting over my head as i am using nav agent
oh, if the animation is reseting then make sure your blend tree isn't exiting that animation when it completes
Both ways are fine, but the physics idea is more for like a ragdoll effect if you wanted that, otherwise if you can pinpoint where the problem may be in the animation. I can probably help otherwise #🏃┃animation is probably the place to post screen shots of the blend tree if that's the problem
Trying to wrap my head around Animal Buddies from DKC, to barely any success
I'm trying to implement rideable things in my platformer, akin to Yoshi and the Animal buddies from DKC.
The first idea was hopping on it and letting the player's script determine the basics of how it moves on land. but since so much of my movement script would be deactivated, i'm struggling to come up with a plan b
@night mural
public TileBase LoadTile(string path)
{
var fileData = File.ReadAllBytes(_basePath+"/Game/Data/Tiles/" + path);
var tex = new Texture2D(2, 2);
tex.LoadImage(fileData);
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
Tile tempTile = ScriptableObject.CreateInstance(typeof(Tile)) as Tile;
tempTile.sprite = sprite;
return tempTile;
}
is working so far 😄 need some optimization but good to go for the moment
us Path.Combine instead
float pingpongValue = Mathf.PingPong(Time.time * rotationSpeed, anglesToCheck) - (anglesToCheck / 2);
cannon.transform.rotation = Quaternion.LookRotation(transform.forward * visionLength + (Vector3.forward * pingpongValue));```
so I have this code for making the enemy basically look left and right constantly
rotationSpeed, anglesToCheck and visionLength are set through the inspector, for the upcoming example
rotationSpeed is 30
anglesToCheck is 30
visionLength is 3
is there a better way to do this?
Do what, implementing it? If it works, then it works.
If you mean designing enemies, you can use SOs and define the properties on it, and use that instead.
it semi works, meaning that it completely ignores the anglesToCheck limit
which isn't intended
I just want it to rotate back and forth rotationSpeed degrees in an anglesToCheck cone
The calculation in LookRotation doesn't make any sense. You are multiplying a world +Z vector with pingpongValue, which gives you a...longer +Z vector
transform.forward * visionLength also doesn't make sense
You should compute a rotation and then apply that to your original forward direction
e.g.
Quaternion.AngleAxis(pingpongValue, transform.up) * transform.forward;
pingpongValue is a number between [-(anglesToCheck/2), (anglesToCheck/2)]
this rotates your original forward vector around your up vector
so if anglesToCheck is 30, pingpongValue is a number between [-15, 15]
yes, I understand that -- the resulting math still makes no sense
you are adding together two vectors and then using the resulting direction to compute a rotation
why transform.up?
don't you need a Quaternion for AngleAxis?
no, it computes a Quaternion from an angle and an axis
hence the name
I presume that the turret rotates around the tank's up vector
well uhh
you can set cannon.transform.forward to the resulting direction
alternatively, you can combine that angleaxis rotation with another rotation
oh, wait
cannon.transform.forward = Quaternion.AngleAxis(pingpongValue, transform.up) * transform.forward;
cannon.transform.rotation = Quaternion.AngleAxis(pingpongValue, transform.up) * transform.rotation;
Both of these would work.
i completely forgot about the fact that transform.forward can be set .-.
that works, thank you very much!
Personally, I would go with the second one. That will make sure the turret is rolled correctly
I feel silly that I've been using quaternions and such for so long and I still struggle with simple up and down movements :/
there's less information in a direction than there is in a whole rotation
well I don't even want to give the code the chance to rotate the cannon on any axises other than y
so i've followed this logic where I've created 2 triggers for each side of the character to determine what wall they're touching
using UnityEngine;
public class WallJump : MonoBehaviour
{
Rigidbody2D parentRb;
bool isTouchingWall = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
parentRb = transform.parent.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
/* while touching wall, if holding a direction opposite to the current object
then start wall slide logic
*/
}
void OnCollisionEnter2D(Collision other)
{
isTouchingWall = true;
}
void OnCollisionExit2D(Collision other)
{
isTouchingWall = false;
}
}
now i'm confused if I'm gonna apply this script to both of the child objects how would i know which one i'm currently on
or would i need to make 2 separate scripts?
how would you know which side is currently touching the wall?
i meant like
is that the question?
i have 2 triggers on each side
i'm not sure if i use that script how would i know which trigger i'm using
my structure is a parent object with 2 separate game objects as children and each has a trigger
one for left and one for right
wym
would there be any way for the character to be touching a wall on the left, if the character is moving toward the right?
If you put a script on each of those children, does OnTriggerEnter2D get called on the child? I forget how it works in 2D
if you are certain that this cant happen, you can just use a single trigger, and check the velocity of the player
if the velocity is facing the left, you are touching a wall on your left
well no
if the velocity is facing the right, you are touching a wall on the right
this works with the wall slide
basically
if you are going left
you are touching a wall's right side
that makes sense
and vice versa
I dont think velocity is reliable since you might have already collided with the wall and bounced back
Or stopped
i believe that's how it works
If that's the case then you can try that
you could just make the trigger slightly bigger to counteract that no?
yeah that's what im doing i'm just saying
Another common way is to do physics queries like OverlapBox/OverlapCircle
how would i differentiate which trigger is the one that actually is it
could do that instead of a trigger yeah
you could just ditch the triggers entirely and do what osmal said, use overlapboxes
i'll have to look into it, is there any advantage?
you would know exactly which one is colliding with a wall
also yeah, circles are generally nicer
can u use layermasks w/ those? im pretty sure u can..
you can, yeah
id just mask out my player and have 1 on each side
so you can make a layermask which only collides with walls
so you cant walljump/wallslide off of, say, enemies
basically
Wallslide Right
else if (OverlapCircleOnLeft == wall)
Wallslide left```
this isnt how OverlapCircle works ofc
it just returns to you an array of colliders
you can look through that array and see if there are any walls in there
i'm confused so overlap circle is added to every single wall in the game and it checks if the player is currently colliding with it?
no
basically
you draw a circle around the player
or, in this case, on the left and on the right of the player
and if the circle overlaps with a wall, then use wallsliding logic
there are other ways of doing this wallsliding too, now that I think about it
but I won't confuse you any more
I'm sorry if I'm not understanding but isn't this basically the same as the triggers? I set up one on each side and if it overlaps I do the wallslide logic
basically, yeah
OverlapCircle returns an array of Colliders that are inside of it's radius
oh interesting
You don't add it to anything, it's a method you would call
you just need to check if any of the colliders is a wall
Similiar to raycast if you are familiar with that
I am not
raycast basically draws a line in a direction, and tells you what it hit
oh wow
basically imagine it for like guns
ah so you shoot the bullet and see if it hit anything
hit-scan vs rigidbody projectiles
well, you check if there is a target in front of the weapon's barrel
well it draws a ray a direction * distance... and returns true or false.. if true u can dig deeper and get the RaycastHit variable back from it
w/ all the info on the hit, position, what it was etc
just remember theres 2 variants..
personally I use raycasts in my game
theres Raycast.. and Raycast2D
for now I might just stick with the triggers i have cause I think the OverlapCircle might be overkill
those green lines
interesting
I basically check if the rays ever touch the player
in which case I make the enemy attack
smart
actually, @rocky canyon, is overlapsphere or a raycastcommand more efficient?
are there gonna be multiple players?
why not just reference the player and check the distance?
- a raycast to check line of sight
nope
thatd work too
I dunno, I've seen this method used way more
plus it was a nice way for me to learn about jobs and raycastcommands
raycast legit.. I think raycasts are more performant..
but i think u could also make overlaps pretty close.. using the Non-Alloc version
oh yeah, I know why actually
you use raycastcommands for cones of vision
but for me it doesnt make much sense to use raycastcommands because I check in a circle
ya totally.. use w/e u feel comfortable with
I guess theres the option for me to use cones of vision at any point tho
This should be executing or am I doing something wrong?
I mean, for me this is a school project, so its w/e
I like the way I made my enemy AI code because everything is customizable
well, debug the values you're checking
searching, chasing, dodging, firing
@true owl the topic got a bit off track, I hope u understand what u need to do
if u need further specifications, just ask :)
Oh, okay, I know what I am doing wrong
quick tweak, I made it so the tanks can have varying angles of vision, so using raycastcommands makes more sense
good call on this actually Chris, ty!
How do I... get a list of all child gameObjects that contain a specific script?
GetComponentsInChildren<ThatScript>
Note that this also includes the object itself, if that object has the script on it
soooo many raycasts 😄
i like the way it makes those cool grid/wavy scanlines
So that does a return a List already?
(s) makes me believe its a collection of some sort yes
no it returns an array
forgot to reduce the amount after changing the angle xD
Mmmmm.... I was setting everything with Lists....
using UnityEngine;
public class GetComponentsInChildrenExample : MonoBehaviour
{
public Component[] hingeJoints;
void Start()
{
hingeJoints = GetComponentsInChildren<HingeJoint>();
foreach (HingeJoint joint in hingeJoints)
joint.useSpring = false;
}
}```
its funny because I could have like 50 tanks using 100 raycasts every frame and I still wouldn't have much performance issues
(fwiw you could also check the angle with the player, but this probably lets you do more complex ai 👍)
i use a custom tick-rate for mine..
every (x) amount of seconds it fires off a ray
and if I do, I can just reduce the amount of checks per second
I can do that too, yeah
tho thats still scary cuz of lag spikes
so I also have a function to smear the calculations out over x seconds
so I dont have 30 checks happening in one frame, rather over x amount of frames
maybe, but that maths sounds abit more complicated
not really, there's built-in functions for it
fuckin flashbang, dude
lol.. this is beautiful
who needs overlap sphere when you got overlap lattice
overlap world
now draw a wiresphere everywhere two rays intersect 😉
...you can do that? i thought rays cant hit each other
u'd need some custom maths
also, this is just my debug rays being fucked
I'm trying to fix the angle, but i cant
I am assuming that the array does get the components in descending order on the hierarchy?
what angle?
i think it may be distance related.. like first come first serve
but that i dont know tbh
components aren't guaranteed an order
not sure if that still holds over multiple gameobjects though
it starts checking from transform.forward, but I want it to check from transform.forward - (scanAngle/2)
basically rotate the cone (scanAngle/2) degrees
im just way too cooked mentally to do quaternion maths rn
Like the ListOfEntities is supposed to store the reference to each entity present, so basically has a list for Enemies, Players and Waypoints, and I want the script for it to take each of the parent GameObjects and take the script of each of the entities inside them, since, basically all of them have the script I am looking for
hello, I would like to understand why I have a capsule even though I never asked for it
do u have a CharacterController?
you could do that to prioritize stuff directly in front
It's not a Bug, it's a Feature!
the ship gif i sent i have my raycasts start by using spacing between the rays and the number of rays i want.. and then it auto-centers..
me ?
thats the thing, it ignores half of what's in front of it
yea... thats why
a CharacterController has a capsule collider built in..
just make 2 loops to check the right side then the left side
Technically, CharacterController is a Capsule Collider
yea there ya go ^
ah ok so how do I remove the capsule?
remove the Character Controller?
thats not the issue, but i figured it out
u can't have a character controller w/o a capsule collider.. like digiholic said..
its one of the same
if u dont wanna see the gizmo. just collapse the Component
you can turn off the gizmo, if that's what you're asking?
is that really more efficient than using something like overlap sphere?
Remove the CharacterController
well I use a raycastcommand, so maybe it is, idk
Chances are you need that though
well basically I want it to be the same size as the human
you can change it's height and width
Then you'll need to adjust the properties on the charactercontroller until it is. Change the center, radius and height until it's what you want
or position the graphics (ur model) to be centered to the capsule (as it is)..
b/c it'll start properly centered
I see what I can do
2 unity units = 6 foot 5 inches
we flexing rn? xD
nah, my rooms already warm enough 😛
oh yea, cool.. u already have an interval built in.. timebetwenscans
awesome.. mines a singleton "TickManager" i call events from.. then first the ray off b/c its listening
yeah, i think i mentioned it
same concept
thank you (I'm a beginner, that's why I'm struggling)
gotta learn somehow 💪
You realize most of these rays are useless, if this is for vision
Normally you'd do an angle check to see if the target is in the view cone, and if it is, cast a ray to check for obstructions
well, yeah, I could optimize it further by checking for distance
pretty tho
I know, but this is for a school project, so I'm not going for 100% optimization
I mainly did this to learn about raycasts
also, I see a lot of people do it this way, even though your method makes way more sense
I usually do like sphere then calculate angle then raycast for obstruction
if theres only one player, you can also just check the distance between it and the player
so no need for spheres
yeah true
I have a character, what is better to use, aggregation or composition?
Why is everything so easy and difficult at the same time?
I feel like this depends on what it is you do. Some people swear by Association/Composition but not everything works well by just doing it this way. It really depends on your use case
In the end it's a combination of all of them
is Time.deltaTime supposed to increese?
It is the amount of time in seconds the last frame took to render. It'll fluctuate often as your framerate changes
tnx, so im the one wrong and not unity to blame
Abstraction layer and minimal inheritance, then focus on composition
whats difference between private void update and void update
nothing just you dont need to type it (but I do anyway)
No accessor implicitly implies private
So nothing
(access modifier)
You shouldn't
yeah, you can't find the "other" collider in a trigger message
You'll want to put them on separate game objects
Multiple colliders of the same type on the same object should basically be considered the same. If they do anything different, they need to be on different objects
How it works:
The Rigidbody involved in the collision will detect when it collides with a collider. It will then call OnTrigger on every component on itself, then every component on the object with the collider it hit.
So, you'd need a script on each thing with the collider on it that handles its own case
Yes. Assuming the rigidbody is the one moving into these, rather than these being children of the rigidbody that moves
i'm pretty sure trigger messages are sent to the object with the trigger collider on it if they are a child of a rigidbody
I forget which way it goes, but either collider or trigger messages don't get sent to components on the same collider
u can't really do that.. and single out individual colliders
but this still 100% seems like a usecase for physics queries rather than relying on trigger messages. of course they won't say why they want to use physics messages
It's one or the other
pretty sure it's OnCollision messages that don't get sent to the child collider
If you just need to detect when you stop colliding with something you can just run the physics query in update and see when it returns a different result
i always build a simple test script when dealing with these type issues..
by testing out the messages w/ multiple objects and different hierachy setups it can really solidify understanding how they interact
for what purpose
Maybe? Unsure what you specifically need
ya, lets hear the use-case for this
please explain what you are actually trying to accomplish
and i don't mean some vague abstract description of what you think you want, explain what you are actually trying to do with this
https://xyproblem.info
If you literally just want to know what objects are within range once per frame, OverlapSphere
It sounds like they're detecting when an interactable object gets in range.
^ im itching that direction as well
It does sound reasonable to just use trigger messages to notice when they enter and exit your interaction range
these are implementation details; you need to explain the actual gameplay you are creating
note that if you only react to the OnTriggerEnter/OnTriggerExit messages, you'll need to keep a list of interactable objects that are currently in range
six of one, half a dozen of the other (:
Okay, so if you want to know if the player is within range of the interactable, why not put the larger trigger collider on the interactable, and have them check if they're within range of the player?
You can still use a normal collider to detect when you collide with the object directly
i think i remember now.. were u asking about the WorldSpace UI the other day for pickups?
Decentralized is kind of the goal though
uh oh
Each thing should take care of its own functionality
Then you can do that, probably with OverlapSphere
oh, okay, not the worst: but I would rather use a Dictionary<Interactable, InteractionPrompt>. you'd have an Interactable component that represents a thing you can interact with, and you'd have an InteractionPrompt component that handles showing the name, image, etc. for an Interactable
Ok, I am freaking becoming crazy, this says that those Lists are never read. They are supposed to get a copy of the data of another script (ListOfEntities) and this one does show to gather the List data properly, but then, when passing it, it's empty? What am I doing wrong? I don't get it
Then you can do that, by putting scripts on the interactable objects
Show !code for ListOfEntities
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
please share a paste of the entire script, rather than a screenshot of most of it
i suspect you two are envisioning completely different systems right now
Pretty sure the = new List< stuff is gonna get run on Start since it's in the constructors, even though those are serialized fields? Try removing them
the field initializers execute before Unity even deserializes anything
I see no reason to do this!
Make small components. Put them where they're needed.
Okay, so that wouldn't be it. Second guess is that the Get___ functions are clearing them and finding nothing
The most common source of project disorganization is having too few scripts, not too many
The more scripts you have, the better
SingleResponsibilityOLID
So... do I not initialize the Lists?
I was mistaken about the order, this is likely not the problem after all
Cause the List I get from that ListOfEntities is actually accurate
Put logs in your Get___ functions where you clear the lists, see if they find anything
It's just not passing it correctly and I don't know why
I don't really understand what your problem is here.
Is the problem that these lists are empty after starting the game, when you expected them to be non-empty?
These 2 Lists should match, they don't
Do you have more than one "List Of Entities" component?
Nope
Oh wait, these are different components, just with variables of the same name?
The whole reason to have that is so I don't have to create a whole List anew for each entity, so it only happens one isntead
You are replacing the reference that you assigned in the inspector, which is suspicious.
If the purpose of these variables on NavMeshTargetSetter is to always reflect the values in ListOfEntities, why not just cut out the middleman and use the lists from ListOfEntities?
As I said: Make small components and put them where they're needed.
You'll create an InteractableDetector component on "Collider Interact". Its sole job will be to tell a component on the Player when things go in and out of range
It basically is
Hi, my card game object is being destoyed on play, but i have no idea why. How can i see what destroys it?
You can log something in OnDestroy
then look at the stack trace for that log entry
That will give you a hint, at least
The latter is a way to achieve the former.
So, why have a local copy? Just use the lists from the ListOfEntities
But that's pretty much waht I am doing
They just have a variable for that
So I can tell if they are passed correctly
did you verify that any of your code is actually running
i would also still suggest getting rid of that FindFirstObjectByType call and seeing if the result changes.
No, it's not, you're creating a second variable that's meant to be a copy of another one. Just use the first variable
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
string scriptName = "Unknown Script";
if (stackTrace.FrameCount > 1) {
var frame = stackTrace.GetFrame(1); var method = frame.GetMethod();
scriptName = $"{method.DeclaringType?.Name}.{method.Name}";
}
Debug.Log($"{gameObject.name} was destroyed by {scriptName}!");
}```
i tried something like that, it was destroyed by uknown script
Any other way?
I may know what's going on here.
You're sharing a reference to the same list that ListOfEntities is holding
But Unity's serializer doesn't really care about that.
I actually don't know how it handles that situation...
I mean, you're literally setting the script name to Unknown Script. Just do a normal log in OnDestroy, then look at the stack trace in Unity
It's meant to find the type name of the method
but yes, just look at the stack trace :p
Note that there won't be much of interest if it's a delayed Destroy call
It wouldn't change the result, like, it's pretty much just placing and extra "=" sign
im very new, is there a way to tell if a gameobject has moved up by like 5? Like if it goes up by 5 then itll do something
What do u mean?
It would change things, because if you just use the variable directly then you cannot possibly have an ordering problem
Have a single source of truth. Use that.
Don't copy a bunch of data around and just hope you kept track properly
oh, yes, I see your ordering problem
this creates a new list
NavMeshTargetSetter is holding a reference to the original list
which was cleared and then thrown out
That's definitely not it -- I was wondering if displaying the component in the inspector was causing a new list to be created.
Anyone that grabs possibleEnemyTargets before ListOfEntities.Start() executes will wind up with references to the original list object
But this only runs at the Start of the ListOfEntities, right?
Should not cause an issue later
So are u saying this is sending the List AFTER the clear, but before refreshing it??????
No.
List<int> foo = new();
List<int> bar = foo;
foo = new();
foo.Add(1);
bar contains a reference to an empty list.
You know what could solve this?
Just not having two lists
NavMeshTargetSetter is having its Start method called before ListOfEntities.
Therefore, it is getting a reference to the list that ListOfEntities starts out with.
ListOfEntities throws this list out and creates a new one.
You have a reference to the listOfEntities. Just do listOfEntities.possibleEnemyTargets
Then how the fuck am i getting the Waypoints?
because you don't throw the original list out
you just clear it and then add things to it again
So why would that be different than replacing it for a new one?
because it's the same list
Do you not understand why bar contains an empty list in this example?
as compared to this example
List<int> foo = new();
List<int> bar = foo;
foo.Clear();
foo.Add(1);
If your hamster dies when you're away at summer camp and your parents buy a new one, it's still not the same hamster, even though it's in the same cage
where both foo and bar contain a reference to a list with a single number in it
From what i understand it points at the line in the script AFTER destoy method, which doesnt make any sense
one hell of a message to join in to
lmao
Oh, wait
Am I doing that?
I may
yes
You're doing both.
Which is why you shouldn't have a second variable that is meant to hold the same data
In some places, you are creating an entirely new list. In other places, you are inserting items into the original list.
If you want to add a bunch of things to an existing list, use AddRange
But yes: I see no reason to add this layer of indirection
at Draw.OnDestroy () [0x0003f] in E:\Tarot Chess — kopia\Assets\Scripts\Cards\Draw.cs:38 ```
You are accessing gameObject.name when gameObject is null
That's line 38
Or wait what's the issue
It is so confusing... I mean i just play a card and it seems to be deleted when it was supposed to change parent
how do you change parent?
{
if (playedCard != null)
{
// Transport the card to the graveyard
MoveCardToGraveyard(playedCard);
}
else
{
Debug.LogWarning("Played card is null.");
}
}
private void MoveCardToGraveyard(Transform card)
{
if (graveyard.Contains(card))
{
Debug.LogWarning($"Card {card.name} is in graveyard.");
return;
}
card.SetParent(graveyardObject.transform, false);
card.gameObject.SetActive(false);
graveyard.Add(card);
Debug.Log($"Card {card.name} moved to graveyard.");
}```
are you sure that the issue is that it gets destroyed, not that it gets deactivated?
thats my best bet
also, not entirely sure, but you might want to move the object to the graveyard before disabling it
waitt
I cannot find it anywhere by search
card.SetParent(graveyardObject.transform, false);
Actually there may come the case where the List of all Entities is not the same that those the entity has access to as targets
But ya
what does your hierarchy look like?
https://paste.myst.rs/uta0c8xz
something simple like this might get the job done..
u'd need a bit extra logic ofc.. (for example having two interactables close enough that the script would trigger twice)
but the basics are there..
To interact w/ a script you only need a reference to said script.. and public variables and/or public methods
not that hierarchy
So what do you mean?
im not involved in w/e u guys conversation is.. i was talkin to Vengeful
the objects im interacting w/ are these if u were askin about me lol
I know, I just needed a screenshot of a hierarchy
OHH okay i see
yeaa ty xD
Here you go, but thanks to this i looked at it again and it seems there is something that may be the culprit, but im not sure.
using UnityEngine;
namespace demo {
public class CardDestroyer : MonoBehaviour {
public CardContainer container;
public void OnCardDestroyed(CardPlayed evt) {
container.DestroyCard(evt.card);
}
}
}
"my cards are being destroyed without me wanting them to"
hierarchy shows Card Destroyer
could there be something calling that function?
time to debug 🙂
try to log it every time it gets called
vertx huh how page has a good writeup on how to reference other scripts..
https://unity.huh.how/references
Choose the best way to reference other variables.
or referencing in general.. may want to check it out as well
Ok, just wait a sec, unity crashed
Ok, it all is mega weird. I disabled the shit out of this, and now ill implement correct changes in other scripts. Thanks
[SerializeField] Camera mainCamera;
When i try to attach my camera it says type missmatch
Why is this happening?
in your ide, hover over Camera to make sure its not another type
e.g. a monobehaviour called Camera
and if it is the correct type, that means you are trying to drag a scene object into a prefab which is not possible.
https://unity.huh.how/references/prefabs-referencing-components
in the Hierarchy?
in your ide
where ide means "Integrated Development Environment" and refers to your code editor
you want to see
When it says Type missmatch in the inspector its cus you changed the type of the field and the old value is still in there but invalid.
it will also say Type Mismatch if you try to drag something that doesn't have the correct component or if you try to drag a scene object into a prefab
doesn't it just not do anything?
My object(player) wich has this script assigned is not a prefab
there were two things i said that it could be, if you have determined it is not one of those then it must be the other
well i sent an image with my camera object wich has a Camera Component
and did you do what rob5300 suggested and confirm that you are using UnityEngine.Camera and not perhaps some other Camera class, like one you may have created?
Oh right my camera is just as class camera not UnityEngine.Camera but the intelisense or however its called only autocompletes with this camera not any other Camera that is of UnityEngine.Camera
and have you created your own class called Camera?
pffffff right.... the script is called Camera so its the class
yeah so that would be the problem. don't name your components the same as other components and there won't be any issues like this
Thanks the problem is now solved
thats why i suggested checking in ur ide to see. You can also declare the type with the namespace in it to make extra sure:
[SerializeField]
UnityEngine.Camera cam;
Not sure why but when my character jumps they don't have a parabola, they lose a lot of their speed after the peak of their jump
A tool for sharing your source code with the world!
even after I comment out AirModifier and JumpModifier
Oh i didnt know i can do that thanks
When you manipulate the velocity directly you have to be careful..
for example ur Run() method runs every frame even during jumps and stuff..
void Run()
{
if (isDashing || !isGrounded) return;``` wonder what happens if u were to return out of the run method if ur not dashin or airbourne
wait what
you mean the applyMomentum?
wait
that is ancient code
sorry
A tool for sharing your source code with the world!
idk why it got my old code
this is the new thing sorry
i mean, it looks fine
it just wont execute anything
if i want to make some sort of 2D camera movement like to to slowly move twards the cursor do i need to assign to my camera a rigidbody to use forces? or is there another way
ya, when jumping or dashin it wont.. but i think his problem is b/c the Run() method is using input to manually override linearVelocity during his jumps
then causing it to not have a perfect parabola
@rocky canyon
that is old code i pasted the wrong thing
A tool for sharing your source code with the world!
oh alrighty
ya sorry
u got plenty of variables to work with..
i think u could remedy it by fine-tuning the values
especially since it appears u have gravity modifier before and after the peak of the jump
i remember making mine.. and i had to iterate many many times to get everything working correctly together..
by changing the drag, friction (air resistence in my case), and my control multipliers i was able to get a decent feeling controller
(carries momentum and all that jazz)
but its basically running in different states..
is it grounded -> use all these values
is it airborne -> use all these values instead
well the thing is i commented out all the jump modifiers and air modifiers but still it doesn't go normally
you have heck of alot of code there..
without having it 1:1 on my machine i can't assume how everything works with everything else..
if it was anything like mine.. theres alot of little things working together.. and against each other at various times..
ur the only one thats gonna have a good feel for what alls going on lol
best of luck mate.. i'll come back around to it and check if i can't see something but right now nothing stands out at me
gotcha much appreciated
A tool for sharing your source code with the world!
heres a snippet of mine.. and u can see theres tons of comments telling me.. (remove this force if this..) (make sure to add this force if this) etc etc
it can really help to expose values in the inspector that way u can monitor them a bit better..
i've also used gizmo's and stuff to draw out the trajectory to test
interesting
i appreciate all the helkp
i've been coding for a bit now so I'll take a break and get back to it later maybe
If im comparing 2 vector2 vectors being a velocityVector and Vector2.zero does it compare the values , the magnitude or the vector instance?
Vector2 is a value type, so it would be very hard to do a reference comparison 😉
and just to help speed-run the issue...
i'd try testing w/o movement at all.. should be able to Jump in place and then maybe take a recording.. or even write some code to log numbers and values.. to make sure the RISE of the player is = to the FALL of the player
Oh ok thanks i will just compare their magnitudes so im sure i get what i want
Compare the magnitude of their difference against a small value.
(that's what the == function is, but you might as well pick a specific threshold)
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mathf.Approximately.html Mathf approx to the rescue
New to unity 😄 whatsup everyone 😄
ofc if you want a "bigger" threshold then you should do it yourself
notably, operator == for Vector2 uses a much larger threshold!
Hi, is there any repository GitHub, YT Video, or something else to understand, how is it possible to code an inventory system in Unity with Drag&Drop?
If there are different ways of that, I'd like to read all of them. 😄
A quick and dirty way is you have a sprite constantly follow the cursor and when you click on something(e.g. a button press) you make the sprite following the cursor display the image you clicked.
Wow, nice way. 😄
What are some good short and brief youtube tutorials for unity that are great for a beginner to watch?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
brackeys. but definitely consider checking learn^
ive heard good things about him but im not sure which one of his videos to start with... i heard there is a endless runner with a cube as the player but for some reason i cant find it.
check the playlists tab
but also you should really check out learn, if you haven't already
People say CodeMonkey is good too. But I've never ever watched even one video.
hello everyone. Is this the right channel to ask for coding help?
no
(it is lol)
definitely. his tutorials can get a little complex at times but they're still great learning resources
also !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
hey, whats the difference between update and fixedupdate?
he's okay.. if u dont mind installing his Utilities, or going onto his patreon for code he uses
and if u can tolerate the awful noise his keyboard makes when he decides to do a sped up time-lapse 😄
update every frame.. fixedupdate every physics frame
oh
i mean cuz im having some issues in the animations and i thought was due using fixedupdate
what would happen if i replace fixedupdate with update?
it depends entirely on what you are doing in FixedUpdate and what your actual issue is
it'd run every frame.. as opposed to each physics tick..
oh, interesting
well, the issue i have is the animation is glitched
like is overlapping
and i think i did something wrong in the script
cuz i did the same in the other npcs
and they work right
this is an example of the code
{
rb2D.linearVelocity = new Vector2(runSpeed, rb2D.linearVelocity.y);
animator.Play("Base Layer.valeria_walk");
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2D.linearVelocity = new Vector2(-runSpeed, rb2D.linearVelocity.y);
animator.Play("Base Layer.valeria_walk");
}
else
{
rb2D.linearVelocity = new Vector2(0, rb2D.linearVelocity.y);
animator.Play("Base Layer.valeria_idle");
}```
i dont know what im doing wrong
be more specific. also finish a thought before sending the message instead of spamming the channel with half a dozen messages that all together comprises a single sentence
!ask
i have a vid that explains it
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
you're meant to read the bot message, not parrot the command
you can put cs after the start of the ``` above your !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 im new to this
btw is there an "example" for a 2d player? i mean cuz i feel like my player script could be more simplier
to me it looks like the keyframes are super short..
check out some of the resources on !learn . or check the asset store
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if you read the documentation pinned in #🏃┃animation you can learn how the animator works to better understand how to use it
sure? cuz i checked the animation window and it works well
the issue here is, i did the same with my Npcs
they worked as a charm
what went wrong?
well that walk cycle look like he on Speed
but it could also be transition problems
she, but yeah, but the animation still works, even when is idle
where ur starting the animation over and over and over w/o it ever finishing
is it set to looping?
LoopTime
if its a single keyframe.. im pretty sure it should be set to looping
ah ok.. just checkin
but its still animated even when idle
wich is...odd, obviously
you're kidding me. I dont know why, and i dont know how, but...its fixed
ah no
nvm i know why, and its not pretty
i have a script that detects if the player is in ground, if is, it will display an idle animation, if is not, it will display a falling animation...I need that script
this is the script, what i did wrong?
{
animator.Play("Base Layer.valeria_idle");
}
if (CheckGround.IsGrounded == true)
{
animator.Play("Base Layer.valeria_jump");
}```
you should learn how to use the animator so you can properly transition between your animations based on different conditions instead of hardcoding which animation to play
hello. I too am having a problem with the unity....
I made a script to detect when i click an object based on raycasting (this works no issues)
problem lies that i assigned a variable in the inspector and unity is telling me that the field is null 😦
there's probably another instance of that object in the scene at runtime where the variable is not assigned