#💻┃code-beginner

1 messages · Page 136 of 1

muted wadi
#

but how would i change the overlapsphere to be a cone?

wintry quarry
#

Explained already here

muted wadi
#

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?

agile arrow
#

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.");
} 

muted wadi
queen adder
deft venture
#

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);
    }
}
muted wadi
#

that way you should be able to stop the paddles from moving past the borders by simply using a collider

wintry quarry
#

If you want proper physics only move via the Rigidbody

muted wadi
deft venture
fluid remnant
#

How do I assign all children a LayerMask again?

wintry quarry
#

In the editor you can simply select all the objects at once and change the layer in the inspector

fluid remnant
#

Ohh, how would I do it then, I'm trying to do it runtime

fluid remnant
#

LayerMask.NameToLayer takes only string but not very neat

#

I guess LayerMask is only for Raycasts?

wintry quarry
fluid remnant
#

placementLayer is LayerMask

wintry quarry
#

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

gaunt ice
#

Layermask in number between 0 to 0xffffffff, it is bitmask

fluid remnant
#

just seems dirty to use integer

wintry quarry
#

Use NameToLayer if you want to use a string

fluid remnant
#

Oh ok what if my layers change , do I just change inspector value of string?

wintry quarry
#

Sure

#

Why not

fluid remnant
#

Yeah I will do that thanks!

agile arrow
spiral glen
#

how do I see how many lines are in a .txt file?

rich adder
spiral glen
#

swag thanks

#

💋

vocal sail
#

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?

teal viper
#

Might want to use an overlap query on scene load or just avoid that situation entirely(preferable).

vocal sail
#

Is there a way to check whether it is player or the collider that causes the problem in build

wintry quarry
vocal sail
#

can you be more specific? or code is needed?

teal viper
smoky stump
#

Can anyone send me a good beginner c# tutorial

north kiln
#

Please link to large codeblocks !code

eternal falconBOT
north kiln
#

Also, this all could be improved massively by caching variables, using Camera.main, and getting rid of whatever on earth .GameObject() is

vocal sail
rich adder
vocal sail
#

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

teal viper
#

Just call it on scene load or some time after it.

vocal sail
#

I made it a serial prefab that triggers in order and that one is the head

teal viper
#

Also, not sure if it's relevant to your issue(could be), but your EnterGame coroutine doesn't do anything.

teal viper
vocal sail
teal viper
vestal adder
#

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

vocal sail
#

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

teal viper
#

That's sounds like a very bad approach. You might want to look at the timeline package for scripted cinematics /cut scenes.

vocal sail
#

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

teal viper
#

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...

vocal sail
#

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

teal viper
#

Then trigger it via code when the scene is loaded.

vocal sail
teal viper
vocal sail
#

hmm I see, thanks for the support kind person ❤️ truely appreciated

eternal latch
#

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?

charred spoke
#

Depends on what you do with the list and how many items you have in there

wintry quarry
#

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

eternal latch
#

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

wintry quarry
#

Simply defining it has almost no computational cost

wintry quarry
charred spoke
#

Or rather the initial capacity but its good practice to preallocate that with some sane number

wintry quarry
#

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

charred spoke
#

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

eternal latch
wintry quarry
#

It's premature optimization

#

Obviously the data has to go somewhere though

#

Lists don't give you free memory magically

eternal latch
whole sapphire
#

How do u make a 2D object half transparent

timber tide
#

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

whole sapphire
#

my object is currently using the default texture

timber tide
#

UVs -> blender
textures -> any art program

whole sapphire
#

so u cant do it in unity?

timber tide
#

can also do it via shaders but that's a little more harder if you've not used them

whole sapphire
#

im just trying to change the opacity

#

to 0.5 sth

timber tide
#

if you want to do it in unity then probably shaders

north kiln
#

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...

whole sapphire
#

ehhhh i cant do it with code?

#

cuz im trying to make when the player walk behind the object it will go half transparent

north kiln
#

There's a number of ways to go about that. Depends on the render pipeline, the camera perspective with the objects, the whole setup

wintry quarry
timber tide
#

Ya got those if you're dealing with 2D

timber tide
#

oh you just wanted the opacity lowered eh angerjoy (sorry half awake and must have read over your previous reply)

vestal adder
#

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

gaunt ice
#

Every prefab spawns a new prefab

vestal adder
#

ooooohhh

#

so how do i just spawn one in

gaunt ice
#

