#💻┃code-beginner
1 messages · Page 136 of 1
Explained already here
oh i think i get what you mean
so if the angels that are within the overlap sphere are above or below a certain angle from the player's forward then i can determine whether or not they should be frozen?
I have this issue where it seems that the AI does not recognize the area and is just turns around on a loop. I tried baking the scene for the nav mesh but same results, this is the code:
void SetRandomNavTarget()
{
int maxAttempts = 10; // maximum number of attempts
for (int i = 0; i < maxAttempts; i++)
{
Vector3 randomPosition = Random.insideUnitSphere * 30;
randomPosition.y = 0;
randomPosition += transform.position;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPosition, out hit, 5, NavMesh.AllAreas))
{
Vector3 finalPosition = hit.position;
position = finalPosition;
nav.SetDestination(position);
return; // break out of the loop if a valid position is found
}
}
//if we reach this point, it means no valid position was found :(
Debug.LogError("Failed to find a valid target position on the NavMesh after " + maxAttempts + " attempts.");
}
add a debug log when a destination is set for the agent. I had a similar issue and the problem was that my script was constantly setting a new destination for the agent and so he barely moved at all
Thank you, will try!
It does messup a bit at high speeds but that's probabaly fine. However now the paddles seem to not even collide with the borders even though in my old code the paddles are not able to go past the borders, is there a way to fix that?
Old Code:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float movementSpeed;
[SerializeField] private bool isAi;
[SerializeField] private GameObject ball;
private Rigidbody2D rb;
private Vector2 playerMove;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (isAi)
{
AIControl();
}
else
{
PlayerControl();
}
rb.velocity = playerMove * movementSpeed * Time.fixedDeltaTime;
}
private void PlayerControl()
{
playerMove = new Vector2(0, Input.GetAxisRaw("Vertical"));
}
private void AIControl()
{
if (ball.transform.position.y > transform.position.y + 0.25f)
{
playerMove = new Vector2(0, 0.5f);
}
else if (ball.transform.position.y < transform.position.y - 0.25f)
{
playerMove = new Vector2(0, -0.5f);
}
else
{
playerMove = new Vector2(0, 0);
}
}
}
new code:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float movementSpeed;
[SerializeField] private bool isAi;
[SerializeField] private GameObject ball;
private Rigidbody2D rb;
private Vector2 playerMove;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (isAi)
{
AIControl();
}
else
{
PlayerControl();
}
}
void FixedUpdate()
{
rb.velocity = playerMove * movementSpeed;
}
private void PlayerControl()
{
playerMove = new Vector2(0, Input.GetAxisRaw("Vertical"));
}
private void AIControl()
{
float targetY = Mathf.Clamp(ball.transform.position.y, transform.position.y - 0.25f, transform.position.y + 0.25f);
float step = movementSpeed;
float newY = Mathf.MoveTowards(transform.position.y, targetY, step);
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
}
}
idk too well how your mechanics work, but if the paddles are going past the borders then you could try different approaches to moving them. Like using the rigidbody with rb.MovePosition
that way you should be able to stop the paddles from moving past the borders by simply using a collider
You're mixing transform.position movement with Rigidbody movement
If you want proper physics only move via the Rigidbody
finally had this drilled into my head after messing up player controllers so many times 🥲
How would I do that? I kinda just borrowed the ai control from the internet
How do I assign all children a LayerMask again?
You can't assign a LayerMask to an object, only a layer
In the editor you can simply select all the objects at once and change the layer in the inspector
Ohh, how would I do it then, I'm trying to do it runtime
It's just a simple property on GameObject
https://docs.unity3d.com/ScriptReference/GameObject-layer.html
I tried this way
foreach(var t in sections)
{
t.gameObject.layer = placementLayer;
}```
but give me error
**A game object can only be in one layer. The layer needs to be in the range [0...31]**
LayerMask.NameToLayer takes only string but not very neat
I guess LayerMask is only for Raycasts?
You're passing in something other than a number between 0 and 31
placementLayer is LayerMask
Layers can only be a number between 0 and 31
Layers are not the same as layer masks
Completely different things
Don't mix them up
Layermask in number between 0 to 0xffffffff, it is bitmask
just seems dirty to use integer
Use NameToLayer if you want to use a string
Oh ok what if my layers change , do I just change inspector value of string?
Yeah I will do that thanks!
In the update method I was doing it, now fixed it but the issue persists
how do I see how many lines are in a .txt file?
string[] lines = File.ReadAllLines(path)
int numbersOfLines = lines.legnth```
Question here:
The capsule is the player, when switch scene from another scene using asyncLoadScene, I want the player instant trigger the collider (blue box)
This works as fine in the editor play mode, but when it comes to the build, it cannot. What could be happening?
The capsule is probably already intersecting with the collider when physics starts processing the new scene.
Might want to use an overlap query on scene load or just avoid that situation entirely(preferable).
After I move the collider out of the player and tried to trigger it manually, it still fails
Is there a way to check whether it is player or the collider that causes the problem in build
sounds like it's not set up properly
can you be more specific? or code is needed?
Code and/or setup in the scene. Start from sharing code and explaining how you confirm the issue.
Can anyone send me a good beginner c# tutorial
Please link to large codeblocks !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also, this all could be improved massively by caching variables, using Camera.main, and getting rid of whatever on earth .GameObject() is
sorry didn't know I need to do that, I'm fixing it
check pins in this channel
Thanks
Here is my code, the first and second part is for the dialogue trigger which I intended to trigger right when the player enters the scene.
The third part is the opening, when enters the game plays the opening video, scene switch when the video ends
If you need to trigger it when it enters the scene, what do you need the collider for?
Just call it on scene load or some time after it.
I made it a serial prefab that triggers in order and that one is the head
Also, not sure if it's relevant to your issue(could be), but your EnterGame coroutine doesn't do anything.
Not sure what that means and how it's related to the issue at hand.
I did what the Unity document demonstrates how to switch to another scene
I'm sure they don't have a coroutine like that. If they do await for anything in it, there're probably more lines in it. Check the docs page again.
I believe i am supposed to attach all enemy stuff in my enemy script to a prefab but when i do that the code does not work
My idea is the player will trigger the blue box and each blue box will enable the next one, at the same time the npc will follow according to the green cylinder.
and each blue box is holding a dialogue I'm making sure that the player doesn't trigger the later one before its time
That's sounds like a very bad approach. You might want to look at the timeline package for scripted cinematics /cut scenes.
hmm my initial thought is that in most games player will get to a place and trigger dialogue. Thus, I can make it like this and let the npc talk to the player with the player's pace
Not necessarily. A trigger collider can be used if it's a location based cut scene. But there could be many other types of trigger conditions. For example, completing a certain quest, killing an enemy, loading a scene(your case), etc...
Did I said that after the opening video is played this scene will be loaded?
I want to do a full screen opening video -> sceneload -> trigger the first dialogue
Then trigger it via code when the scene is loaded.
So it sounds to me.
Does that mean I'm creating another script for this specific case?
No necessarily. You could execute the code from the Game/Level manager. Probably LevelManager, since it's an event unique to the level. Could even use some kind of SO based system to configure what cut scenes play on what scene start.
hmm I see, thanks for the support kind person ❤️ truely appreciated
if I were to define a list of lists of vector3s:
List<List<Vector3>> segments = new List<List<Vector3>>();
would that be expensive, in terms of computation or memory?
Depends on what you do with the list and how many items you have in there
Compared to what
As it is it's just an empty list BTW
If you put a lot of lists in here sure that could take a lot of memory, or a few very large lists
As far as computation goes that would depend what you do with it
oh sweet, so what I'm hearing is empty lists dont take up much memory and are pretty fast to create? (compared to maybe a regular vector3)
for some reason I thought memory might be allocated based on the maximum size of the list :P
Simply defining it has almost no computational cost
Memory will indeed be allocated based on the size of the list
Or rather the initial capacity but its good practice to preallocate that with some sane number
I don't see how you're comparing this list to a vector3. It's a list of lists of Vector3s. Depending on how many vectors you put in it it will take up memory
Eg if you know your gonna have around 500 elements in the list eventually just pre allocate that and save on the resize performance cost
see, I wasn't sure if that was the case :) I'm going to look into "pre allocating" lists now, that is not something I'm familiar with 👍
Don't worry about the preaplocation thing yet
It's premature optimization
Obviously the data has to go somewhere though
Lists don't give you free memory magically
understood, hence me asking about it and looking for best practices 👍
How do u make a 2D object half transparent
two meshes, two materials
or if you just want the opacity to be different on parts then you modify the values on the textures or change the UVs
where
my object is currently using the default texture
UVs -> blender
textures -> any art program
so u cant do it in unity?
can also do it via shaders but that's a little more harder if you've not used them
if you want to do it in unity then probably shaders
You certainly don't do it with code unless you randomly add more context to the question that makes that clear
which begs the question...
ehhhh i cant do it with code?
cuz im trying to make when the player walk behind the object it will go half transparent
There's a number of ways to go about that. Depends on the render pipeline, the camera perspective with the objects, the whole setup
Do you just want the whole thing to be at half alpha? That'd just be the alpha channel of the SpriteRenderer color
oh yeah that works
oh you just wanted the opacity lowered eh
(sorry half awake and must have read over your previous reply)
i am doing this
private void Start()
{
Instantiate(EnemyPrefab, new Vector3(0, 1, 25) , Quaternion.identity);
}
but it spawns alot of enemies rather than just one
the script is attached to the prefab which i placed in the scene
EnemyPrefab is set to the enemy prefab in the editor
Every prefab spawns a new prefab
Dont let the prefab spawns itself
i have an issue where enemies which are instantiated after the first one is killed
all spawn with 1 health
so i tried that as a solution
i thought that would work because it would be spawning in new instances rather than copying the dead one
https://learn.unity.com/tutorial/introduction-to-object-pooling
Not related but you should have a look
Object Pooling is a great way to optimize your projects and lower the burden that is placed on the CPU when having to rapidly create and destroy GameObjects. It is a good practice and design pattern to keep in mind to help relieve the processing power of the CPU to handle more important tasks and not become inundated by repetitive create and des...
Ill do that now
i can spawn in the prefab now by having that code on a different object
but the enemy just sits there
if i put the enemy prefab into the scene and assign it to things also in the scene then it works
but then i have the old issue
For the prefab not in the scene it seems like i can only add things in its editor that are other prefabs
private void OnTriggerEnter()
no reaction tho
yeah
perhaps that
i did that
did you do these after {}
Go through this resource https://unity.huh.how/physics-messages
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pillarScript : MonoBehaviour
{
public SpriteRenderer spriteRndr;
// Start is called before the first frame update
private void OnTriggerEnter(Collider collision)
{
Debug.Log("a");
//spriteRndr.color += new Color (0, 0, 0, 127);
}
}
i did this
to anyone who can guide me since i’m a beginner in this, i have this assignment to make but here’s the context before i inform u ab my problems
From a 3D game i made it into 2d perspective and created a rectangular cube for the cannon
the thing entering the trigger also has to be set to a trigger i think
nvm solved
winning
i forgot to do trigger2D
Hello. Can someone confirm or deny, please? Basically tried to implement the 3rd person navigation with clicking the mouse on the surface (using raycast and also navmesh). But it doesnt work. The controllable player does not move towards the point. Using the starter pack for 3rd person controller. Pretty sure that code is correct and I am also doing everything like it should be done. What could prevent character from moving?
Cannot modify the return value of 'SpriteRenderer.color' because it is not a variable i dont understand this error
spriteRndr.color.a += 255;
``` here is the line of code
My thoughts: something in starter pack: third person controller prevents it.
man thanks alot thie website is cool
Typically, you only need the navmesh agent component for moving on the navmesh. Anything else that might be moving an object would be fighting the navmesh agent potentially causing movement issues.
Yeah, but to locate the MoveTowards coordinates one needs raycast. At least that's how brackeys suggests it in tutorial.
@gaunt ice hey do you get my issue or is it not explained well
And yes. I think that somehow the beginners pack third person controller fights it. I guess I will just have to create my own third person controller and camera follow
Why do you need a controller if you're using a navmesh agent?
Isn't it moving with rb/CC? You wouldn't need any of these with navmesh agent.
Till now I was controlling the character by using wasd. Now I want to swich to mouse click + navmesh.
Well, then you'll need to remove or disable the previous controller. Otherwise they would be fighting for control over the character.
Oh, okay, that seems very logical. Gonna try that when I get to my pc) Thank you
How would you usually set up an enemy for a shooter cause i guess me winging it has caused issues
if you needed an enemy which died, then spawns a new one on death
how would you go about it
ill link my enemy code if someone thinks that will help
but i think the issue is with me just not getting prefabs
i had never done this before, i just want to know if its possible
void start:
mask = maskA.gameobj;
--------------------------
//maskA.gameobj is destroyed
if (mask == null ) {
instantiate (mask);
}
maskA referenced in field already at beginning
wait u can lol
You'd have something like an EnemyManager that keeps track of the enemies. When one enemy dies, you decrement the counter of living enemies for example. Then you could also use that counter to know that you need to spawn a new enemy. At which point you would instantiate a new enemy from a prefab.
what would be a "good way" to calculate the distance traveled in 1 axis ?
doing currentX - startX does the work, but because i am doing a infinite runner this might be costy if the player does a long run, because the UI is updated at each frame
well since im doing only 1 axis yeah
idk if vectors are "more" calculations, because its just doing 3 additions instead of 1
sometimes i feel like all PCs are running on a potato xD, I need to stop doing "bad optimizations"
i have some ideas but probably worse that what i just said
Are you planing to calculate this for thousands of entities? If no then it literally does not matter
This is quite the microoptimization.
no only player
Computers are pretty good at doing math nowadays.
Float operations are very fast. It wouldn't make much difference if you have one or 3 of them.
If it was hundreds/thousands of units per frame, ya I'd be concerned.
okay thanks guys
I am effectively doing this with about 1000+ objects in the scene every update
Entities or with GOs?
Individually or all within 1 monobehaviour?
path finding is somewhat similar but it doesn't need to be strictly each update
billboarding stuff towards the camera and checking orientation
2D characters in 3D world?
ye
Been having trouble with that, mostly with transparency sorting.
I've been using opaque and alpha clipping
transparency can work but when you're working in a 3D world you're better off making your character opaque otherwise alpha blending becomes more limited
That does seem to be the play.
Though for some reason I'm having trouble getting opaque shaders to work with Sorting Groups.
Since my sprites are composed of lots of segments.
What're my options then?
opaque is specifically sorted through depth
rather, they both sort by depth, but transparency is only sorted via pivot while opaque is sorted per pixel
If I try to layer a sprite by just changing the Z then I get the classic issue of the sprites not sorting correctly when multiple "entities" are overlapping.
this issue
Ah, if you're using segments yeah that can be a problem
Cult of the Lamb features a ton of these types of sprites.
And I'm almost 100% sure the characters are segmented.
Due to their animations and because a lot of the NPCs are mixes of different parts.
I would need to play around with it to see the segment problem as I still feel like depth should be respected between different characters, but otherwise I can think of updating a single sprite
ah, yeah I see what you mean
it's more sorted by pivot here then
what the heck?
I dont think i have enough concentrate or focus enough to code or make a game
what do you mean by sorted by pivot?
if you develop a 2D top down game you usually sort by the Y, meaning that you'd render the higher values first
When you say a 2D top down do you mean something like CotL?
no clue what that is but think stardew valley
ya that's more standard 2D
oh yeah I'd consider that topdown
Man transparency is literally the bane of rendering.
If it's by pivot then it's probably using transparency, but I'm not sure how segmented sprites are sorted even in 2D so probably research more on that and perhaps the idea is similar here.
I think I'll post in #archived-shaders and see if someone has a better idea.
So basically my firerate is not working in my weaponsystem and I have no idea why. https://pastebin.com/5TEjcYGg
just a quick question regarding Awake, Awake will be called when a script is loaded, so even if the script is disabled, Awake will be called ?
so even if i have my firerate to 0 it still shoots
you dont even use firerate in your code beyond declaring it
ig its nextfire then?
You tell me lol
Anyway, I'd start by using debug.log in your method and check values
compare your values and figure out what values they should be at that time
Awake is called when a GO is loaded, so even if you disable the script, it will still be called
"Awake is called even if the script is a disabled component of an active GameObject."
anyone know why I see more of the scene when I don't maximise on play?
I see this without maximising on play
and i see this when maximising
why does maximising on play cut off the horizontal edges?
need to adjust your camera view
in the scene when I press on the camera it shows this window:
how should I adjust the camera
why would it be different when maximising on play? i'm just making the game full screen
what is your ratio set to?
how do I check?
says "free aspect"
change it to match your actual game aspect
😅 how do I know what my actual game aspect is?
prolly 1920x1080 default
full hd (1920x1080)
I change it to that?
oh now I gotta change the sizes of all my gameobjects
you shouldn't
well it kinda zoomed in, cuttin off my portals a bit, and cutting off completely the player
maybe just changing the positions is good enough
try different aspects for mine it changes according to aspect thats set
is your scale slider all the way to the left?
yep
on 1
the sizes of my gameobejct stay the same
it's just the camera which gets smaller
meaning I have a smaller space to work with 🫤
show me your camera in the scene
In unity I know how to code most of the things that I want to actually make, but I do not think I am crystal clear on the actual good practices with C# and unity, especially within inheritence, interfaces and just general architecture on a broader scale. Since I have been learning by doing, I doubt myself which cripples my capability to code efficiently. I know how to code Java for example because i have actually studied it and learnt what's proper practice, in c# I have just put scraps and pieces from many different resources together in my head. Does anyone recommend any resource for learning the actual good practices? Maybe not beginner level, paid is fine
can you still see the sliders or no?
you mean the scale thing?
yea
when I don't maximise on play I can see them yeah
oh wait
I can see them when I maximise as well
take a full screen shot so i can see it
https://gdl.space/necajupeni.cs why are lines being deleted properly upon mouse click release but the dots are being removed in real time?
Good practices and good patterns are language agnostic. If we are talking Unity specifics here learn more about the Composition pattern and if you want to future proof yourself get into Data Oriented design rather than OOP, DOD suits what games do as a software much better than OOP
i am adapting my enemy script
to be on an EnemyManager object
rather than the enemy itself
i tried creating a camera in code, i set the stereotargeteye to none but it still shows on my vr? what am i missing?
and im not sure how to reference the enemy for some of the things
such as bullets colliding with the enemy
yea your aspect ratio of your camera isn't set to a specific aspect. so you can just adjust it to the size that works for you or do some complicated stuff to figure out your cameras aspect and set it to match. thats just from my few mins of research but someone might have a more clear answer that understands the camera setting better than i do :/.
But it's not? Start is not an abstract or virtual member of MonoBehaviour. It's called by reflection
oh alright thanks, i'll try and find a matching aspect
Look up OnCollisionEnter / Exit, and TryGetComponent
They crossposted from #💻┃unity-talk
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("InstantiatedProjectile"))
thats what i had before but now that its not on the enemy it wont work
since it detects what collides with the attatched object
is this something that isnt beginner im not sure
can you show the code !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.
which of these links is most convenient for you
also by enemy manager do you just mean an empty gameobject that has the enemy as a child?
the first one
if your calling something to collide with something else the script has to be attached to the object with the collider but let me see what you got
i comment stuff to try and make sure i know what im doing
that is good 2 know
honestly im still learning a bunch so i with you
in the curly brackets of else if (health <= 0 )
i have accidentally commented out the instantiates
they get instantiated because im doing a funny troll
where enemies double when u kill them and you can see how many you get before you die
So that you don't have to do GetComponent these fields should be declared for the type you actually want
public EnemyController NewEnemy1;
public EnemyController NewEnemy2;
public GunPickup PlayersGun;
what does that mean i should do
it will show up in the inspector and you can drag your enmies into it
its already like that
No it's not
oh lolololol
You declared those fields as GameObject and then you do GetComponent<EnemyController>() to get the actual component/class you want
if you declare how I've shown above, you still drag the same GameObject into the field, but it will get the correct component then, and you won't need the GetComponent
And you'll do just: NewEnemy1.health = 3;
Was being new
Which is why I pointed it out, I vaguely remember not knowing/ understanding this when I first started
fixed that up now
so ye erm bashically this script was on my enemy and now its on a separate thing to avoid all these bugs
but i dont know how to adapt it to change the enemy when its not attatched to it
so rn the box i put the script on is doing all the enemy things
anyone know how to fix this weird collision bug im having with navmesh AI? Im walking into the ai and i just teleport on top of them. Im using a character controller if that helps
what would help is if you posted some !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.
https://hatebin.com/hbpgpulemd
thats my enemy handler code
https://hatebin.com/ddggddlqyo
and this is my character code
i really dont know whats goingg on with it
is there a way to gradually make a wall go down?
in 2d?
so when I touch a key then the wall on the edges will lower itself
if u change the pivot to the top of the wall and scale it down it should work i imagine
Alright I'll try that thx
I dont see anything in that code which is handling collisions
why is why im thinking its a physics probl;em
im just using built in character controller
do you have colliders on your player and enemies?
im pretty sure there is no barrier on the collider and it makes some wierd stuff happen. i went through this like 3 weeks ago but i haven't messed with the nav mesh ai stuff in a while so its lost on me again. but there is a way to set a small barrier between the colliders so you cant climb up the enemy
A collider IS the "barrier"
@celest holly - Show a video of what's actually happening
sure, give me a minute
yes
can you screenshot the inspectors of both
The character conroller gives you a collider, you don't need (and afaik shouldn't have) another collider, remove the capsule collider
sure, i just added that now to see if it helped
still getting the same problem though
Yes, it wasn't a fix for that
I can't view the vids (cookies I cba to sort).. this sounds like the same issue
https://forum.unity.com/threads/solved-character-controller-is-lifted-up-onto-kinematic-rigidbody.450523/
sounds like the character controller simply doesnt work well with navmesh agents
ill just rework my movement to a rigidbody
remember the * time.delta time
since its ran in update
you could do it in fixed update which would work better since i ts a rigidbody
then you wouldnt need the time.deltatime at al
wdym flies off
m_Rigidbody.AddForce(Vector3.MoveTowards(transform.position, player.position, 2f));```
That doesn't seem like something you'd want to do
also like tim said, you want to be doing rigidbody method calls in fixedupdate and other physic methods
Try just grabbing the direction of the two and plugging that in with the speed
removed the rigidbody from the AI and it works, thanks for those who tried to help
Hi, i have one dropdown with value of (sprite, string) options, i want that dropdown searchable like when i type "a" all country name that has "a" show up on dropdown, any idea how to do that?
that's another method now though
I've not used MovePosition but I suggest looking up the documentations
custom editor scripting #↕️┃editor-extensions
In the example they've got a direction (transform.up) and are multiplying it by a magnitude
also player.position is not a direction
you can get a direction from two points
The direction From A to B is B-A, not +
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
That's a good read, though you can skip the normalization part via vector3 method
I have some buttons in a list
my goal is to naviguate between them using c#
when doing myList[0].Select() the button is selected
but when using myList[0].FindSelectableOnDown().Select(), FindSelectableOnDown() returns the correct button, but the button doesnt seem selected
Is the main purpose of an interface to be able to call methods of a class without knowing the specific class?
Ye
If you know an object implements that interface, then you know you know the methods you can call and their return values
Aight ye makes sense
and however that method is implemented inside of that object's class can differ between other object classes which also implement that interface
it also allows you to pass and contain objects by their interface types
via lists and other data structures
Why are you starting the Coroutine every FixedUpdate
another neat use is passing objects by their interface type which helps conceal some of an objects data. This allows another way to prevent classes from interacting with properties or methods, while allowing other scripts referencing it more access.
What's the intended behavior here?
aye and a class can implement multiple interfaces?
Calling it every FixedUpdate is foolish
Think about it
It will start a whole new sequence 50 times per second
50 new sequences every second!
Yep, so technically you can chop up your properties and methods into multiple interfaces and never send the full reference of a class
welp, time for some refactoring, i had touched on unity events before for a simple canTakeDamage thing, but using interfaces feels cleaner
The only big problem with them is Unity doesn't serialize them because there's some ambiguity when setting them on the editor.
Ah okey
you can still get components by interface via GetComponent though
its just for dragging it in you need a concrete type
You can do it via serialize references and other user created libraries, but like Passerby mentioned doing it via GetComponent when initializing is usually the solution (much like how you initialize dictionaries and other non-serialize types)
i made a tool which adds an attribute to filter stuff you drag in the inspector, you can filter by any type, interfaces included
Or grabbing the interfaces when needed like trigger events too
yeah SerilizedReference too, though find that feature can be rather fragile to refactoring
So on a collision event for example with ICanTakeDamage i have to grab the component?
well for a collision event you need to do so anyways even if not using interfaces
Ye, just making sure
but yeah if the thing collided had a IDamageable on it, you could GetComponent that from the hit collider
Yeah, that's a very standard way you may see people use interfaces as far as unity goes
doesnt serialized reference just shows a serialized struct/class in a dropdown including fields from stuff those inherit/implement?
its usecase is more for working with regular classes as referencess, since if you used serlizefield multiple fields will not point to the same objects after deserilization
can you select a button through script without submiting it ?
UI button?
yes
yes
Anything that as ISelect interface
if nothing is focused .Select() "selects" the button without submit, but if calling it again on any button it will submit :/
do you mean ISelectable ? found nothing with ISelect
There's a Selectable component too, it's Button's parent class
Depending on your use case that might be more suitable than Button
but will Selectable have the same behaviour ?
No
What is the behaviour you want
well adding a EventSystem component fixed the issue, not sure why
nvm, i can now move button-to-button, but calling Select() on a already-selected button wont submit it
replacing Select() by onClick.Invoke() fixed this
EventSystem is how Unity registers and responds to input..
its necessary if your canvas has any sort of interactable UI
thanks
here's the definition of Select:
public virtual void Select()
{
if (!(EventSystem.current == null) && !EventSystem.current.alreadySelecting)
{
EventSystem.current.SetSelectedGameObject(base.gameObject);
}
}
hence why it didn't work without an event system!
i have an issue where i recently added difficulty to my game, i added a diificulty select (using prefabs) at the start and added a if statement for each difficulty in the start of my player control script which makes it so that depending on the difficulty a multiplier is made a different number, then this multiplier is used to change health, however this just makes all my enemies move at a ridiculours speed.
that's good to know about; I didn't realize that method was there
if (TryGetComponent<Selectable>(out var selectable))
selectable.Select();
nice and tidy, vs. using EventSystem.current.SetSelectedGameObject yourself
well, then your code is changing the speed of your enemies
you're going to have to show your code
if (PlayerPrefs.GetString ("Difficulty") == "Easy") {
mult = 1f;
}if (PlayerPrefs.GetString ("Difficulty") == "Medium") {
mult = 1.5f;
}if (PlayerPrefs.GetString ("Difficulty") == "Hard") {
mult = 2f;
;
} else {
mult = 1f;
}```
thats all that the new code i added
Debug.Log or visibly inspect the mult var..
and there is no enemy speed variable in the current code]
see whats happening
one handy trick
private void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.CompareTag ("basicEnemy") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 10 * mult;
StartCoroutine(Red ());
} else if (other.gameObject.CompareTag ("advEnemy") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 20 * mult;
StartCoroutine(Red ());
}else if (other.gameObject.CompareTag ("Spikes") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 30 * mult;
StartCoroutine(Red ());
}
}```
and thats the only mention of enemies in the code
click on mult and hit Shift+F12
This will reveal every single place you use mult
If you find no other references, then this isn't the source of your problem.
also, this logic is wrong
it will set mult to 1 as long as the difficulty isn't on Hard
if (easy)
mult = 1;
if (medium)
mult = 1.5f;
if (hard)
mult = 2;
else
mult = 1;
Your formatting makes it harder to read. You should have your IDE auto-format your code for you
in VSCode, at least, you just do Ctrl+Shift+P and type "Format" in the command palette
shift alt f
mmm weird macos button
yeah, the palette will also display the shortcut, if one exists
very very useful
wait whatt how does it set it to 1 as long as it isnt on hard
wouldnt i need to do else if?
Read your four statements from top to bottom.
Because if it's hard you set it to 2. Otherwise, you set it to 1
- If the difficulty is set to "easy", set mult to 1
- If the difficulty is set to "medium", set mult to 1.5
- If the difficulty is set to "hard", set mult to 2
- If the previous condition wans't met, set mult to 1
You want to use else if here.
- If the difficulty is set to "easy", set mult to 1
- Otherwise, if the difficulty is set to "medium", set mult to 1.5
- Otherwise, if the difficulty is set to "hard", set mult to 2
- Otherwise, set mult to 1
thanks
Ey, do you guys know how to make a proyectile pierce X amount of times?
Like, I can make the object count how many times it goes though X stuff, but how do I avoid stuff like two "pierceable objects" being so near that are only counted as one collision?
If you decrement the counter in OnTriggerEnter or OnCollisionEnter, then that won't be an issue.
Each collider overlap will produce a separate message
You just need to make sure that the pierce counter isn't 0 before applying damage
imagine if a 1-pierce projectile overlaps three enemies at once
you probably didn't want it to damage all of them
hey guys, does this if statement wait for an animation to finish playing?
if (this.playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("TurnAround")){
playerAnimator.SetBool("hasTurnedAround", false);
}
}```
it checks if the current state on layer 0 has a certain name
if the state does, it sets a bool
then it terminates
i would not say it "waits" for anything
If you ran this every frame, it would set a bool once a condition was met
what layer 0?
what is that?
Have you implemented a way to prevent a ability from hitting more than one instance
The base layer.
By default, the animator controller only has one layer
any additional layers you add would be at indices 1, 2, 3, etc.
ah I see, thanks!
I mean, it should work just fine if the thing that the proyectile needs to hit has just OnTriggerEnter, which is just called once. But I think I would have to implement a raycast feature to detect collision for the fastest proyectiles
oh I mean, preventing the projectile from hitting someone multiple times
Ah, yeah OnTriggerEnter should be fine
in some cases if your projectile is slow enough your enemy could always enter it again
What I mean is like imagine a game like Vampire survivor where there are like a freaking ton lot of colliders clipping with each other, and I want like a proyectile that is meant to just pierce 2 times, how do I do that?
or vice versa
keep the data on the projectile
if it hit someone, decrement the counter
So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but there will be can i add more and less events whenever i want?
if counter is 0, destroy projectile
(better to queue it back to a object pool tho ^^)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed = 5f;
public float jumpForce = 5f;
private Rigidbody rb;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
isGrounded = true;
}
void Update()
{
HandleMovement();
// Jump with space key if grounded
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
Jump();
}
}
void HandleMovement()
{
float horizontalInput = Input.GetAxis("Vertical"); // Switched W and S
float verticalInput = Input.GetAxis("Horizontal"); // Switched A and D
// Calculate movement direction
Vector3 movement = new Vector3(horizontalInput, 0, verticalInput).normalized;
// Apply movement
rb.velocity = new Vector3(movement.x * movementSpeed, rb.velocity.y, movement.z * movementSpeed);
}
void Jump()
{
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
isGrounded = false; // Set to false when jumping
}
void OnCollisionEnter(Collision collision)
{
// Check if the player is touching a surface
float slopeAngle = Vector3.Angle(Vector3.up, collision.contacts[0].normal);
if (slopeAngle <= 45f)
{
isGrounded = true; // Set to true when landing on a surface with a slope angle less than or equal to 45 degrees
}
}
void OnCollisionExit(Collision collision)
{
isGrounded = false; // Set to false when leaving the ground or a surface with a slope angle less than or equal to 45 degrees
}
}
whats wrong with this code. everythings working fine except "a" key makes the object go right and "d" key makes it go left. while it should be the opposite
!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.
was tryna find that
what does Input.GetAxis(Horizontal) return?
Oh, wait, yeah, sure, I was thinking that I have a CollisionEnter on the proyectile, and It would really know when it is leaving one collider and entering another, I should just have the onTriggerEnter on the enemy collider and then call back to the proyectile to keep track of how many times it has pierced something
Yes, thats a step in the right direction.
in unity -1 on the x axis is left and 1 on the x axis is right
It gets the Horizontal Axis (whatever is assingned to it on the Unity editor, usually AD or left and right arrows) and returns a float from -1 to 1; -1 is left, 0 is no input and 1 is right
Am aware i was just helping the guy
I'm usually just casting the stuff myself via overlapsphere, but I may reimplement the triggers eventually if my projectiles continue to have problems at higher speeds. Ideally you want some hashset on the projectile itself so it knows that it has already previously hit an enemy. This way you won't run into issues where an enemy is hit multiple times from a single ability when you don't want it to. And, the projectile itself is what's keeping count of the pierces. The enemies shouldn't need to do any callbacks to the projectile, nor do they need to know about it as any damage applied will be done through a method on the projectile itself.
such that the projectile will be the one accessing the HealthProperty on the enemy, or any method you've got for that on the entities.
Also, you can consider putting a reference of who cast the projectile or any stat related info if there needs to be more calculations done when the projectile collides onto the projectile itself
The enemy would just have something like OnTriggerEnter (collision other) other.numberOfPiercesDone ++;
Cause as I said I think the proyectile would get really confused if the enemies are way to close, considering that it just entered the collider once, since it never left one if two or more colliders are specially close to each other
bro i don't understand at all, simple code not working : i want to play an animation when a trigger is hit , made the animation made the trigger , made the code , why is't it working please help
Perhaps, but it shouldnt be confused if it's actively appending to a hashset since it can always compare references of those hit and not hit, so getting similar colliders shouldnt be a problem.
if for some reason you get 3 colliders in a frame, you still decrement the counter for each enemy hit and destroy it when 0, and you can even compare distances if you want to order by that.
do you know if the collision is working?
I think that stuff that can hit multiple stuff in a single frame consistently should have a different version of the script entirely
I actually keep the hashset for when I want to hit stuff multiple times too
but instead of checking if I hit something previously, I add previous hit time to each enemy entry
It happenned to me that I was detecting for collision with "player", when "player" was just a emptyobject and I should be searching for "player capsule"
so I can add a cooldown of say 0.3 seconds so they can be affected multiple times over the duration without instant exploding
So you have like... a timer for each proyectile for each enemy or...?
Try logging other inside the function, outside the if. See if you collide with anything at all, and if you do, what that object is. See if that object has the tag Player
protected Dictionary<Guid, float> entitiesHit = new();```
Actually I used a dict
lol
in essence, yes
Also we are not seeing what trigger ant animation here, have you tried to make "PlayText" true manually on the inspector to see if it works?
for each thing you can hit, you remember the last time you hit it
I had a hashset, but I think once I needed previous time I needed dict
A dictionary is appropriate when you have a problem shaped like:
"I need to remember an X for each Y"
GUID over reference because sometimes the enemy can dequeue
and still be part of the list
"dequeue"?
from the object pool
that is not relevant right now, I don't think
oh yeah Im just saying why I use GUID over reference
because I ran into that problem
unless daleo happens to also have an object pool system that assigns guids to objects as they're allocated out of the pool
Literally the first time I have heard about a Dictionary here
that is reasonable though
let's not make things more complex than necessary, though :p
No so much a timer needed, just a previous time hit to compare to
I just wanted to do a simple shoothing arcadey game where you kill guys, game some basic powerups (like shoot speed, cadence, damage, number of shoots, bounces...) along the way and more enemies spawn until you eventually lose
animation works so it's not that
private Dictionary<Enemy, float> hitTimes = new();
void OnTriggerEnter(Collider collider) {
if (!collider.TryGetComponent(out Enemy enemy)) // give up if we didn't hit an Enemy
return;
if (hitTimes.TryGet(enemy, out float time)) // if we saw the Enemy before, get the time we hit them
if (time + 0.25f > Time.time) // if we hit them less than 0.25 seconds ago...
return; // give up
hitTimes[enemy] = Time.time; // remember the current time
enemy.Damage();
}
Here is how I might do this.
I am still learning not really sure how hard that can be though
Dictionaries are good to learn
A dictionary stores keys and values.
Each key is associated with a value.
here, the key is Enemy and the value is float
TryGet lets me ask the dictionary if it has a certain key
If it does, I get the value
List and Dictionary are the two big data structures to know about, yeah
use List if you just want to store a bunch of things
use Dictionary if you want to store a bunch of pairs of things
imagine a shopping list vs. ... well, a literal dictionary
the only thing tagged player is the main one nothing else
with a shopping list, I can remember a bunch of things
with a dictionary, I can look up the meaning of a word
Try logging other inside the function, outside the if. See if you collide with anything at all, and if you do, what that object is. See if that object has the tag Player
this is not a server to ask for support with games you're playing
this is for Unity development
But... the Dictionary thingy, is meant to be just like a general script such as a GameManager that just always stays on or it is meant to be on a specific object?
whats the key in unity to bring object to geometry?
It is not a "script". It is also not a Unity component.
Cause I was gonna do that initially, not sure how that effects performance though
It's just a kind of object you can have.
But if you're asking where the dictionary should be, it sounds like it should be on each projectile
i wonder what the use cases of sorted set are (though i still dont know how to code tree rotation, i remember it rotates based depth)
Okay then show your unity project and what is producing the error
since each projectile needs to remember how long it's been since it hit each enemy
pretty sick if he's getting unity errors in an unreal engine game 
This is a game development server. You should probably send your question to the dev rather than this game development server.
Maybe I am wrong, but, wouldn't I be able to do the same without the Dictionary just using the same script but only when proyectile colliders with an enemy? I am not really seeing the use rn
No, show your unity project that you are developing because that's what this server is for
What are you trying to make your game do?
I want to make sure we're on the same page here.
Then why did you come to a server about unity game development
OK
Dunno, just the expected stuff, proyectiles that hit once, that might be able to pierce/bounce, that may be able to hit multiple times (such a some short of laser or AoE). When something hit, keep track of what hit, what did it hit and what should it do
Like... I dunno, the basics on proyectile based game no?
When something hit, keep track of what hit, what did it hit and what should it do
Do you mean that you need each projectile to remember every single thing it has hit?
Wait......wtf just happened? lol.
Or do you just mean you want piercing projectiles to pierce a limited number of enemies?
If you need to be able to remember a value for each enemy you hit, you need a list or dictionary.
<@&502884371011731486> banned from the server any% WR
a list if you don't care which enemy is which; a dictionary if you do
He's already left but yeah
!ban 1081022170920132658 Trash
82hundred was banned.
some examples:
- Remembering how many enemies you've hit: Use an
intvariable - Remembering how much damage you've done: Use a
floatvariable - Tracking which enemies you've hit so you don't hit them twice: Use a
List<Enemy> - Remembering how many times you've hit each enemy: Use a
Dictionary<Enemy, int>
(yes, HashSet is better for point 3; keeping it simple right now)
🤫
Hashset is good if you just want to know what was hit if you dont need a value
but once you add the requirement of time then you need the dict
did that , still doesn't play animation, the trigger works, the animation...
Hashset over list in this case, especially with a lot of enemies
Show the inspector for the object "Collider"
Nah, I think I just need to do "this enemy was already hit for this collision, apply the stuff to it just once"; I don't think I need to remember any specifics for what I want to do
Okay. Sounds like case 3, then.
You want to remember which enemies you've already hit, so that if the trigger goes off again, they aren't hit again.
That's simpler than case 4, where you're trying to remember a value for each enemy
as Mao suggested, the best option here is HashSet<Enemy>. A hash set doesn't care about order and can't have duplicates.
It's also usually faster to check if something is in a hash set than in a list
It's a good conceptual fit.
List<Enemy> is mandatory if you care about the order of the enemies in the list or want to be able to store the same enemy many times
so, when you hit something, you will check if it is in the set. if it is, you return immediately
if not, you add it to the set and do damage
I don't want the enemy to not be able to be hit again, like I mean, if it was hit once, the bullet pashed through and somehow hit them again, I want then to take damage, what I don't want is for them to take damage from it each frame they are colliding; what I am trying to do I think is the simplest case scenario
Okay, I see.
I see two ways to do that.
wait, no, I see just one way to do that. i misread (:
and that way is pretty simple: just only do damage in OnTriggerEnter
That will only fire the first instant the colliders overlap.
Yep, that's what I was thinking of
If you need to know which enemies are being overlapped, you could store a set. Add enemies to it when you enter, remove when you exit.
I was about to suggest that, but it'd be pointless here
you already know when you start overlapping!
If I'm understanding correctly, easiest way I know of to do that is to have a boolean 'flag' like "has been hit", if false do hit stuff, then set to true, if true don't do hit stuff?
On the actual enemy itself.
Yeah, but my argument to that is that there is scenarios where the enemy can move back into the projectile if quick enough, or if the projectile is slow enough
I could do constant fire weapons like a laser of something of the sort to just activate and deactivate their collision on a timer instead of placing a CD on the enemy and that would work?
that's a game design question
Like, there needs to be a little more logic than simply OnTriggerEnter
should there be a cooldown or not
Constant-damage weapons would do damage in OnTriggerStay as well
Show the inspector for the object "Collider"
Another argument about OnTriggerStay is that you can move in and out of the Stay area
;)
Does it apply damage at first tick? Or a duration>?
or do you keep track of the duration ect
am i dumb, isn't that the collider
just a cube, to test this simple code , 2 hours later same problem
Well, your log is saying you've collided with something name "Collider", so show that
Yeah, I mean like it deals damage to the enemy when the enemy OnTriggerEnter detects it is colliding with the laser, then the laser itself has a timer, so it deactivates for X time and then it activates again for brief time, triggering another OnTriggerEnter if I am not mistaken; that should work exactly like an internal timer on the enemy to able to take damage again right?
That would also work, yes, but it feels more awkward than just dealing damage as long as the laser overlaps the enemy.
But it's perfectly valid.
especially if you're modeling the laser as a beam that flickers on and off rapidly
that is just what i named it as in the log , want me to name it cube , same thing , it's a big ass cube
Show the code. I can't guess what you wrote.
It sounds to me like you aren't logging what digi asked you to log.
So you didn't do what I asked and log the object you collided with, you just wrote the word "Collider" like that would help at all
oh, you are, good!
No, nevermind you did do what I asked
Now show the inspector for the object "Collider"
the Box Collider component in the inspector is not a game object
game objects are those things in the Hierarchy panel.
you are hitting a game object named "Collider"
How can I turn a Vector3 into a quaternion?
Yeah seems kinda weird, but I though it might put less procesing stress on the game, since it is counting just one timer isntead of one for every enemy
what does this vector3 represent?
Euler angles? The direction you are looking?
Quaternion Euler
the direction in which an object is meant to move
Know nothing about optimization really, so, I have no fucking idea though XD
Quaternion.LookRotation(Vector3.forward) produces a zero-rotation
Quaternion.LookRotation(Vector3.right) is a 90 degree rotation to the right
hey that reminds me though
LookRotation gives you a rotation that makes your forward vector point a certain way
but what if I want my right/up vectors to point a certain way?
I usually just do transform.right = ... if I need that
(oh yeah, Alfy, you can do transform.forward = lookDirection to rotate it, too)
Then you'd need to do math and figure out which way your forward would be pointing if your right/up were pointing that way
but suppose I need a rotation
fair enough :p
If you need to do this a lot, it's easy enough to come up with an extension method that does that
Maybe a FromToRotation would be appropriate
Usually you use this to rotate a transform so that one of its axes eg. the y-axis - follows a target direction toDirection in world space.
That does some relevant.
might need to correct the roll afterwards
Yeah, I think that'd actually be the mathless way to do it
transform.forward and up setters use FromToRotation.
There's no timer in the dictionary method, it's just values which you previously compare to. It's honestly not that taxing and is very standard because if you dont add any internal cooldown then you're opening up to scenarios where something can be hit as soon as the next frame.
ah, there you go (:
I would be mostly concerned about all the garbage being generated
if every bullet has a dictionary on it, that's gonna take up a little memory for every bullet
and that has to get cleaned up later
Still, I doubt it's going to be what ruins your game's performance.
gc is the problem yeah (this why object pooling and non-alloc containers is ideal)
I would revisit dictionaries if I need to in the future, since you both gave pretty good explanation of it, but I don't think I am really needing them right nos
but you can say that for a lot of other similar methods like getting colliders
Another thing to think about is where you store your data
imagine you want each bullet to die after 5 seconds
you could:
- give each bullet a
floatvariable - store a single
Dictionary<Bullet, float>somewhere
just food for thought 🙂
ok now it's says collided with cube, i put the script on the collider instead of the car, was that what i needed to do or ...
i'm new btw, first project and i already want to quit
object was the car ,
Are you following a tutorial right now?
It can be very overwhelming when you're just starting and have lots of ways to mess something up.
If you are, then you need to pay very close attention to what's being done
Putting components on the wrong object will break your game
if you have a component that makes you take damage when you get hit by a bullet, putting it on the bullet wouldn't work very well..
so, the video is 9 minutes and i have almost 3 hours of this , no progres
Hey ! I would like to know if someone know a good Block/Parry system tutorial for a 2D Metroidvania game somewhere ?
!learn has some good beginner content that doesn't require you to follow a single long video
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I find it kind of exhausting to follow along with long code tutorial videos
I get lost and miss things.
In this Unity Tutorial, I show you how to animate an object, setup the animation controller, write the C# script and be able to play an animation on a trigger event, as well as stopping it when you exit. Suitable for Unity 5 / 2017 / 2018 and above!
➡️Playing Animation on Trigger (With one line of code): https://www.youtube.com/watch?v=kqBGg6R...
just 9 minutes 1 code , and it doesn't work for me
this feels like a weird topic to make a tutorial about
it's two separate ideas that, once you understand both, are very easy to connect
i guess that's how video tutorials go, though...
i mean he made his video, got his views made money,
what I suggest is whenever the player uses a parry, it creates an invisible hitbox in front of it, and anything caught inside that hitbox gets parried
the two topics being:
- Detecting when a trigger event happens
- Making an animator switch states
It sounds like you're having problems with the first part right now.
is there anything i missed to show that could help you, help me
yeah thats what i was thinking about, if there is no tutorial ima create it by myself😼
It sounds like you had the component on the wrong object.
Lemme make a thread.
i did it myself too
I'm also sending this because there's seems to be some weird problem with the green projectiles' movement, but I can't figure out what
like can yall see it?
if (parriable || other.CompareTag("Shield") && !stuck)
{
SetVelocity(moveSpeed, new Vector3(-moveDir.x, moveDir.y, -moveDir.z));
transform.gameObject.layer = 11;
transform.gameObject.tag = "FProjectile";
transform.rotation = Quaternion.LookRotation(new Vector3(-moveDir.x, moveDir.y, -moveDir.z));
}```
This is what I do to reflect the projectiles
"Shield" is the tag of the hitbox of the shield
I have a parriable flag that can be set on projectiles
and I added a stuck flag which gets turned true or false whenever the object collides with something and hence stops
I implemented blocking similarly to hurtboxes
if an attacking hitbox hits a blockbox, the attack ends
It was kind of fiddly, though..mostly because my animations were bad
(this was for a soulslike)
can you check what's happening at 0:14 seconds in the vid?
I didn't do projectile parrying, so that's probably not relevant
it doesn't look normal
gonna need that too lol
(that's just a special attack that does mega-damage if it hits a hurtbox while the enemy is attacking)
thats basically what I thought of
For parrying projectiles, I guess I'd create a large "parrybox" that reflects any projectiles that hit it
it feels like at 0:14 once the projectile gets reflected it starts moving in a very jittery way
yup have that
It seems fine on my end. Maybe turn off camera shake and all the other projectiles
its just a gameobject with a box collider and the Shield tag
that'll make it easier to see what's happening
true
i can just create a pattern
all about these ones
@swift crag
is it just me, or do some of the projectiles just go into the ground when they are meant to get stuck in it?
also they STILL don't rotate where they're meant to rotate once they get hit
looks like your arrows are moved back somewhere once they hit the ground, correct
I literally have transform.rotation = Quaternion.LookRotation(new Vector3(-moveDir.x, moveDir.y, -moveDir.z)); to make sure that the projectiles get rotated whenever they get reflected
what is the origin of your arrows
transform origin
it'll rotate them around the origin
if your origin is far away from the actual arrow model, itll look funky
seems fine to me
but why tf does setting the rotate do nothing
and now they sometimes just go through the hitbox of the enemy. great.
i assume that code line is directly on this spear and not on some parent object, right?
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player") && !isBeam && hitCooldown <= 0f)
{
other.GetComponent<HitScript>().TakeHit();
hitCooldown = 1f;
if (sticks)
{
transform.parent = other.transform;
SetVelocity(0f, moveDir);
stuck = true;
}
}
if ((parriable || other.CompareTag("Shield")) && !stuck)
{
SetVelocity(moveSpeed, new Vector3(-moveDir.x, moveDir.y, -moveDir.z));
transform.gameObject.layer = 11;
transform.gameObject.tag = "FProjectile";
transform.rotation = Quaternion.LookRotation(new Vector3(-moveDir.x, moveDir.y, -moveDir.z));
}
if (other.CompareTag("Enemy") && sticks)
{
stuck = true;
transform.parent = other.transform;
SetVelocity(0f, moveDir);
}
if (other.CompareTag("Ground") && sticks)
SetVelocity(0f, moveDir);
}```
the spear is the parent object
do they have rigidbodies on them?
if so, you need to set the rotation on the rigidbody component
why
thats so weird
same reason you shouldn't mess with transform.position for something with a rigidbody on it
the rigidbody is keeping track of its rotation and angular momenutm
And if you have Interpolate turned on, it's also constantly updating the position and rotation of the Transform every frame
it'll interfere yea
Why is it weird to set the rotation on the component responsible for rotating the object
So it'll clobber the rotation immediately
wh???
notice how the projectiles get sent backwards
but when they collide with the enemy, they get rotated
oh
when they get hit I do parent them
omg
i might be stupid
hold on
I think there's some extra parameters using set parent to update it
but knowing me I'd just calculate for the heck fo it lel
also, if you are using transform methods with rb then the continuous checking probably wont work too well
I fixed it almost
it gets reversed when it hits the enemy
did it!
@timber tide yeah so the problem was
whenever I set the velocity of the projectile to be reversed
I didn't multiply the speed by -1
I multiplied the movement direction by -1
but then when I went to rotate it
I did the exact same thing
and used the new movement direction, which is reversed
and reversed it again
and yknow
x * (-1) * (-1) = x
im stupid
thanks for the help @timber tide and @swift crag :)
I'll figure out how to make it so u can actually control which way the projectile gets reflected later
rn it helped with debugging
I also have a problem with the particle systems suddenly disappearing whenever the projectile disappears, but ill figure that out later
Good morning. Hope everyone's day is going great. Sanity question but I think I know the answer. I have a rule tile which operates so far correctly for dirt but I've added ore into my game and I'm getting this appearance now. Does a rule tile work its logic off of only tiles included in the rule tile or does it perceive any tiles that are placed on the tilemap however they were placed on it?
I'll give a picture to help illustrate
the code that places the dirt or the ores is as follows:
var t = oreTable.GetRandomItem();
if (t.id == 0)
groundTileMap.SetTile(new Vector3Int(x, y, 0), groundTile);
else
groundTileMap.SetTile(new Vector3Int(x, y, 0), t.tile);
groundTile is my ruleTile (aka place a dirt block and make it look correct based on surrounding tiles [if there or not]
my ruleTile seems correct so it kinda leads me to believe that the ruleTile isn't seeing there's a placed tile above
Hello, is there a way to make when my character is on the wall, it would fall down even though I'm holding the direction button? unity2D
I'm using RigidBody to move my character. RigidBody2D.Velocity.
But when I use transform.position, it does fall. But the Animation is kind of stuttery
What's the best way to get something to happen over a period of time? Like in my case I have a float of 1 and I Want that to go to 0 in 5 minutes
Coroutines
Put it in update and move it towards zero scaled by your duration
Would decrementing by a smaller float work best or calculate time like 1*(5/60)...
this may help you too:
https://www.youtube.com/watch?v=NFvmfoRnarY
✅ Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=NFvmfoRnarY
Lets create a Time Tick System.
It is an easy way to run game logic periodically without having timers in every single object.
This is also an excellent way to improve performance by running logic on a Tick Rate rather than on every single Update.
🌍 Get...
But assuming it's more complex than that.. you could opt for a coroutine.
Pffft , I didn't even think about that dang rookie mistake
if I'm reading correctly the situation is that your character is sticking to the side of a wall?
if so, add a material to your Rigidbody [2D possibly] and adjust the material's Friction to zero, call the material Slippy if you want
Yes, If I keep pushing the direction key while in the air, it just sticks.
What's a material?
if you're working in 2D, in your Assets hierarchy right click in a folder and choose Create/2D/Physics Material 2D
Oh okay thanks. I'll try it.
change the Friction to 0 and click drag on your character, it will apply it to the Rigidbody 2D component
Thanks! It works now. I didn't know about physics material and stuff. Thank you very much. I have been figuring this for the past three hours now.
Chatgpt won't tell me about this stuff. Good thing I asked.
Hey guys, I'm using Navmesh to make npcs wander on a 2d Top Down game I'm making. I made a list of waypoint game objects that an npc could go to but for some reason all the npcs are choosing to walk into the upper top left corner of my map. Changing their waypoint makes them go to the waypoint I picked out so I don't understand why they don't go to the randomly picked one like they should. They aren't even going to a "wrong" waypoint, they're just choosing to walk into the corner.
well, we'll need to see some code
Hello there again, how do I fix this?
I tried changing PixelPerUnit
there is a line on top of my character
(replying to Dayvon here)
i'm guessing the corner is close to [0,0,0]
make sure you're actually picking a waypoint and not just using a default value
no problem, i've been in that same situation plenty 🙂
Quick question
if I wanted to store gameObject.GetComponent<SomeComponent>() in a variable so I could call that path easier would I store that in a Component object?
you should use the specific type of the component
in this case, SomeComponent
you can indeed store it in a Component variable, but I imagine you want to use the features of SomeComponent here
you could also store it in a UnityEngine.Object or even an object field!
but those would be even less specific and less useful
so it is a PlayerMovementScript.
so I would do private PlayerMovementScript player;
easy enough
Just making sure though. If I call methods in that script I would be calling methods from the script location where I get component and not a new right? as long as I don't use the new keyword?
Right.
I wouldn't say you call it from "the script location"
But you're definitely calling the method on the same object as you originally got with GetComponent
Ok yea. that is what i mean sorry lol
if GetComponent returned the player's PlayerMovementScript, then you'll be able to keep that reference
np!
storing these things in fields instead of constantly searching for them is a good idea
yea I am tired of typing getcomponent XD especially because I keep typing getcompoent or compnent XD I can't for the life of me type it right the first time
also, instead of referencing prefabs as a plain GameObject, you can reference them with a specific component type
I have bought a C# microsoft.net book. I am wondering if it's still relevant today, and if learning from it is still useful. It was published around 2002 to 2003.
any component that's on the root of the game object
It won't be irrelevant but it'll almost certainly be incomplete
Basic concepts like loops, referencing, etc. aren't going to change much. But that old and you are probably missing stuff like Linq and other libraries included over the years
Hello, I right now have a problem where I have hurtboxes all set up and they work. But although the triggers are bigger then the colliders on the object it most the time the trigger does not register and the collider eats the projectile. How can I fix this?
Are you using multiple triggers or something? However you are killing the projectiles should be registering how that hit is handled too
I have actual colliders(for objects collision) and triggers(different part, different damage)
Hey, does anyone know why the animation is playing twice when going from any action to crouching and when going from crouching to any action? I have only two instances in the code that allows this animation to be played, when the down key button is being pressed, the peramiter in the animator "holdingTheDownKey" is being pressed, and when it is not being pressed, this peramiter turns false. What is the problem?
So, what's destroying the projectiles
the collision collider
and the triggers dont react event though they are bigger than the colliders
The projectiles have IsTrigger selected, right
is there a method which is activated before the project starts no matter on which gameobject it is on, something like Awake but not for the specific object
You can do either honestly if you're letting projectiles be affected by collision, but they shouldn't be destroyed through your collisional method if you want the trigger methods to handle it
https://docs.unity3d.com/ScriptReference/RuntimeInitializeLoadType.BeforeSplashScreen.html
That too so you can preload before the splash ;p
those attributes are right in the UnityEngine namespace
They're attributes which you can plop onto any method. It's some reflection stuff
what does that mean
there are examples of how to use the attribute on the doc page
so would this work?
Hi, I just started learning how to code (like 1-2 days ago) and I have a major problem with my programming journey. So basically I wanted to implement a script in the update or in a different void (Idk how this works) that when I click the "red" button that will gonna send a broadcast to the another script and enable the void and then cube will turn red. I tried for the couple of hours trying to understand how to make this work but I made no progress at all. So could someone please assist me with that? Thank you!
I honestly dont know how it works so idk if it may be possible
you need to get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Can someone help me here please. #💻┃code-beginner message
what's the underline telling ya
Where are you calling the Red() function
i gotta make my method static but fuck that cuz it dont work no more
https://www.youtube.com/watch?v=gSfdCke3684
you can watch this tutorial, it'll teach you how to use buttons in general so you can adjust it to your needs
How do you create and script a button? Do you want to use the OnClick() Unity event? We'll go through that today, using TextMeshPro and the systems around it.
🎁 Get OVER 200+ Scripts, Projects and premium content on my PATREON HERE:
➡️http://bit.ly/SpeedTutorPatreon
············································································...
oh yeah you need static
im gonna figure out something else
no because instances of this object (as well as your other objects like your AudioManager) will not exist before the splash screen runs.
also the method needs to be static
so basically i gotta make everything in this method load before the splash screen
why do you need this to happen before the splash screen? why can this not be applied in Awake?
If it's changing values of an instance of something, then no you don't. Changing the values of an instance before it exists just doesn't make sense, and before the splash screen, no objects could possibly exist
Yeah, if it's singleton stuff then awake would be the idea here since it'll load up as soon as the scene loads. Actually, you'd want start if you're relying on audio manager singleton, otherwise may need some custom execution ordering or method call after instantiation.
Your speed seems to be dependent on the distance to the player. You should probably normalize that direction vector
I'm using a ruleTile, is there a way to have the ruleTile adjust if it finds any tile is found (aka not one part of the ruleTile rules?
Hey there, I made a state machine for my player and it works well, but it has one weird issue. So in the Awake() I set my currentState to an initialState so it's not null. After doing that, the currentState still returns null for some reason. However, the code for all my states do work. Even I switch between them on runtime, the currentState still returns null while debugging. It doesnt give any compiler errors. Any idea what might cause this? I added the code below.
` private BaseState currentState;
[HideInInspector] public Movement movementState;
[HideInInspector] public Climbing climbingState;
[HideInInspector] public WallSliding wallSlidingState;
private void Awake()
{
movementState = new Movement(this);
climbingState = new Climbing(this);
wallSlidingState = new WallSliding(this);
currentState = GetInitialState();
}
private BaseState GetInitialState()
{
return movementState;
}`
where is it returning null
Whenever I debug.log it, it says it's null
Hey yall where can i install the UnityEvents assets?
you do realize i asked because i would like for you to be specific. you are not showing anything that would cause it to be null
what assets are you referring to? 🤔
you don't...its part of the engine already
well then im confused why my code isnt working, its saying i dont have access to those assets
what is? show
As long as You're using the correct namespace it should work fine
share the code and the error
yup namespace
make sure that your !IDE is configured. then you can use the quick actions to add the correct using directive
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
is your IDE conigured? it should give you suggesttions
configure your ide @broken hill
there is no namespace just called UnityEvents
private void FixedUpdate() { currentState.UpdatePhysics(baseStrategy); print(currentState); }
When I print it, it says the currentState is null even though I assigned it the GetInitialState() method which gives it a value
!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.
and if it is printing null then whatever UpdatePhysics is doing is making it null somehow since it isn't throwing an NRE and preventing the log from printing
whats that and how do i do it?
You were linked to it
so i just click visual studio and it does it for me?
no mate, its very simple instructions to follow
can somebody help me? i have a working jump function but before it actually jump i have to press space lot of times before it actually jumps https://hastebin.com/share/oyuyicaloj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
dont do inputs in FixedUpdate
don't use GetKeyDown inside of FixedUpdate. GetKeyDown only returns true the first frame the key is pressed which is unlikely to be a FixedUpdate frame
ok
Is it a 2D game void?
no
thanks, i put the if statement in update and it worked tysm
okay trying to set up IDE and it only shows microsoft Visual studio 2019 as an option
is that the code editor you are using?
Sorry for repeating
I'm using a ruleTile, is there a way to have the ruleTile adjust if it finds any tile is found (aka not one part of the ruleTile rules? i can share code and picture of what's occurring if needed. Thanks!
yes i think so
then why is it an issue that it is the only one listed? it only shows editors you have installed
Is it best if i just create an enemy AI with FSMs because im having a hard time with enumerators and coroutines. For example I don't know how I can stop a patrolling coroutine for the AI to be able to chase the player and then when the player goes out of sight, the AI goes back to patrolling
because thats not what the tutorial shows nevermind i'll figure it out myself.
is it easier if I just use FSMs?
just stop the coroutine