Dont let the prefab spawns itself

vestal adder
#

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

gaunt ice
#
Unity Learn

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...

vestal adder
#

Ill do that now

vestal adder
#

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

whole sapphire
#

how to detect if an object touch a trigger

#

like whats the function name

vestal adder
#

private void OnTriggerEnter()

whole sapphire
vestal adder
#

erm

#

private void OnTriggerEnter(Collider collider)

whole sapphire
#

yeah

vestal adder
#

perhaps that

whole sapphire
#

i did that

vestal adder
#

did you do these after {}

north kiln
whole sapphire
#
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

frozen stream
#

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

vestal adder
#

the thing entering the trigger also has to be set to a trigger i think

whole sapphire
#

nvm solved

vestal adder
#

winning

whole sapphire
#

i forgot to do trigger2D

visual hedge
#

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?

whole sapphire
#

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
visual hedge
#

My thoughts: something in starter pack: third person controller prevents it.

whole sapphire
#

man thanks alot thie website is cool

teal viper
visual hedge
vestal adder
#

@gaunt ice hey do you get my issue or is it not explained well

visual hedge
teal viper
#

Isn't it moving with rb/CC? You wouldn't need any of these with navmesh agent.

visual hedge
teal viper
#

Well, then you'll need to remove or disable the previous controller. Otherwise they would be fighting for control over the character.

visual hedge
vestal adder
#

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

nimble apex
#

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

teal viper
# vestal adder how would you go about it

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.

vestal adder
#

okay yes

#

thanks ill move the script off of the enemy

shrewd swift
#

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

teal viper
#

Why would that be costly?🤔

#

And what other alternative do you have?

shrewd swift
#

well since im doing only 1 axis yeah
idk if vectors are "more" calculations, because its just doing 3 additions instead of 1

shrewd swift
shrewd swift
charred spoke
#

Are you planing to calculate this for thousands of entities? If no then it literally does not matter

static bay
static bay
#

Computers are pretty good at doing math nowadays.

teal viper
#

Float operations are very fast. It wouldn't make much difference if you have one or 3 of them.

static bay
#

If it was hundreds/thousands of units per frame, ya I'd be concerned.

shrewd swift
#

okay thanks guys

static bay
#

But just 1?

#

You're fine.

timber tide
timber tide
#

GOs

#

camera stuff

static bay
#

Individually or all within 1 monobehaviour?

timber tide
#

path finding is somewhat similar but it doesn't need to be strictly each update

#

billboarding stuff towards the camera and checking orientation

static bay
timber tide
#

ye

static bay
#

Been having trouble with that, mostly with transparency sorting.

timber tide
#

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

static bay
#

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.

timber tide
#

cant use sorting groups with opaque

#

that's specific to transparent queue

static bay
#

What're my options then?

timber tide
#

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

static bay
#

this issue

timber tide
#

Ah, if you're using segments yeah that can be a problem

static bay
#

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.

timber tide
#

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

static bay
#

what the heck?

daring pagoda
#

I dont think i have enough concentrate or focus enough to code or make a game

static bay
timber tide
#

if you develop a 2D top down game you usually sort by the Y, meaning that you'd render the higher values first

static bay
timber tide
#

no clue what that is but think stardew valley

static bay
#

sorry CotL is Cult of the Lamb

#

the game in the screenshot I sent

static bay
timber tide
#

oh yeah I'd consider that topdown

static bay
#

Man transparency is literally the bane of rendering.

timber tide
#

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.

static bay
crude prawn
shrewd swift
#

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 ?

crude prawn
timber tide
#

you dont even use firerate in your code beyond declaring it

crude prawn
timber tide
#

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

nocturne parcel
#

"Awake is called even if the script is a disabled component of an active GameObject."

uncut bay
#

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?

plush cave
uncut bay
#

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

plush cave
#

what is your ratio set to?

uncut bay
#

how do I check?

plush cave
#

its a drop down in the game tab

#

next to display

uncut bay
#

says "free aspect"

plush cave
#

change it to match your actual game aspect

uncut bay
#

😅 how do I know what my actual game aspect is?

plush cave
#

prolly 1920x1080 default

uncut bay
#

full hd (1920x1080)

#

I change it to that?

#

oh now I gotta change the sizes of all my gameobjects

plush cave
#

you shouldn't

uncut bay
#

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

plush cave
#

try different aspects for mine it changes according to aspect thats set

uncut bay
#

ok

#

none of them work :/

plush cave
#

is your scale slider all the way to the left?

uncut bay
#

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 🫤

plush cave
#

show me your camera in the scene

uncut bay
#

this is free aspect

plush cave
#

the main camera is what you should see

#

press play and take a screen shot

royal ledge
#

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

uncut bay
#

this is when I use "maximise on play"

#

this is without

plush cave
#

can you still see the sliders or no?

uncut bay
#

you mean the scale thing?

plush cave
#

yea

uncut bay
#

when I don't maximise on play I can see them yeah

#

oh wait

#

I can see them when I maximise as well

plush cave
#

take a full screen shot so i can see it

uncut bay
#

ok

#

maximise on play:

sullen galleon
uncut bay
charred spoke
uncut bay
#

when I don't maximise on play

#

🫤

vestal adder
#

i am adapting my enemy script

#

to be on an EnemyManager object

#

rather than the enemy itself

wooden minnow
#

i tried creating a camera in code, i set the stereotargeteye to none but it still shows on my vr? what am i missing?

vestal adder
#

such as bullets colliding with the enemy

plush cave
# uncut bay when I don't maximise on play

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 :/.

north kiln
#

But it's not? Start is not an abstract or virtual member of MonoBehaviour. It's called by reflection

uncut bay
#

oh alright thanks, i'll try and find a matching aspect

hexed terrace
vestal adder
#

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

plush cave
eternal falconBOT
vestal adder
#

which of these links is most convenient for you

plush cave
#

the first one

vestal adder
#

i have it on a cube

#

which is not attatched to the enemy

plush cave
#

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

vestal adder
#

i comment stuff to try and make sure i know what im doing

plush cave
vestal adder
#

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

hexed terrace
# vestal adder https://gdl.space/enusasumof.cs

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;
vestal adder
#

what does that mean i should do

plush cave
#

it will show up in the inspector and you can drag your enmies into it

vestal adder
#

its already like that

hexed terrace
#

No it's not

vestal adder
#

oh lolololol

hexed terrace
#

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;

vestal adder
#

okay i see how its different from what ive done now

#

was being a fool

hexed terrace
#

Was being new

#

Which is why I pointed it out, I vaguely remember not knowing/ understanding this when I first started

vestal adder
#

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

celest holly
#

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

languid spire
eternal falconBOT
celest holly
#

i really dont know whats goingg on with it

uncut bay
#

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

celest holly
#

if u change the pivot to the top of the wall and scale it down it should work i imagine

uncut bay
#

Alright I'll try that thx

hexed terrace
#

Don't scale it

#

move it

languid spire
celest holly
#

why is why im thinking its a physics probl;em

#

im just using built in character controller

languid spire
plush cave
# celest holly why is why im thinking its a physics probl;em

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

hexed terrace
#

A collider IS the "barrier"

#

@celest holly - Show a video of what's actually happening

celest holly
languid spire
celest holly
#

Player

hexed terrace
#

The character conroller gives you a collider, you don't need (and afaik shouldn't have) another collider, remove the capsule collider

celest holly
#

sure, i just added that now to see if it helped

#

still getting the same problem though

hexed terrace
#

Yes, it wasn't a fix for that

celest holly
#

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

timber tide
#
 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

celest holly
fickle wagon
#

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?

timber tide
#

that's another method now though

#

I've not used MovePosition but I suggest looking up the documentations

timber tide
#

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

wintry quarry
#

The direction From A to B is B-A, not +

timber tide
#

That's a good read, though you can skip the normalization part via vector3 method

shrewd swift
#

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

royal ledge
#

Is the main purpose of an interface to be able to call methods of a class without knowing the specific class?

timber tide
#

Ye

#

If you know an object implements that interface, then you know you know the methods you can call and their return values

royal ledge
#

Aight ye makes sense

timber tide
#

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

wintry quarry
#

Why are you starting the Coroutine every FixedUpdate

timber tide
wintry quarry
#

What's the intended behavior here?

royal ledge
#

aye and a class can implement multiple interfaces?

wintry quarry
#

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!

timber tide
royal ledge
#

welp, time for some refactoring, i had touched on unity events before for a simple canTakeDamage thing, but using interfaces feels cleaner

timber tide
#

The only big problem with them is Unity doesn't serialize them because there's some ambiguity when setting them on the editor.

royal ledge
#

Ah okey

shell sorrel
#

you can still get components by interface via GetComponent though

#

its just for dragging it in you need a concrete type

timber tide
#

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)

undone rampart
timber tide
#

Or grabbing the interfaces when needed like trigger events too

shell sorrel
#

yeah SerilizedReference too, though find that feature can be rather fragile to refactoring

royal ledge
#

So on a collision event for example with ICanTakeDamage i have to grab the component?

shell sorrel
#

well for a collision event you need to do so anyways even if not using interfaces

royal ledge
#

Ye, just making sure

shell sorrel
#

but yeah if the thing collided had a IDamageable on it, you could GetComponent that from the hit collider

timber tide
#

Yeah, that's a very standard way you may see people use interfaces as far as unity goes

undone rampart
shell sorrel
shrewd swift
#

can you select a button through script without submiting it ?

timber tide
#

UI button?

shrewd swift
#

yes

timber tide
#

Anything that as ISelect interface

shrewd swift
#

if nothing is focused .Select() "selects" the button without submit, but if calling it again on any button it will submit :/

shrewd swift
wintry quarry
#

There's a Selectable component too, it's Button's parent class

#

Depending on your use case that might be more suitable than Button

shrewd swift
wintry quarry
#

No

timber tide
#

What is the behaviour you want

shrewd swift
#

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

shrewd swift
rocky canyon
#

its necessary if your canvas has any sort of interactable UI

shrewd swift
#

thanks

swift crag
#

hence why it didn't work without an event system!

gusty hazel
#

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.

swift crag
#

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

swift crag
#

you're going to have to show your code

gusty hazel
#
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

swift crag
#

okay, that's fine

#

now how do you use mult?

rocky canyon
#

Debug.Log or visibly inspect the mult var..

gusty hazel
#

and there is no enemy speed variable in the current code]

rocky canyon
#

see whats happening

swift crag
#

one handy trick

gusty hazel
#
    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

swift crag
#

This will reveal every single place you use mult

#

If you find no other references, then this isn't the source of your problem.

swift crag
#

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;
gusty hazel
#

ahhh

#

ok

swift crag
#

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

gaunt ice
#

shift alt f

swift crag
#

mmm weird macos button

#

yeah, the palette will also display the shortcut, if one exists

#

very very useful

gusty hazel
#

wait whatt how does it set it to 1 as long as it isnt on hard

#

wouldnt i need to do else if?

swift crag
polar acorn
swift crag
#
  • 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
swift crag
#
  • 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
gusty hazel
#

thanks

frigid sequoia
#

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?

swift crag
#

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

warm condor
#

hey guys, does this if statement wait for an animation to finish playing?

        if (this.playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("TurnAround")){
            playerAnimator.SetBool("hasTurnedAround", false);
        }
    }```
swift crag
#

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

warm condor
#

what is that?

timber tide
swift crag
#

By default, the animator controller only has one layer

#

any additional layers you add would be at indices 1, 2, 3, etc.

warm condor
#

ah I see, thanks!

frigid sequoia
timber tide
#

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

frigid sequoia
timber tide
#

or vice versa

#

keep the data on the projectile

#

if it hit someone, decrement the counter

lavish gate
#

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?

timber tide
#

if counter is 0, destroy projectile

#

(better to queue it back to a object pool tho ^^)

timid saffron
#

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

timber tide
#

!code

eternal falconBOT
lavish gate
lavish gate
frigid sequoia
# timber tide if counter is 0, destroy projectile

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

timid saffron
#

-1 and 1

lavish gate
#

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

timid saffron
#

oh okay then

#

i just started unity

#

thanks

lavish gate
#

Thats okay

#

So if you flip the -1 and 1, you go in different directions

frigid sequoia
lavish gate
#

Am aware i was just helping the guy

timber tide
# frigid sequoia Oh, wait, yeah, sure, I was thinking that I have a CollisionEnter on the proyect...

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

frigid sequoia
deep grove
#

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

timber tide
#

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.

lavish gate
frigid sequoia
timber tide
#

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

frigid sequoia
timber tide
#

so I can add a cooldown of say 0.3 seconds so they can be affected multiple times over the duration without instant exploding

frigid sequoia
polar acorn
timber tide
#

Actually I used a dict

#

lol

frigid sequoia
swift crag
#

for each thing you can hit, you remember the last time you hit it

timber tide
#

I had a hashset, but I think once I needed previous time I needed dict

swift crag
#

A dictionary is appropriate when you have a problem shaped like:

"I need to remember an X for each Y"

timber tide
#

GUID over reference because sometimes the enemy can dequeue

#

and still be part of the list

swift crag
#

"dequeue"?

timber tide
#

from the object pool

swift crag
#

that is not relevant right now, I don't think

timber tide
#

oh yeah Im just saying why I use GUID over reference

#

because I ran into that problem

swift crag
#

unless daleo happens to also have an object pool system that assigns guids to objects as they're allocated out of the pool

frigid sequoia
#

Literally the first time I have heard about a Dictionary here

swift crag
#

that is reasonable though

#

let's not make things more complex than necessary, though :p

timber tide
#

No so much a timer needed, just a previous time hit to compare to

frigid sequoia
swift crag
# frigid sequoia Literally the first time I have heard about a Dictionary here
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.

frigid sequoia
timber tide
#

Dictionaries are good to learn

swift crag
#

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

swift crag
#

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

deep grove
swift crag
#

with a shopping list, I can remember a bunch of things

#

with a dictionary, I can look up the meaning of a word

polar acorn
swift crag
#

this is not a server to ask for support with games you're playing

#

this is for Unity development

frigid sequoia
#

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?

timid saffron
#

whats the key in unity to bring object to geometry?

swift crag
frigid sequoia
swift crag
#

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

gaunt ice
#

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)

polar acorn
#

Okay then show your unity project and what is producing the error

swift crag
#

since each projectile needs to remember how long it's been since it hit each enemy

upbeat stream
ivory bobcat
#

This is a game development server. You should probably send your question to the dev rather than this game development server.

swift crag
#

that's an unreal engine game

#

so, wrong server, wrong engine

frigid sequoia
polar acorn
#

No, show your unity project that you are developing because that's what this server is for

swift crag
#

I want to make sure we're on the same page here.

polar acorn
#

Then why did you come to a server about unity game development

swift crag
#

OK

frigid sequoia
# swift crag What are you trying to make your game do?

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?

swift crag
#

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?

ruby python
#

Wait......wtf just happened? lol.

swift crag
#

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.

polar acorn
#

<@&502884371011731486> banned from the server any% WR

swift crag
#

a list if you don't care which enemy is which; a dictionary if you do

ivory bobcat
#

He's already left but yeah

frosty hound
#

!ban 1081022170920132658 Trash

eternal falconBOT
#

dynoSuccess 82hundred was banned.

swift crag
#

some examples:

  • Remembering how many enemies you've hit: Use an int variable
  • Remembering how much damage you've done: Use a float variable
  • 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)

#

🤫

timber tide
#

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

deep grove
timber tide
#

Hashset over list in this case, especially with a lot of enemies

polar acorn
frigid sequoia
swift crag
#

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

swift crag
#

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

frigid sequoia
swift crag
#

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.

frigid sequoia
swift crag
#

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!

ruby python
#

On the actual enemy itself.

timber tide
#

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

frigid sequoia
#

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?

timber tide
#

Like, there needs to be a little more logic than simply OnTriggerEnter

swift crag
#

should there be a cooldown or not

swift crag
polar acorn
timber tide
#

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

deep grove
swift crag
#

what are you logging, exactly?

#

show us the line of code.

deep grove
#

just a cube, to test this simple code , 2 hours later same problem

polar acorn
frigid sequoia
# swift crag Constant-damage weapons would do damage in OnTriggerStay as well

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?

swift crag
#

But it's perfectly valid.

#

especially if you're modeling the laser as a beam that flickers on and off rapidly

deep grove
swift crag
#

It sounds to me like you aren't logging what digi asked you to log.

polar acorn
deep grove
swift crag
#

oh, you are, good!

polar acorn
#

Now show the inspector for the object "Collider"

swift crag
#

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"

quick pollen
#

How can I turn a Vector3 into a quaternion?

frigid sequoia
swift crag
#

Euler angles? The direction you are looking?

ivory bobcat
quick pollen
swift crag
#

Okay, you want a look rotation

#

Quaternion.LookRotation()

frigid sequoia
swift crag
#

Quaternion.LookRotation(Vector3.forward) produces a zero-rotation

#

Quaternion.LookRotation(Vector3.right) is a 90 degree rotation to the right

quick pollen
#

oh yeah, forgot

#

thanks!

swift crag
#

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)

polar acorn
swift crag
polar acorn
#

If you need to do this a lot, it's easy enough to come up with an extension method that does that

swift crag
#

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

polar acorn
#

Yeah, I think that'd actually be the mathless way to do it

brave compass
#

transform.forward and up setters use FromToRotation.

quick pollen
#

whoops

#

probably shouldnt set the dir to 0

timber tide
swift crag
swift crag
#

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.

timber tide
#

gc is the problem yeah (this why object pooling and non-alloc containers is ideal)

frigid sequoia
timber tide
#

but you can say that for a lot of other similar methods like getting colliders

swift crag
#

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 float variable
  • store a single Dictionary<Bullet, float> somewhere
#

just food for thought 🙂

deep grove
#

object was the car ,

swift crag
#

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.

deep grove
#

yhea , simple plain tutorial , even i can understand

#

want me to send?

swift crag
#

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..

deep grove
#

so, the video is 9 minutes and i have almost 3 hours of this , no progres

hybrid plover
#

Hey ! I would like to know if someone know a good Block/Parry system tutorial for a 2D Metroidvania game somewhere ?

swift crag
#

!learn has some good beginner content that doesn't require you to follow a single long video

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

swift crag
#

I find it kind of exhausting to follow along with long code tutorial videos

#

I get lost and miss things.

deep grove
#

just 9 minutes 1 code , and it doesn't work for me

swift crag
#

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...

deep grove
#

i mean he made his video, got his views made money,

quick pollen
swift crag
#

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.

deep grove
#

is there anything i missed to show that could help you, help me

hybrid plover
swift crag
#

Lemme make a thread.

quick pollen
#

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

swift crag
#

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)

quick pollen
#

can you check what's happening at 0:14 seconds in the vid?

swift crag
#

I didn't do projectile parrying, so that's probably not relevant

quick pollen
#

it doesn't look normal

quick pollen
swift crag
#

(that's just a special attack that does mega-damage if it hits a hurtbox while the enemy is attacking)

quick pollen
#

thats basically what I thought of

swift crag
#

For parrying projectiles, I guess I'd create a large "parrybox" that reflects any projectiles that hit it

quick pollen
#

it feels like at 0:14 once the projectile gets reflected it starts moving in a very jittery way

swift crag
#

It seems fine on my end. Maybe turn off camera shake and all the other projectiles

quick pollen
#

its just a gameobject with a box collider and the Shield tag

swift crag
#

that'll make it easier to see what's happening

quick pollen
#

true

#

i can just create a pattern

#

all about these ones

#

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

slate gale
#

looks like your arrows are moved back somewhere once they hit the ground, correct

quick pollen
#

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

slate gale
#

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

quick pollen
#

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.

slate gale
#

i assume that code line is directly on this spear and not on some parent object, right?

quick pollen
#
    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);
    }```
quick pollen
swift crag
#

do they have rigidbodies on them?

#

if so, you need to set the rotation on the rigidbody component

quick pollen
#

they dont have rigidbodies

#

wait no

#

they do

quick pollen
#

thats so weird

swift crag
#

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

slate gale
#

it'll interfere yea

polar acorn
swift crag
quick pollen
#

also how is this not a hit

timber tide
#

continous collision checking

#

click it

quick pollen
#

it already is

#

I had to do it because it couldn't detect hitting the player

timber tide
#

next -> increase radius

#

otherwise may need to implement some custom checking logic

quick pollen
#

notice how the projectiles get sent backwards

#

but when they collide with the enemy, they get rotated

timber tide
#

are they being child to the enemy

#

because then they get the local rotation applied

quick pollen
#

when they get hit I do parent them

#

omg

#

i might be stupid

#

hold on

timber tide
#

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

quick pollen
#

it gets reversed when it hits the enemy

#

@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

warm anvil
#

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

devout swift
#

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

warm anvil
frail star
#

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

ivory bobcat
#

Put it in update and move it towards zero scaled by your duration

frail star
#

Would decrementing by a smaller float work best or calculate time like 1*(5/60)...

warm anvil
# frail star What's the best way to get something to happen over a period of time? Like in my...

✅ 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...

▶ Play video
ivory bobcat
#

But assuming it's more complex than that.. you could opt for a coroutine.

frail star
warm anvil
#

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

devout swift
warm anvil
#

if you're working in 2D, in your Assets hierarchy right click in a folder and choose Create/2D/Physics Material 2D

devout swift
#

Oh okay thanks. I'll try it.

warm anvil
#

change the Friction to 0 and click drag on your character, it will apply it to the Rigidbody 2D component

devout swift
#

Chatgpt won't tell me about this stuff. Good thing I asked.

queen adder
#

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.

swift crag
#

well, we'll need to see some code

devout swift
#

Hello there again, how do I fix this?
I tried changing PixelPerUnit

there is a line on top of my character

swift crag
#

(replying to Dayvon here)

swift crag
#

make sure you're actually picking a waypoint and not just using a default value

warm anvil
rich ember
#

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?

swift crag
#

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

rich ember
#

OHHH

#

ok

swift crag
#

you could also store it in a UnityEngine.Object or even an object field!

#

but those would be even less specific and less useful

rich ember
#

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?

swift crag
#

But you're definitely calling the method on the same object as you originally got with GetComponent

rich ember
#

Ok yea. that is what i mean sorry lol

swift crag
#

if GetComponent returned the player's PlayerMovementScript, then you'll be able to keep that reference

rich ember
#

Ok sweet.

#

Thanks bro 🙂

swift crag
#

np!

#

storing these things in fields instead of constantly searching for them is a good idea

rich ember
swift crag
#

also, instead of referencing prefabs as a plain GameObject, you can reference them with a specific component type

small mantle
#

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.

swift crag
#

any component that's on the root of the game object

polar acorn
#

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

amber nimbus
#

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?

timber tide
#

Are you using multiple triggers or something? However you are killing the projectiles should be registering how that hit is handled too

amber nimbus
#

I have actual colliders(for objects collision) and triggers(different part, different damage)

warm condor
#

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?

timber tide
amber nimbus
#

the collision collider

#

and the triggers dont react event though they are bigger than the colliders

timber tide
#

The projectiles have IsTrigger selected, right

pallid verge
#

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

timber tide
#

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

pallid verge
#

do i need to type using ... to use the methods?

#

cuz i cant seem to find them ;p

slender nymph
#

those attributes are right in the UnityEngine namespace

timber tide
#

They're attributes which you can plop onto any method. It's some reflection stuff

pallid verge
#

what does that mean

slender nymph
#

there are examples of how to use the attribute on the doc page

pallid verge
#

so would this work?

limpid shoal
#

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

slender nymph
#

you need to get your !IDE configured

eternal falconBOT
warm condor
timber tide
polar acorn
pallid verge
ancient island
# limpid shoal Hi, I just started learning how to code (like 1-2 days ago) and I have a major p...

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

············································································...

▶ Play video
timber tide
#

oh yeah you need static

pallid verge
#

im gonna figure out something else

slender nymph
# pallid verge so would this work?

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

pallid verge
slender nymph
#

why do you need this to happen before the splash screen? why can this not be applied in Awake?

polar acorn
timber tide
#

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.

polar acorn
#

Your speed seems to be dependent on the distance to the player. You should probably normalize that direction vector

warm anvil
#

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?

smoky niche
#

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;
}`

slender nymph
#

where is it returning null

smoky niche
#

Whenever I debug.log it, it says it's null

broken hill
#

Hey yall where can i install the UnityEvents assets?

slender nymph
slender nymph
rich adder
broken hill
rich adder
#

As long as You're using the correct namespace it should work fine

broken hill
rich adder
#

yup namespace

slender nymph
# broken hill

make sure that your !IDE is configured. then you can use the quick actions to add the correct using directive

eternal falconBOT
rich adder
#

is your IDE conigured? it should give you suggesttions

broken hill
rich adder
#

configure your ide @broken hill

slender nymph
#

there is no namespace just called UnityEvents

smoky niche
slender nymph
#

!code

eternal falconBOT
slender nymph
#

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

broken hill
rich adder
broken hill
#

so i just click visual studio and it does it for me?

rich adder
vocal fable
#

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

slender nymph
#

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

vocal fable
#

ok

queen adder
#

Is it a 2D game void?

vocal fable
#

no

vocal fable
broken hill
#

okay trying to set up IDE and it only shows microsoft Visual studio 2019 as an option

slender nymph
#

is that the code editor you are using?

warm anvil
#

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!

broken hill
slender nymph
#

then why is it an issue that it is the only one listed? it only shows editors you have installed

weary summit
#

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

broken hill
#

because thats not what the tutorial shows nevermind i'll figure it out myself.

weary summit
#

is it easier if I just use FSMs?