#💻┃code-beginner

1 messages · Page 671 of 1

summer forum
#

it was for a gamemanager script that restarted the game

#

so he didnt refrence it normally

#

with the refrence object

grand snow
#

i dont need a new description im good

summer forum
#

well you said its hard to understand

#

so i had to explain

grand snow
#

it was 😆
Anyway you seem to know that using a serialized field ref is better

#

If you load an additive scene and need to find one or a few objects from there its an acceptable solution to Find()
Else we usually avoid it.

slender nymph
# summer forum it was for a gamemanager script that restarted the game

if this "gamemanager script that restarted the game" is a persistent object (like being a DontDestroyOnLoad object) then it would need to find the player object each time it restarted the scene because the old player object would have been destroyed so it makes sense to use one of the Find methods there (though there are still better ways to handle it)

summer forum
slender nymph
#

the new player object would have the new references. of course you haven't shared the tutorial or actual code, so this information could be entirely irrelevant

summer forum
#

What happens when we lose?

● Download the Project Files: http://devassets.com/assets/how-to-make-a-video-game/

❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU

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

▶ Play video
grand snow
#

my guy didnt use .CompareTag() CANCELLED

summer forum
#

just did it with refrence object and it worked just fine

grand snow
#

Hmm i wouldnt do what he did but it makes it easier for a beginner tutorial

#

no one past the beginner stage really does this so I think its all on purpose

grand snow
#

tbh I dont really know his skill but he does godot now

polar acorn
#

He's decent at the engine but he's not a programmer

#

he's a visual artist which is why the videos usually have good production values. Programming has never really been his strong suit

grand snow
#

Shame visual scripting was not around 8y ago as it is now.

sweet iris
#
{
    Vector2 moveValue = value.Get<Vector2>();
    Vector3 newPosition = new Vector3(transform.position.x + moveValue.x, 0, transform.position.y + moveValue.y);
    rb.Move(newPosition, transform.rotation);    
}```
Hello I'm learning the Player Input component, I tried this code to make my player move, but it always goes back to its initial position, is Move the wrong method, or am I doing vector manipulation wrong ? thank you 🙏
shut swallow
sweet iris
#

I don't know 😦

shut swallow
#

“When Rigidbody interpolation is enabled, Rigidbody.MovePosition creates a smooth transition between frames. Unity moves a Rigidbody in each FixedUpdate call” - scripting API

#

I mean if you have a velocity (your move vector) you’ll still need time for distance

eternal needle
sweet iris
#

I was thinking of adding a speed variable so that it moves more smoothly but what I don't understand is why it goes back to its position before it moved

sweet iris
shut swallow
#

Debugging will help you out

sweet iris
#

I still don't get it

eternal needle
#

part of your issue might also be that you're trying to move a rb outside of fixedupdate

#

input is handled every frame and not tied to the physics loop

sweet iris
shut swallow
eternal needle
sweet iris
#

thank you

eternal needle
#

unless there is something else wrong in the setup that i'm not seeing, I don't think much else could be going wrong here

sweet iris
#

I made the change but I get the same behavior, also since my moveVector is initialized a 0, 0, 0, the player is teleported at those coordinates, maybe Move is the wrong method ?

eternal needle
supple flume
#

yall i need help with this

using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

public class Systematic : MonoBehaviour
{
    public GameObject[] mauz;
    public int indicator=0;
    public ag agagag;
    public PetMover pet;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        agagag = mauz[indicator].GetComponent<ag>();
        if (Input.GetKeyDown("space"))
        {
            pet.movepoint = agagag.LocalMove;
        }
        
        if (Input.GetKeyDown("right"))
        {

            if (indicator < 3)
            {
                indicator += 1;
            }
        }
        else if (Input.GetKeyDown("left"))
        {
            if (indicator > 0)
            {
                indicator -= 1;
            }

        }
        if (indicator == agagag.tilevalue)
            {
                agagag.hoverindicator = 1;
            }
            else
            {
                agagag.hoverindicator = 0;
            }
        
        
    }
}

so at first i tested this in a linear way, but now that i want it to read two ints as in indicatorx and indicatory, how can i register the same object with tiles while not being able to access the list

ivory bobcat
supple flume
#

as you can see in the script, the object selected is determined by the array's value, which is a linear number from left to right, but now i want to determine it by the selective location via an X and Y value, ill provide a vid

ivory bobcat
#

Use a 2d array? (or jagged array etc)

supple flume
#

dont mind the jump, its just a wrong assigned order

#

but i want it to do this with Y access too

supple flume
#

it only shows numbers when i do it

#

wait i am mistaken, it just disappears

rich adder
supple flume
#

i tried even serializing them

supple flume
rich adder
#

you can't you'd need struct

supple flume
ivory bobcat
#

I'm not entirely sure what you're trying to do but if you've got a 2d grid of objects and are wanting to map it, a 2d array should suffice. Where you'd access elements using two values (x, y etc).

rich adder
supple flume
rich adder
supple flume
#

the 2d array values

rich adder
#

Like any other value =

supple flume
#

I want them to be given in order, that seems tff

#

Ooo i figured it out

#

erm help with this

rich adder
supple flume
#

but i assigned them as 0,0

#

oh

rich adder
#

Did you not initialize it

#

Create the object mauz

supple flume
rich adder
#

That doesn't answer the question lol

supple flume
rich adder
supple flume
#

oh

rich adder
#

assigning values to an array not created will def give you null ref

supple flume
#

i never knew i had to do that

eternal needle
supple flume
#

i used them and didnt create it

rich adder
supple flume
#

oh

rich adder
#

Exception unity Objects but those are special

#

also normally unity creates object for you if you serialize it in the inspector like a regular poco/object (arrays is a good example)

eternal needle
# supple flume for normal arrays

🤷‍♂️ up to you, but you also seemingly have never seen a null error before. you can struggle through the c# part all you want while trying to learn unity too. it wont be fun

rich adder
#

You can't travel the road if you don't know how to walk

eternal needle
# supple flume all roads lead to rome

or as we've seen lots of times, beginners who give up because their code "stops working" and isn't possible to fix without rewriting everything. 6 months of duct taping and awful coding habits isnt sustainable. willpower wont create your game

supple flume
rich adder
#

computer science isn't always synonymous with specific language coding

#

Plenty of compsci graduates who never coded a thing to save their life lol

ivory bobcat
# supple flume but i assigned them as 0,0

For clarity, a null reference exception error occurs when you attempt to access a member (get component function in your case) from something that is null and not the thing we're trying to actually get (what we're trying to get can be null and it would be fine). So if a had a field named b and b had a field named c and c had a function named D..
If an nre had occurred when trying to:
access b, we can assume that a was nullcs var t = a.b;//nre if a was nullsame applies for the remainder:cs t = a.b.c;//nre if a or b were null t = a.b.c.D();//nre if a, b or c were nullIf we were to only access a, it would not throw an error during assignment as a being null is valid (you just might get errors later if you ever attempt to access a member of t):cs t = a;//no error even if a is null t.b = z;//nre: t was null but we're attempting to access the member b

supple flume
#

ik what null is, i just didnt read the error 🔥

sour fulcrum
#

My brain is being dumb this morning. I've got a list of world positions that i want to make a bounds out of. I know i can get the average position for the center but how do i calculate size?

#

oh can i just make a empty bounds and encapsulate them all?

nocturne parcel
#

Bounds out of?

charred spoke
charred spoke
#

Depending on the size of his point cloud that could get expensive

sour fulcrum
#

heard ty both

odd swift
gloomy hamlet
#

hello @everyone, i am creating a 3d chess game, and rn i am only at the beginning, and i am trying to, when i hover my cursor on a tile (that i created via script) it changes layer, like from( tile ) to (hover) and then comes back to (tile) when i remove my cursor from that tile. My problem now is that it isnt working even tho i got no console error and i think that my script is good. Maybe i need to add something to it idk: here is the part of my script:
private void Update()
{
if (!currentCamera || !boardActive //IS A BOOLIAN)
{
currentCamera = Camera.main;
return;
}

    RaycastHit info;
    Ray ray = currentCamera.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out info, 100,  LayerMask.GetMask("Tile", "Hover")))
    {
        //GET THE INDEXESOF THE TILE I'VE HIT
        Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);

        //IF WE'RE HOVERING A TILE AFTER NOT HOVERING ANY TILE
        if (currentHover == -Vector2Int.one)
        {
            currentHover = hitPosition;
            tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
        }

        //IF WE WERE ALREADY HOVERING A TILE, CHANGE THE PREVIOUS ONE
        if (currentHover != hitPosition)
        {
            tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
            currentHover = hitPosition;
            tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
        }
    }
    else
    {
        if (currentHover != -Vector2Int.one)
        {
            tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
            currentHover = -Vector2Int.one;
        }
    }
}
#

pls answer i am desperate

hexed terrace
#

lol, don't at everyone 🤦‍♂️
And use the !code tags to display it properly 👇

eternal falconBOT
hexed terrace
#

your code looks like AI code.

Also, for a start - this will give a compile error
if (!currentCamera || !boardActive //IS A BOOLIAN)

simple hawk
#

I created code to instantiate a bullet prefab, but how can I make a custom rotation for it? right now, it spawns according to this player rotation, which is horizontal, but I want it to be vertical.


public class shootTest : MonoBehaviour
    
{
    [SerializeField] private GameObject bulletPrefab;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))

        {
            Instantiate(bulletPrefab, transform.position, transform.rotation);
                
                }
            
        
}}
keen dew
#

Instead of using the player rotation when instantiating, use whatever rotation you want

hexed terrace
#

you did not, use 3x `

#

Instantiate(bulletPrefab, transform.position, **theRotationYouWantItToBe**);

simple hawk
keen dew
#

Yes because you just added 3 zeroes instead of a rotation

simple hawk
#

yea, I'm super confused on how it should be set out

naive pawn
#

it needs a quaternion (as the hover message shows), not 3 euler angles or whatever you've tried to set there

keen dew
#

You can do something like Quaternion.Euler(0, 0, 0) to get a rotation

naive pawn
#

also why do you want a bullet to be vertical if you're presumably trying to shoot it

keen dew
#

but if this is confusing it might be best to go through !learn beginner courses again

eternal falconBOT
#

:teacher: Unity Learn ↗

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

rigid kite
#

Hello guys. I want to make a circle like this. And I want it to be Collider sensitive. How can I do that?

simple hawk
naive pawn
#

a bullet being vertical looks better than a bullet actually pointing in the direction of travel?

#

is your mesh misaligned or something?

hexed terrace
rigid kite
simple hawk
naive pawn
#

or do you mean when looking up?

#

sounds like you'd want the rotation of the camera, not the player

simple hawk
naive pawn
#

yeah you definitely need to give more context here

#

what exactly is the issue you're having?

hexed terrace
#

put an empty transform as a child of the gun. Rotate it so that the Z forward is pointing along the barrel of the gun and at the end of it.

Spawn the bullet at the same pos/ rotation as this transform.

#

err... might not be Z forward on top down... X instead?

simple hawk
hexed terrace
#

the gun can remain part of the player sprite

simple hawk
rigid kite
# simple hawk game is in top down view, I may be getting my words mixed up
public GameObject gun;
public GameObject bulletPrefab;

public void Shoot()
{
  GameObject spawnedBullet = Instantiate(bulletPrefab);
  spawnedBullet.transform.forward = gun.transform.forward;
}

//Or if your game is top-down

public void Shoot()
{
  GameObject spawnedBullet = Instantiate(bulletPrefab);
  spawnedBullet.transform.up= gun.transform.up;
}
#

try to do this

hexed terrace
#

don't use public fields
assign the position and rotation when instantiating, not on a separate line

keen dew
#

that won't even set the position

rigid kite
rigid kite
naive pawn
rigid kite
keen dew
#

Yeah but fixing the rotation isn't very useful if the solution breaks setting the position

naive pawn
#

and spoonfeeding discourages that

hexed terrace
# rigid kite Every time I do this, it works. What is the problem with tihs?

It works, but it's bad/ beginner code.

You don't want public fields, because nothing outside of this class should have direct access to those fields, if you want them visible in the inspector use [SerializeField] private <type> myVariable;
The instantiate method has overloads, specifically for setting the position and rotation when you spawn the object, so it can be put in the correct position / rotation (etc for the other overloads), and not spawn at 0,0,0 then jump to whatever position and rotation you set after spawning it.

gloomy hamlet
#

i am creating a 3d chess game, and rn i am only at the beginning, and i am trying to, when i hover my cursor on a tile (that i created via script) it changes layer, like from( tile ) to (hover) and then comes back to (tile) when i remove my cursor from that tile. My problem now is that it isnt working even tho i got no console error and i think that my script is good. Maybe i need to add something to it idk

#
private void Update()
    {
        if (!currentCamera || !boardActive  //IS A BOOLIAN)
        {
            currentCamera = Camera.main;
            return;
        }

        RaycastHit info;
        Ray ray = currentCamera.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out info, 100,  LayerMask.GetMask("Tile", "Hover")))
        {
            //GET THE INDEXESOF THE TILE I'VE HIT
            Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);

            //IF WE'RE HOVERING A TILE AFTER NOT HOVERING ANY TILE
            if (currentHover == -Vector2Int.one)
            {
                currentHover = hitPosition;
                tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
            }

            //IF WE WERE ALREADY HOVERING A TILE, CHANGE THE PREVIOUS ONE
            if (currentHover != hitPosition)
            {
                tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
                currentHover = hitPosition;
                tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
            }
        }
        else
        {
            if (currentHover != -Vector2Int.one)
            {
                tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
                currentHover = -Vector2Int.one;
            }
        }
    }
timber tide
gloomy hamlet
#

i dont want something to happen when i click but something to happen when i ONLY put my cursor on the game object

rocky canyon
#

its really curious how u dont have errors.. when the script u sent is broken

gloomy hamlet
#

i just added it when i was sending you the script

naive pawn
#

we can tell it's a boolean by the way it's used in an if

rocky canyon
#

ahh,, well add the //comment after the )

#

or u break the if statement

gloomy hamlet
#

only cuz i didnt send

private bool boardActive;

.....

naive pawn
#

or use a /* boolean */ block comment

rocky canyon
gloomy hamlet
naive pawn
#

the boolean knows where it is because it knows where it isn't

rocky canyon
# gloomy hamlet how do i do it
        if (!currentCamera || !boardActive) //like this
        {
            currentCamera = Camera.main;
            return;
        }```or 
```cs
        if (!currentCamera || !boardActive /* like this */)
        {
            currentCamera = Camera.main;
            return;
        }```
gloomy hamlet
#

ok wait a sec

rocky canyon
#

that clears up the compile error u may or may not have. (unsure)
but that doesn't solve ur main issue (unless it does)

gloomy hamlet
#

still the same

#

the layer doesnt change

rocky canyon
#

u need to use some log statements

naive pawn
gloomy hamlet
#

when i hover my cursor on the game object

rocky canyon
#

put them in ur raycast see if its hitting anything/ what its hitting/ when its not hitting

gloomy hamlet
#

i can send the entire code if you guys want but the rest is all about generating the tiles

naive pawn
#

put some logs - is the raycast being reached, is it passing, is some other conditional not passing?

#

etc

rocky canyon
#
if (Physics.Raycast(ray, out RaycastHit info, 100f, LayerMask.GetMask("Tile", "Hover")))
{
    Debug.Log("Raycast HIT: " + info.transform.name + " on layer: " + LayerMask.LayerToName(info.transform.gameObject.layer));
    ...
}
else
{
    Debug.Log("Raycast MISS");
}```
#

u can log when u change the layer to confirm that happens..

#

so on and so on the more u know the better

#

im guessing its probably a layer / mask issue

#

for example is the tile actually on the tile layer...
(like if the collider was a child object) it could be missin

gloomy hamlet
gloomy hamlet
#

the tile the collider etc

rocky canyon
#

Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject); possibly this is broken somehow then

#

or in the LookUpTile function

#

send logs to urself in those methods and see if its outputting what it should

gloomy hamlet
#
private Vector2Int LookUpTileIndex(GameObject hitInfo)
    {
        for (int x = 0; x < TILE_COUNT_X; x++)
            for (int y = 0; y < TILE_COUNT_Y; y++)
                if (tiles[x, y] == hitInfo)
                    return new Vector2Int(x, y);
        
        return -Vector2Int.one; // -1 -1
    }
shut swallow
#

for hitboxes in my game with timestop, is it better if I store the hit and apply the effects after time has been resumed or if I instansiate a collisionbox alongside my Visual Effect object

rocky canyon
gloomy hamlet
#

k wait

rocky canyon
gloomy hamlet
rocky canyon
#

what concerns do u have to be debating the two?

rocky canyon
gloomy hamlet
#

which is?

rocky canyon
#

how do you think raycasts work?

#

what it is that causes a raycast to log a hit?

gloomy hamlet
#

like an invisble line

rocky canyon
#

whats it hitting do you know?

gloomy hamlet
#

what do you mean?

#

pls get straight to the point 😭

rocky canyon
#

a raycast hits a collider

#

ur tiles have no collider

#

so.. no raycast can ever detect them

gloomy hamlet
#
Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);
#

to this maybe?

#
Vector2Int hitPosition = LookUpTileIndex(info.collider.gameObject);
rocky canyon
#

thats using the info variable..

#

which is hit info the raycast outputs

#

but thats if the raycast detects a collider...

#

ur raycast is never hitting any of those tiles

#

u dont need to change ur code.. u need to fix ur tiles

gloomy hamlet
#

so i need to change info to hitInfo?

gloomy hamlet
shut swallow
#

I'm thinking of if using a boxcast will make my life easier because registrating the hit while the VFX is still playing is fine, any onhit effect I can delay them until after time has resumed

gloomy hamlet
rocky canyon
#

ya, thats the problem

gloomy hamlet
#

wait a sec

#

i went to my code and i saw this:

tileObject.GetComponent<BoxCollider>();

i fixed it

tileObject.AddComponent<BoxCollider>();

but it still doesnt work

rocky canyon
#

if not and theres reasons to have immediate hit detections /visual feedback id do the latter

rocky canyon
gloomy hamlet
#

they do

rocky canyon
#

then add logs in ur raycast to see if ur hitting them..

gloomy hamlet
#

wait

#

should they have box collider or mesh collider?

rocky canyon
#

it doesnt really matter..

shut swallow
gloomy hamlet
shut swallow
rocky canyon
#

you'll just want to Log the hit variable of ur raycast

#

and even put one in the if and the else Raycast succeeded Raycast Failed

shut swallow
#

for a second I thought you were responding to me lol

gloomy hamlet
rocky canyon
#

i understand that.. and these are the most basics of concepts..

#

logging is 1 of the first things u should learn

shut swallow
rocky canyon
#

it occurs on the next physics frame (FixedUpdate()) i believe

edit: my mistake.. Physics "Raycasts" are just checks not physics-driven forces or any of the like..
therefor they are practically "instant".. If you call a raycast in update it'll run a check every frame

shut swallow
#

I feel like the latter will be better then, gives more control over behaviour

gloomy hamlet
rocky canyon
#
  if (Physics.Raycast(ray, out info, 100, LayerMask.GetMask("Tile", "Hover")))
    {
        Debug.Log("Raycast succeeded");
        Debug.Log(info.transform.name);

        // GET THE INDEXES OF THE TILE I'VE HIT
        Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);
        Debug.Log(hitPosition);
        ...
    }
    else
    {
        Debug.Log("Raycast failed");
        ...

    }```
https://gamedevbeginner.com/how-to-use-debug-log-in-unity-without-affecting-performance/
rocky canyon
#

and see if it runs.. and if it doesn't.. if it does u send info thats useful to figure out what in the code isnt returning the results ur expecting.. or running at all)

rocky canyon
#

but the collider method sounds fine too

gloomy hamlet
#

absolutly nothing works

#

i feel like my brain wants to implode

#

i am about to give up on this project

rocky canyon
#

i personally feel like u bit off more than u can chew.. and need to take a step back..
for example first writing a simple raycast.. have it hit a cube directly in front of it.. see what works and what doesnt.. log that information in the console.. take in, take notes, then u grow.. expand.. and add more and more slowly

shut swallow
#

how do you exclude all collision layers except one for colliders? When initiated do they default to collide all or no layers?

gloomy hamlet
#

i did that

#

i spent the entire moring working on this

rocky canyon
#

once u had it working with a tile.. u could add in the layers..

shut swallow
rocky canyon
#

so and so on.. my point still stands.. ur biting off more than u can chew.. and resolving ur issue is going to be more frustrating for you and the helper than needs be..

#

im being generous too. most other guys will just send you the !learn links and tell you to go back to the basics

eternal falconBOT
#

:teacher: Unity Learn ↗

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

shut swallow
#

Read documentation it helps a lot

rocky canyon
#

for example i bet u unity has tile systems as examples in their documentation

sour fulcrum
#

Unity’s tile stuff is kinda mid for what most beginners will want

gloomy hamlet
hexed terrace
shut swallow
shut swallow
hexed terrace
shut swallow
#
    {
        Physics.BoxCast(
            center: castCenter,
            halfExtents: vector3HalfExtents,
            direction: slashDirection,
            hitInfo: out _meleeHitRegister
            );
        return;
    }``` bit of a stupid question: is this correct syntax?
#

does returning this gives a boolean?

hexed terrace
#

If your IDE is setup correctly, it will tell you of any compile / syntax errors.

#

you're not returning anything there.

#

void - means the method doesn't return anything, so your return at the end there does nothing, removing it and you're doing the same thing.

shut swallow
hexed terrace
#

because your wrote it like that?

shut swallow
#

I'm sorry isn't BoxCast() supposed to return a bool?

hexed terrace
#

It does.

You are not doing anything with that bool.

shut swallow
#

I just want to store it

hexed terrace
#

you have the documentation open, the documentation has example code

thorn holly
thorn holly
rocky canyon
# gloomy hamlet imma try again

https://streamable.com/6jc4km here's a vid clip i made laying out the process you probably need to take..

  • make simple raycast, raycasting using mouse position and main camera (test and confirm)
  • make tile prefab setup to work w/ raycast (collider and layer assignment) (test and confirm)
  • simply use the raycast overload that can accept a layermask, assign the 'Tile' layer or w/e layer u chose for the tiles to this layermask in the inspector (test and confirm)

Watch "SimpleGridInteraction" on Streamable.

▶ Play video
#

if u stop and test along the way you end up with smaller problems with easier solutions..
than if u wait until the end and realize it doesn't work.. but unsure why or how it became that way

lilac cape
#

Is anyone free to help troubleshoot an object interaction?
In my player controller script I have:
Getting these debug messages

  {
    playerInteraction.TryInteract();
    Debug.Log("Interact action performed");
  }

Getting these debug messages as well

using UnityEngine;

public class PlayerInteraction : MonoBehaviour
{
  Transform _transform;
  [SerializeField] LayerMask interactableLayer;

  void Awake()
  {
    _transform = transform;
  }
  public void TryInteract()
  {
    Debug.Log("Attempting to interact...");
    if (!Physics.Raycast(_transform.position + (Vector3.up * 0.3f) + (_transform.forward * 0.2f),
     _transform.forward, out RaycastHit hit, 3f, interactableLayer)) return;
    
  }
}

For some reason I'm not getting anymore debug messages: My SingleDoorControl script

using UnityEngine.Events;

public class SingleDoorControl : MonoBehaviour, IInteractable
{
  private Animator animator;
  private bool isOpen = false;
  private bool openedForward = false;

  [SerializeField] private Transform playerTransform;
  [SerializeField] private Transform doorForwardReference;

  void Awake()
  {
    animator = GetComponent<Animator>();
  }

  public void Interact()
  {
    if (!isOpen)
    {
      Debug.Log("Door was open and tried to open");
      Vector3 toPlayer = (playerTransform.position - transform.position).normalized;
      float dot = Vector3.Dot(doorForwardReference.forward, toPlayer);

      if (dot >= 0)
      {
        animator.Play("SingleDoorOpen_Backward");
        openedForward = false;
      }
      else
      {
        animator.Play("SingleDoorOpen_Forward");
        openedForward = true;
      }

      isOpen = true;
    }
    else
    {
      if (openedForward)
        animator.Play("SingleDoorClose_Forward");

      else
        animator.Play("SingleDoorClose_Backward");

      isOpen = false;
    }
  }
}
#

My interactable object and iinteractable scripts:

using UnityEngine;
using UnityEngine.Events;

public class InteractableObject : MonoBehaviour, IInteractable
{


  [SerializeField] private UnityEvent _onInteract;

  public void Interact()
  {
    Debug.Log($"Interacted with {gameObject.name}");
    _onInteract.Invoke();
  }
}
using UnityEngine;
using UnityEngine.Events;

public interface IInteractable
{
  // public UnityEvent Interact { get; protected set; }
  public void Interact()
  {
    Debug.Log("Interact method called on IInteractable");
  }
}

#

My player and door have the following components:

#

Let me know if there is anything else I can provide that would be helpful 🙂

#

I'm thinking the problem might lie somewhere on my player interaction script. Maybe it's not called the Interact right?

#

Door is on the intractable layer

hexed terrace
#

you say you don't get any logs, and then the next code block doesn't have any logs in it

eager elm
hexed terrace
#

your PlayerInteraction class doesn't actually call any interaction.. it's just raycasting looking for an interactable layer

lilac cape
# hexed terrace you say you don't get any logs, and then the next code block doesn't have any lo...

Ahh you're right Gruhlum, I added a debug message inside this method and I do see the debug message in the console:

public void TryInteract()
  {
    Debug.Log("Attempting to interact...");
    if (!Physics.Raycast(_transform.position + (Vector3.up * 0.3f) + (_transform.forward * 0.2f),
     _transform.forward, out RaycastHit hit, 3f, interactableLayer))
    {
      Debug.Log("No interactable object found in range.");
      return;
    }
    else
    {
      return;
    }

  }
hexed terrace
#

right.. but you're not doing anything... you're not getting the component to call the interact method on it. Methods don't run if you don't call them.

eager elm
#

see if "hit" has a Component of Type IInteractable and then call Interact() on that component

lilac cape
#

Something like this?


public class PlayerInteraction : MonoBehaviour
{
  Transform _transform;
  [SerializeField] LayerMask interactableLayer;

  void Awake()
  {
    _transform = transform;
  }
  public void TryInteract()
  {
    Debug.Log("Attempting to interact...");
    if (!Physics.Raycast(_transform.position + (Vector3.up * 0.3f) + (_transform.forward * 0.2f),
     _transform.forward, out RaycastHit hit, 3f, interactableLayer))
    {
      Debug.Log("No interactable object found in range.");
      return;
    }

    // Get the IInteractable component and call Interact()
    var interactable = hit.collider.GetComponent<IInteractable>();
    if (interactable != null)
    {
      interactable.Interact();
      Debug.Log("Interact called on: " + hit.collider.name);
    }
    else
    {
      Debug.Log("Hit object is not interactable: " + hit.collider.name);
    }
  }
}

#

Just tested and only getting to the attempting to interact debug message

rocky canyon
# lilac cape Something like this? ```using UnityEngine; public class PlayerInteraction : Mon...
 void Update()
    {
        ray = new Ray(cam.transform.position,cam.transform.forward);

        if(Physics.Raycast(ray,out RaycastHit hit,distance,mask))
        {
            if(hit.collider.TryGetComponent(out IInteractable interactable))
            {
                cachedInteractable = interactable;
                cachedTransform = hit.transform;
                cachedHitPoint = hit.point;

                if(Input.GetKeyDown(interactKey))
                {
                    cachedInteractable.Interact();
                    Dbug.Italic($"Interacted with {cachedTransform.name}");
                }
            }
            else
            {
                ClearCache();
            }

            draw = true;
        }
        else
        {
            ClearCache();
            draw = false;
        }
    }``` heres how mine looks if it helps any..
eager elm
#

if you don't see "No interactable object found in range." than that means that you found an object but it doesn't have an IInteractable Component

rocky canyon
rocky canyon
eager elm
#

well, something isn't right tho, because you should either way get one more Debug massage

rocky canyon
#

-check layermask
-check ur actual raycasting position and direction
-check that the object is in range and not blocked by something else
-check that the object has a collider and its not on a child or something else

#

do what i did ^ and just log the hit info in the console or inspector at first.. make sure its detecting the thing that has the component..

#

and that u dont have to retrieve it from up or down its hiearchy

lilac cape
#

So on my player gameobject, I changed the player interaction serialized field to Player Interactio and the door is opening now. Originally I had this set to playerinteractionmanager. Is it better to try and set unity events up in a manager? Sorry if this question is badly worded. Just started learning how to set up more scalable unity events yesterday..

lilac cape
#

Visual view:

median hatch
#

to open a door?

lilac cape
#

Honestly to have a system that makes it easier to add future events like picking up object, throwing things, interacting with different object with different results, etc

rocky canyon
#

well the goal would be bigger than that. if they're doing an Interactable Interface

median hatch
#

interfaces are perfect for this

#

you make an IInteractable interface

#

and objects that are interactable can have different behaviours

rocky canyon
#

ya, interfaces w/ trygets is my jam 🪕

lilac cape
#

I'll have to look into interfaces. What were y'alls favorite resources while learning how to use them?

rocky canyon
#

tbh interfaces were trial and error + friends help

#

basically its just this tho

#

and then anything that inherits just has to have that Interact() method

#

and for a pickup:

lilac cape
#

Then you just have a super long switch statement? Somethign that has all the interactions?

rocky canyon
#

well the switch is only b/c my switch class can function 3 different ways

#

like toggle, push to start, etc

lilac cape
#

ahh, nice

rocky canyon
#

u just call the function with the Interactable Raycaster or w/e

#

my raycast doesn't really care if its a pickup, a switch, any kind of action..

#

it only has to call .Interact()

lilac cape
#

What confuses me the most is when linking interact() with the method that does the action. I feel like seeing Interact() everywhere confuses me but I like the benefit lol

rocky canyon
#

if its an IInteractable -> then it must have an Interact() method..
if it has an Interact() method.. i'll just call it.. theInteractableYouHaveSelected.Interact();

eternal needle
median hatch
# lilac cape Then you just have a super long switch statement? Somethign that has all the int...
public class TunaCan : MonoBehaviour, ICollectible
{
    [SerializeField] PlayerController playerController = null;
    [SerializeField] bool isMovingToPlayer;
    [SerializeField] bool isCollected;

    public static event Action OnCollectTunaCan;

    // Update is called once per frame
    void Update()
    {
        if (isMovingToPlayer)
        {
            transform.position = Vector3.MoveTowards(transform.position, playerController.transform.position, UnityEngine.Random.Range(0.1f, 0.2f));
        }
    }

    public void Collect(PlayerController playerController)
    {
        this.playerController = playerController;
        isMovingToPlayer = true;
    }
#

my code is simpler

#
using UnityEngine;

public class Collect : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Collectible"))
        {
            PlayerController playerController = GetComponentInParent<PlayerController>();

            ICollectible collectible = other.GetComponent<ICollectible>();
            collectible.Collect(playerController);
        }
    }
}

then just a lil script that calls that interface

lilac cape
#

Could you use that Collect class on an any gameObject you want to be collected?

median hatch
#

for me anything that is tagged Collectible will have a ICollectible interface

#

that i can do whatever i want with

rocky canyon
#

🎮 easymode:```cs
if (hitObject.CompareTag("Pickup"))
hitObject.GetComponent<Pickup>().DoPickup();
else if (hitObject.CompareTag("Switch"))
hitObject.GetComponent<Switch>().Toggle();
else if (hitObject.name.Contains("Lever"))
hitObject.GetComponent<Lever>().Activate();

🕹️ skilled-mode:```cs
if (hit.collider.TryGetComponent(out IInteractable interactable))
{
    interactable.Interact();
}```
median hatch
#

in this case collect

#

it seems a bit weird at first but its one of the most powerful ways of not repeating your code

lilac cape
rocky canyon
#

no thats the cool thing about them..

median hatch
#

just a Collectible tag and when player goes over them boom

rocky canyon
median hatch
#

magic

rocky canyon
#

the fact this script has a Switch that inherits from IInteractable

#

my raycast just grabs it

#

i even use Interfaces as tags sometimes

#

well actually i just use an empty script

#

but same idea

median hatch
rocky canyon
#

well my raycast does raycast all the time yea

#

but the tryget fails if its not an Interactable

#

so none of that logic gets run

median hatch
#

just a bit weird, why not put those IInteractable objects in a layer?

eternal needle
median hatch
#

otherwise you're looking at anything and checking for IInteractable constantly

zenith cypress
#

Pretty common and isn't really a problem (I do this in every project that wants interactions).

rocky canyon
#

i can find my interactables pretty easily

#

and its a way to save tags imo

median hatch
#

ah sounds good then

#

yea i got a lot of tags...

#

xD

rocky canyon
#

and i can have more than 1 interface on a Gameobject 😉

median hatch
#

true true

#

although one should be enough

#

dont want any race conditions happening

rocky canyon
#

ya, for basic games 1 or 2 is enough for Interactions

lilac cape
#

Is it better to have an interface system when working with inventory systems?

brave robin
#

I just don't use tags because something can only have 1 tag, which limits their usefulness
My interactables have a separate object with the trigger collider that exists on an Interactable layer, just for raycasting. But the parent object can be on any layer.

median hatch
#

you see it with minecraft

#

some objects arent stackable

#

interfaces are pretty good for that type of stuff

brave robin
#

Interfaces unravel OOP inheritance into something more sane

median hatch
#

yea was honestly one of the best things to learn

#

the code in general gets so much cleaner

lilac cape
#

are scriptable objects another thing to learn as well? I honestly don't know much about interfaces or scriptables object..yet

median hatch
#

yup

#

just remember to only store static data in them

#

they dont save during runtime

brave robin
#

Absolutely, they are very handy as data containers and for compartmentalizing some methods, like RPG skills

grand snow
#

They can also be used for logic in a way you can share easily over many scenes but its easy for it to get unloaded so duplicate instances may be made accidently.

lilac cape
brave robin
#

All the skills, stats, spells, items, traits, monster setups, dialogue, and many other bits of data are scriptable objects in my game

eternal needle
median hatch
#

just make things work

eternal needle
brave robin
#

The chances of actually noticing bad performance in your game when starting out is pretty negligible. By the time you're doing stuff that hurts performance, you'll have the experience needed to tackle it

lilac cape
median hatch
#

my point is if you try to save data into a scriptable object the next time you run your game its gone

grand snow
#

(except in editor where its kept cus dumb)

lilac cape
eternal needle
brave robin
median hatch
grand snow
lilac cape
grand snow
#

Unity should fix scriptable objects keeping the changes post play to make it clearer its not a thing

#

surely it can just re apply the saved data after

brave robin
#

If my scriptable object's state is being changed in game, I store a separate value on it which is the Current value. The current value is set to be the same as the initial saved value, and then only the Current one gets modified.

eternal needle
median hatch
#

you change the spawn location var in the SO, next time you reload the game you're at the beginning

lilac cape
median hatch
#

making games is super hard

#

its normal to get overwhelmed

eternal needle
# lilac cape Yeah I got some tutorials and guides to read up on

you'll likely learn this quicker outside of unity tbh. if you've done your c# basics first then itll be no problem. Find any tutorial that talks about some animals interface, then makes a cat dog and puts them all in the same array and boom its solved. Then try to extend that to your own kind of class

#

there isnt much to learn about interfaces

lilac cape
#

Yeah right now I just have dev_playground project and I'm just tackling random things like making doors open both way or picking up cubes. If I need a quick idea I usually just as AI for something to build out. Once I found out how much goes into player movement it made me appreciate games a LOT more becuase players don't see what makes a game, a game

median hatch
zenith cypress
# grand snow (except in editor where its kept cus dumb)

It's not dumb, and makes sense. In the editor, if you don't instance the SO before modifying it, then you are directly modifying the asset itself. In a built game it basically just loads the SO from the game's resources each time you boot the game, which doesn't change since there are no "assets" anymore.

median hatch
#

once you start diving into it you realize how deep the rabbit hole goes

grand snow
lilac cape
#

It never ends haha. When you think it does the next editor verison comes out..

rocky canyon
#

even if there weren't any new releases from now on.. it'd be unlikely u'd still know everything there is to know

#

and theres some things u never need to know..

#

im building a 3D game.. i don't need to know how the tilemap system works

#

only master nerds know everything bout the entire engine 😈

lilac cape
#

One of my goals is to get suuuper good at unity so that by the time Unity 7 alpha gets released (late 2026 or 2027), I can start making guides on how to use it and hopefully even a course. That was one of my biggest OCD complaints when learning because I'd be on unity 6 but the guide was using 2019. Even those there should be compatibilities, just having a guide that uses the version your on is just helpful. Making a course would also hopefully expose me to Unity areas I hadn't seen before so it's another reason I'd want to tackle something like that.

lilac cape
#

Also @simple hawk any luck on learning the new input system? This was a really helpful video that I used to help learn the system. After watching the tutorial I first studied how each part connected to eachother and then I just kept trying to make my own input system basic control scheme from scratch until I could make it without really needing to glance at the completed code:
https://www.youtube.com/watch?v=Yjee_e4fICc&t=60s

scarlet skiff
#

ok so i have an enemy that i want to stop moving for a bit every now and then, i already got the logic for when it stops moving, to wait a bit before mvoing again, but for stopping movement, can i just start such a coroutine inside start()?

private IEnumerator ResetWalkWaitTimer(float wait)
{
      yield return new WaitForSeconds(wait);
      float delay = Random.Range(5f, 10f);
      waitBeforeWalkTimer = 0f;
      StartCoroutine(ResetWalkWaitTimer(delay));
}
rich adder
#

and probably even make Start itself the coroutine (unless you call ResetWalkWaitTimer at later time)

acoustic belfry
#

Hi, what would be better for move a dynamic rigid object to follow another actor and to move side to side
linearvelocity or addforce?

also, how i can make an int of a script be private but only be accesible for the children of that script? When i make it privated its childrens can't interact with it

rich adder
#

are you talking about inheritance or components in other gameobjects
also linearvelocity or addforce both move the rigidbody properly, addforce takes mass/friction other physics attributes into account, velocity doesn't

polar acorn
acoustic belfry
#

nop, my english is bad, is not heredero, is herencia, but yeah, that thing is

rich adder
#

check the link posted above , you can use protected or private protected

acoustic belfry
#

ooh, interesting, thanks :3

acoustic belfry
rich adder
acoustic belfry
rich adder
#

they are both good methods, different "feel"

acoustic belfry
#

I think velocity is simplier. Cuz i dont need friction and others to be calculed, thanks :3

acoustic belfry
#

how i can fuse functions between inherites?
I mean, i have that in the baseScript update it flips depending on a value transform.localScale = new Vector3(-1, 1, 0); , and i want the InheritedScript update to do the same and play an animation clip animator.Play("Base Layer.MortemRifleSight"); but without having to write the flipping part that belongs to the base, how i can do so?

#

i know how to replace, using overdrive, but i dont know how to fuse

naive pawn
#

you mean override?

#

you can call the base method with base.Method

#
class A {
  public virtual void Print() {
    print("A");
  }
}

class B : A {
  public override void Print() {
    base.Print();
    print("B");
  }
}

new B().Print(); // prints `A` then `B`
short hazel
#

Yeah if you have that in Update, Unity won't call the base class' Update so you have to do it yourself by making it virtual and calling it from the override

vocal wharf
#

General question here. If I have two variables (int type) that are set to different values and I write an equality statement such as
numberA = numberB
does numberA get set to the value of numberB or vise versa? Basically which order does Unity use?

short hazel
#

The value of numberB gets copied into numberA

#

Right-to-left for assignments with =

acoustic belfry
#

i was replacing my old enemy movement with a new one that uses their rigidbodies....but i discovered an issue.........................why my enemies fly?

                mortemRb.linearVelocity = direction * runSpeed;```
naive pawn
naive pawn
#

it's analogous to := in math, as in x := y -> "let x be equal to y"
some languages use := for assignment, but most just use =

naive pawn
#

are you doing sidescroller or top-down?

lilac cape
acoustic belfry
#

now i fix it

#

they no longer fly

#

ths was the bad script

#
                mortemRb.linearVelocity = direction * runSpeed;```
naive pawn
#

yeah thought so

acoustic belfry
#

but, now i have another problem

naive pawn
#

though this means it'll run slower if they aren't at the same elevation

#

instead of normalizing the vector, you'd want to normalize just the x value
you can use Mathf.Sign/Math.Sign for that (depending on what you want to happen if they're perfectly inline vertically)

acoustic belfry
#

oh

#

how i can fix it then?

vocal wharf
#

Is there a way to exclude a single item when using Random.Range to select from an array? I have a string array (six individual letters of the alphabet) and I'm trying to randomly generate one after the other without repeating the previous letter that was generated. I tried assigning a "lastMove" integer to the last array item that was picked and checking if the current item number matches the "lastMove" number using an if/else statement but this doesn't work if the random number is identical twice in a row. Any ideas would be appreciated.

#

here is the script if needed. Useless context: it's a Rubik's Cube random scramble generator and I'm trying to generate 20 random letters consecutively (each letter in the array stands for turning a certain face on the cube).

public class NewScramble : MonoBehaviour
{
    public TextMeshProUGUI scramble;
    private string[] possibleMoves = {"R", "L", "U", "D", "F", "B"};
    private string[] moves = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", 
        "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"};
    private int moveSelector;
    private int lastMove;
    void Start()
    {
        GenerateNewScramble();
    }

    public void SelectNextMove()
    {
        moveSelector = Random.Range(0, possibleMoves.Length);
    }
    public void GenerateNewScramble()
    {
        SelectNextMove();
        lastMove = moveSelector;
        moves[0] = possibleMoves[moveSelector];
        SelectNextMove();
        if (moveSelector == lastMove)
        {
            SelectNextMove();
            lastMove= moveSelector;
            moves[1] = possibleMoves[moveSelector];
        }
        else
        {
            lastMove = moveSelector;
            moves[1] = possibleMoves[moveSelector];
        }

    }
}
#

The text object reference hasn't been used yet because I'm trying to figure out this part first

naive pawn
wintry quarry
acoustic belfry
# acoustic belfry how i can fix it then?

also, i made an if statement that if the distance is less than x value, it should stop, it worked when i used the transform.position, but not with the rigidbody

{
    if (distanciaAbsoluta > rangoDisparo)
    {

        animator.Play("Base Layer.MRifle_Walk");
        Vector2 direction = (objetivo.position - transform.position).normalized;
        mortemRb.linearVelocity = direction * runSpeed;
        bullettimer -= Time.deltaTime;
        if (bullettimer <= 0)
        {
            bullettimer = firingspeed;
            disparar();
        }
    }
    else
    {
        bullettimer -= Time.deltaTime;
        if (bullettimer <= 0)
        {
            bullettimer = firingspeed;
            disparar();
        }
    }

}```
naive pawn
vocal wharf
wintry quarry
naive pawn
vocal wharf
naive pawn
#

you might want to step back and learn about programming fundamentals first rather than stumbling through code

#

see pinned resources

vocal wharf
naive pawn
naive pawn
#

additionally - with how you've written it, you can't get R as the first move, you should probably check that

wintry quarry
#

I don't know anything about rubik's cubes so I don't understand what the goal is here really

#

so I'll back off

acoustic belfry
naive pawn
#

also you probably should not have that moves array literal, you can just do new string[20] for an empty array
but a list would probably make it much easier

naive pawn
naive pawn
naive pawn
acoustic belfry
#

i got lost

acoustic belfry
naive pawn
#

in these 3 scenarios, should the chase speed be the same

acoustic belfry
#

oh now i get it, i guess it will

#

sorry

#

so...how i can fix this?

(i fixed the radius issue, i just had to put mortemRb.linearVelocity = Vector2.zero)

naive pawn
#

if you normalize the entire vector and then get just the x value, the x value's magnitude will be <= 1
you'd want it to be == 1 for a consistent speed, regardless of vertical offset

vocal wharf
naive pawn
acoustic belfry
#

but i mean, speficitly

naive pawn
#

actually i think you missed what i'm referring to

#

a list is similar to an array, just used differently

naive pawn
acoustic belfry
#

Ok

#

Sorry if i btw sounded rude...

Well, thanks UnityChanThumbsUp

vocal wharf
naive pawn
#

lists aren't restricted to when the number of elements is unknown

vocal wharf
#

I'm not sure how it would make things easier though

naive pawn
#

if you treat the "amount of moves already generated" as the number of elements changing, you now no longer need to keep track of how many moves have been generated

#

if you used an array, you would have to keep track separately (or more realisitcally you could use a for loop)

#

with a list the flow becomes more flexible since the loop would no longer be bound to the amount of elements stored

vocal wharf
#

hmm ok I'll look into it

naive pawn
#

here's 2 possible ways you could do it with an array:

moves = array[20]
generated = 0
while generated < 20:
  nextmove = randommove()
  if generated == 0 or nextmove != array[generated - 1]
    array[generated] = nextmove
    generated += 1
``````py
moves = array[20]
for i in 0..19
  do
    nextmove = randommove()
  while i != 0 and nextmove == array[i - 1]
  moves[i] = nextmove
```how you could do it with a list:
```py
moves = list
while moves.length < 20
  nextmove = randommove()
  if moves.length == 0 or nextmove != moves.last
    moves.add(nextmove)
#

with the array approach, you have to manage moving through the array yourself - which isn't bad in itself, but IMO using a list gives a much clearer flow for logic

vocal wharf
#

I'll try it thanks

acoustic belfry
naive pawn
#

yeah

acoustic belfry
#

nice

thanks ✨

rapid laurel
#

for those who have problems with firebase in the future like me, the problem was that I had to download the google.services.json again and import it because something had changed, I don't know why, but now it works.

vocal wharf
acoustic belfry
#

sorry for asking a lot...

But, if the script A has an int, and i want to have the same int in script B but with another value, what i should do?

#

how i can override that value?

naive pawn
naive pawn
vocal wharf
#

I assume I need to make a reference to the moves list at the top of the class?

naive pawn
#

if by "top of the class" you mean as a class member, then yes

acoustic belfry
vocal wharf
acoustic belfry
#

the thing is now i want to make a huge base for all my enemies, for make scripting my enemies more easier, or so i think

#

but before the rainbow i need the storm, to wich is where im right now, traslading my main enemy into the base
thats why im asking so much stuff

naive pawn
#

nextmove is a variable for storing the generated next move before commiting it into the moves list
randommove() is a method to get a random move

vocal wharf
#

oh I thought you were referencing something else my bad

naive pawn
acoustic belfry
#

just make that the base script float "speed" is zero, meanwhile in each enemy differs

naive pawn
#

just set it in the inspector?

#

you'd have a prefab for each enemy type, no?

austere monolith
naive pawn
#

why is gravity multiplied by speed?

#

anyways gravity is an acceleration, not a velocity

austere monolith
#

im using a char controller

naive pawn
#

think about what each value you're using actually represents

#

x and z are magnitudes, then you multiply those by directions, then you add that with an acceleration
then you multiply that by speed, and then the time factor

#

move * speed is a velocity - a speed with a direction
that's what acceleration should be applied to

austere monolith
#

ok

#

kinda simple ig, i just didnt know what to do

austere monolith
naive pawn
#

aren't you supposed to call Move exactly once per frame with a cc

austere monolith
#

its working

#

so yeah

naive pawn
#

if that expectation is broken then it's not gonna be reliable

#

are you doing it all from scratch?

#

you should probably find a tutorial or something

austere monolith
#

no, im watching one rn

naive pawn
#

are you following a tutorial?

austere monolith
#

haha

#

Brackeys

#

my king

naive pawn
#

and Move is called twice in the tutorial?

austere monolith
#

mhm

#

if its by brackeys then hes right 😂

naive pawn
#

well docs don't say anything about it so shrugsinjapanese

austere monolith
#

lolol

polar acorn
# austere monolith mhm

Around here we call that "The Brackeys Error" because it's been a goddamn albatross about our necks for a decade now

#

Don't call Move twice per update

supple flume
#

chat, why cant i access a var from the mauz[,]

eternal falconBOT
polar acorn
naive pawn
austere monolith
#

ch.Move(move * speed * Time.deltaTime);
ch.Move(velocity * Time.deltaTime);

how do i put those two together tho?

supple flume
polar acorn
supple flume
#

i am using the array not the assigned script

naive pawn
#

you could probably have mauz be an array of ag if that's the main component you want to actually use

supple flume
#

i figured out the mistake lol

naive pawn
#

should probably name stuff better though

supple flume
naive pawn
#

"agagag" is a word?

supple flume
#

oh no

#

agagag isnt

#

but mauz is

polar acorn
naive pawn
#

yeah the "agagag" is the main one i was referring to

polar acorn
#

Yeah, mauz seems normal

naive pawn
#

though, types should generally be in PascalCase, so ag should be Ag

naive pawn
#

make sure to add parentheses so the * Time.deltaTime happens last

austere monolith
#

ch.Move((move * speed + velocity) * Time.deltaTime);

yep gotit

naive pawn
#

alternatively, you could have speed multipled into move and then add velocity directly, or since it's only the gravity velocity, you could have that just be a float and add that multiplied by Vector3.down etcetc.. there's a lot of was to achieve this

austere monolith
#

its my first time experimenting w char controller bc i use rb usually, i think i like the customizability more in char controller

austere monolith
austere monolith
naive pawn
#

grave marks surrounding the code for inline code, 3 for a codeblock with an optional language

polar acorn
#

!code

eternal falconBOT
naive pawn
#

Not quotation marks.

austere monolith
#

oh

polar acorn
#

` is not '

austere monolith
#

wrong thing

naive pawn
#

that embed is technically wrong, 3 backticks is a codeblock
inline code is single backticks

austere monolith
#

hi

#

ok

#

thanks guysd

vocal wharf
#

VS puts squiggly red lines under nextMove != moves.Last

polar acorn
vocal wharf
#

it says "Operator '!=' cannot be applied to operands of type 'string' and 'method group'"

polar acorn
#

You probably want to run the function

vocal wharf
#

I need to take a break man this is confusing

stoic summit
#

anybody have any idea why this would be crashing roughly 25% of the time? my only idea is that raycasts might be really intensive computationally when you're doing them a couple hundred times at once, but I'm not sure on that.

polar acorn
#

Why are you taking one thing, casting it to itself, then making a list of one element to loop over?

#

Also this. Just use gameObject. You don't need this variable at all

stoic summit
stoic summit
#

it works though??

polar acorn
#

This literally just stores transform into a variable named spawn

stoic summit
#

it spawns a chunk at each one

polar acorn
#

Oh god damn it this is because of transform's weird gimmicky IEnumerable implementation isn't it

#

Okay, yeah, so Cast<Transform> on a transform magically turns it into a collection because of a terrible design decision Unity made 20 years ago.

stoic summit
polar acorn
#

You can still cut all the linq out and do foreach(Transform spawn in transform)

stoic summit
#

I code like a cro-magnon

polar acorn
#

Do any of the objects you are spawning themselves have this script on it

stoic summit
polar acorn
#

And then change it as you spawn things

stoic summit
#

hella, ty

polar acorn
#

As to why it crashes, it looks like it's because you only actually increment i if the raycast hits anything

#

If it doesn't, you spawn a bunch of things and then run the loop again without changing i

#

So if those things spawn in within view of the raycast, you'll go infinite

#

Actually, scratch that, reverse it. That's a !

stoic summit
#

yup was boutta say

polar acorn
#

So if they spawn in and they are in view of the raycast, they'll go infinite

stoic summit
#

that makes sense, easy fix at least lol

#

I appreciate the help bro

vocal wharf
#

@naive pawn do you think this looks ok? How can I display the moves with text? I could only think of scramble.text = moves but for some reason I get an error. Here is the whole code.

public class NewScramble : MonoBehaviour
{
    public TextMeshProUGUI scramble;
    private List<string> moves;
    private string[] possibleMoves = {"R", "L", "U", "D", "F", "B"};
    private string nextMove;
    
    void Start()
    {
        GenerateNewScramble();
    }

    public void GenerateNewScramble()
    {
        moves.Clear();
        while (moves.Count < 20)
        {
            nextMove = possibleMoves[Random.Range(0, possibleMoves.Length)];
            if (moves.Count == 0 || nextMove != moves.Last())
            {
                moves.Add(nextMove);
            }
        }
    }
}
#

scramble.text = moves; gives the error "Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string'" which to me seems like it should be the same thing but I guess not

eternal needle
vocal wharf
polar acorn
#

Am entire box of pop tarts is not "a pop tart" you shouldn't have that for breakfast

vocal wharf
#

Got any tips for what I can do?

polar acorn
#

Which one did you want to set scramble.text to?

vocal wharf
polar acorn
#

Did you want to combine the list into a single string? Did you want to set it to one element in that list?

vocal wharf
rapid laurel
#

Hii, should i see users connected in Analytics dashboard with just sendind logs or i need to add anything?
FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
FirebaseAnalytics.LogEvent("user_registration_success");
FirebaseAnalytics.LogEvent("user_login_success");

polar acorn
frosty hound
vocal wharf
#

I must be slow or something

polar acorn
eternal needle
vocal wharf
# polar acorn First parameter is the thing you want in between each element of the list. Secon...

So I got it all worked out but when I press play in Unity it gives the error "Object reference not set to an instance of an object" for all the lines having to do with the moves list. I have it referenced in the top of the class but it must have something to do with the fact that the list is empty at the start? I'm not sure. Any pointers on what's wrong here?

public class NewScramble : MonoBehaviour
{
    public TextMeshProUGUI scramble;
    private List<string> moves;
    private string[] possibleMoves = {"R", "L", "U", "D", "F", "B"};
    private string nextMove;
    
    void Start()
    {
        GenerateNewScramble();
    }

    public void GenerateNewScramble()
    {
        moves.Clear();
        while (moves.Count < 20)
        {
            nextMove = possibleMoves[Random.Range(0, possibleMoves.Length)];
            if (moves.Count == 0 || nextMove != moves.Last())
            {
                moves.Add(nextMove);
            }
        }
        scramble.text = string.Join(" ", moves);
    }
}
polar acorn
vocal wharf
polar acorn
vocal wharf
#

I assumed that's what the reference at the top of the class does?

polar acorn
#

No, that creates a variable. Where do you assign a value to that variable?

vocal wharf
#

nowhere I suppose

polar acorn
#

That would be your issue

#

moves is null since you never create it

vocal wharf
#

how do I assign a value to it?

polar acorn
#

With =

vocal wharf
#

ah I see now

#

IT WORKS

#

you're a legend

tawdry axle
#

Hey everyone. I'm working on a 2D arcade beatem up game in unity and I'm having trouble with the enemy AI flipping 90 degrees in the X-axis whenever I hit play. Here's a video of it happening

#

I have the z-rotation constrained in the inspector and here's the code I have for the enemy rn

using UnityEngine;
using UnityEngine.AI;

public class Enemy1 : MonoBehaviour
{
    private NavMeshAgent agent;
    private Transform player;
    //public float walkSpeed = 3f;

    Rigidbody2D rb;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        agent = GetComponent<NavMeshAgent>();
        player = GameObject.FindGameObjectWithTag("Player").transform;
        

    }

    private void FixedUpdate()
    {
        agent.updateRotation = false;
        // Move towards the player using the NavMeshAgent
        if (agent != null && player != null)
        {
            agent.SetDestination(player.position);
        }
        //rb.linearVelocity = new Vector2(walkSpeed * Vector2.right.x, rb.linearVelocity.y);
    }
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
rich adder
#

oh its the navmesh agent

tawdry axle
#

@rich adder I'm using a navmesh agent and rigidbody component

rich adder
tawdry axle
#

Yeah it's a polyshape that I put the navmesh surface component on

quick monolith
rich adder
quick monolith
quick monolith
rich adder
#

showing which part of tutorial you're at wouldn't hurt either

quick monolith
#

In this Unity tutorial we're going to look at how to create enemy spawn points.

These spawn points will periodically create new enemies, giving us an unlimited horde of zombies to fight.

This is the twelfth video in our series showing how to make a full top down 2D shooter game in Unity.

The playlist for this series can be found here
► http...

▶ Play video
tawdry axle
#

@rich adderturning off the mesh collider doesnt do anything and turning off the nav mesh agent breaks the enemy movement entirely

tawdry axle
#

I meant the capsule collider

rich adder
#

I said remove those completely

#

and test

tawdry axle
#

its not letting me remove the rigidbody for some reason but removing the 2d capsule collider just stops the enemy from being able to move the player

rich adder
tawdry axle
#

Sorry I was able to remove the rigidbody but that didnt do anything/change the rotation

#

I can send a video

rich adder
# tawdry axle

yea its weird..can you screenshot the view so can see which way the navmesh surface from another view see where exactly that agent is going

rich adder
#

thats why its not working... I thought you had more of a ZX plane going instead ur still using 2D renderer and YX ?

#

the orthographic view in scene view messed me up

rich adder
# tawdry axle

you could deal with the navmesh walking like this but keep the sprite facing the camera , you can rotate the graphics on child only but you still need a way to interact with the collider..

deep moss
#

How do I code like snapping objects using empty child? Like robot arm has an empty child place next to a body and snaps when close. Something like transform and distance or something?

alpine summit
#

I'm not sure of the exact terms to describe what I'm looking for here so bear with me: Is there any way to give a script a list in the editor that I can fill by dragging in scripts with subclasses of a certain class? So that, in the main script, I can instantiate those subclasses for my game

#

more concrete context:

slender nymph
#

what is the Player type? is it a plain c# class or does it inherit monobehaviour? if it is the latter then it should JustWork™️ and you can drag prefabs that have a component that derives from Player into it. otherwise you wouldn't be "dragging in scripts", at best you could write a property drawer (or use an asset that does so) combined with SerializeReference to allow a dropdown list for the derived types, but it would be instances of that object stored in the array, not just a list of subclasses

alpine summit
tawdry axle
rich adder
rich adder
deep moss
#

Someone thought me a little but cant seem to remember the steps, something having to do with the parent having the script and the child as its position to snap

rich adder
deep moss
#

they use some kind of threshold too if im not mistaken

rich adder
#

thats always a given, you'd need to know when can you start snapping

#

tbh this a bit complex todo cause unity move .position from the origin point, you'd need to know the offsets and do quite a bit of math

alpine summit
slender nymph
#

read the two options I provided and choose which of the two best suits your needs

near thicket
#

I'm doing a basic rendermesh but it disappears whenever I change something, I have to stop and restart the player

wintry quarry
#

Also your code is creating new arrays every frame instead of reusing one, which is pretty inefficient.

near thicket
#

yep I fixed it

night minnow
#

I'm trying to make a script that takes the location of your mouse cursor and moves a sprite over to that position. However the final result is way too large of a number and I need help with calculating it down so that it works within the game canvas.

brave robin
night minnow
#

I suppose? When referring to "Get Mouse Position" is that calculated based on the world space or canvas space?

slender nymph
night minnow
#

Sorry about that! I didn't realize there was a server just for visual scripting. Thank you!

versed light
#

i have this in my scriptable object:

[SerializeField]
GameObject _prefab;

I select my prefab from the list and it assigns but says "Type mismatch". Feel like i might be doing something dumb but i can't figure it out at this hour...

#

what does the error even mean in this context

slender nymph
#

are you assigning a field on a prefab? because you are selecting a scene object which prefabs cannot reference

versed light
#

what do you mean by assign a field on to a prefab ?

slender nymph
#

i mean is the object you are editing that is in the inspector a prefab

versed light
#

oh, its a field in a scriptable object not a gameobject

slender nymph
#

i do not mean the object being selected in the window because that is not a prefab, it is an instance of a prefab.

slender nymph
versed light
#

oh i thought the blue cube symbol meant it was the prefab version

slender nymph
#

you're selecting an object in the Scene tab which means you are selecting a scene object. the blue symbol just indicates that it is an instance of a prefab

versed light
#

oh i see now i had to hit the Assets tab

#

thanks ! 🙂

alpine summit
#

but thanks for the help

slender nymph
#

that's so much worse

alpine summit
#

worse than if Player were a MonoBehavior but if it works it works

timid salmon
#

Why is it every time i spawn a prefab om my bullet it says the size is negative

sour fulcrum
#

Is the size negative

timid salmon
#

Nope

#

nevermind it was omg srry🙏 😭

split plover
#

Sorry if thisis a stupid question, but what do voids do? Didn't find anything about it on the unity beginner scripting course so far

#

i looked it up and it says it stops things from returning a value, but if things dont return a value then how does code work in a void

sour fulcrum
#

so functions can return things, void returns nothing

#

so like

split plover
#

so im supposeed to put void on non functions?

frosty hound
#

For the record, they're not called "voids" , they're called functions.

split plover
#

wait i was supposed to be learning c++?

frosty hound
#

No

split plover
#

i've been learning c# 😭

#

oh

#

okay

sour fulcrum
#

when you use a printer it might be

Paper PrintPaper(Paper blankPage)
//stuff to fill paper
return (filledPaper)

but when you say, email someone, you don't get anything back from that action, hence void

split plover
#

im not calling functions voids

frosty hound
#

Yes, you're talking about the Start function , which returns nothing (void)

split plover
#

i literally mean void

#

i think im confused

frosty hound
#

void AddNumber (int a, int b)

int AddNumber (int a, int b)

Both of these are functions.

#

The first will not send anything back from the function, hence void (ie, "nothing"). The second will send back an int via a return line.

split plover
frosty hound
#

ignore it

split plover
#

ok

frosty hound
#

Edited for clarity, it means the same thing.

#

Stop spouting nonsense, you're offering nothing to this conversation.

split plover
#

So you put void on functions that you dont want to give code, does that mean if you put it in a earlier code block so that you can call the function in any code block connected instead of putting the function in every code block?

sour fulcrum
#

not give code, give value

split plover
#

well

sour fulcrum
#

the code in the function runs regardless of what it returns

split plover
#

yeah i guess thats what i mean

split plover
frosty hound
split plover
frosty hound
#

Whether you can access those functions to call, depends on scope. Which is to say, if it's a private or public function.

sour fulcrum
frosty hound
#

When you don't want that function to send something back to the line that called it.

#

Here's an example:

#
// Example of a function returning something back to the line that called it

void Start()
{
   int myAnswer = AddNumbers (2, 5);
   print ("My answer is: " + myAnswer);
}


int AddNumbers (int a, int b)
{
   int answer = a + b;
   return answer;
}

#
// Example of a function that does not return anything and handles all the code locally within itself (scope)

void Start()
{
   AddNumbers (2, 5);
}

void AddNumbers (int a, int b)
{
   int answer = a + b;
   print ("The answer is: " + answer);
}
sour fulcrum
#

(if you don't mind Osteel another example for the road)

public class Apple
{ }

public class TestClass
{
    void Start()
    {
        Apple myApple = GetNewApple();
    }

    //This functions's goal is get an apple, so it needs to return a value (an apple)
    Apple GetNewApple()
    {
        return (new Apple());
    }

    //This functions goal is to eat an apple, the goal doesn't neccesitate returning anything because thats not how eating works
    void EatApple(Apple apple)
    {
        //code to eat apple
    }        
}
split plover
#

Alright im gonna go look up what return is and then come back and see if I can understand this

#

Okay i think i get it now

frosty hound
#

Make a simple calculator game

split plover
sour fulcrum
#

ahh i see the confusion now

#

return isn't related to code flow

split plover
#

whats code flow

sour fulcrum
#

think about functions less logically and more like the things you do in life

median hatch
sour fulcrum
#

standing up out of bed, you don't get anything back from that, you just do it

median hatch
#

probably not the best example

#

but you can call functions and set their return into a variable

sour fulcrum
#

finding your car keys, you do get something from that, the car keys, so you return carkeys so you can get that value after finding your carkeys

split plover
sour fulcrum
#

you moved but thats something you did

#

not something you got

split plover
#

Alright yeah no that makes much mmore sense

sour fulcrum
#

if i ask you to find my glasses you would get something back from doing that, the glasses

split plover
sour fulcrum
#

yes

median hatch
#

actually that code is wrong wrote it on phone

sour fulcrum
#

so your function would be finding the glases, then maybe another to give them to me

#

but you need to get the glasses from the findglases function

#

so you return it

median hatch
#
int Number()
    {
        return 2;
    }

    int functionNumber = Number();
sour fulcrum
#

to bring it out of the function

split plover
sour fulcrum
acoustic belfry
#

Hi

I have a question, in theory InTriggerCollision is like a kind of update that only updates when theres something inside the trigger? Or not?

median hatch
split plover
#

Alright i'm honestly really suprised there wasn't a single youtube video explaining this cause this was super confusing before it was explained

median hatch
#

sounds good

frosty hound
acoustic belfry
#

Got it

#

Thanks

sour fulcrum
#

I really like to use a Printer as a example of functions because you put paper in it, the work gets done in the machine (function) and the result comes out of the machine (function)

split plover
#

Are there more unity courses than just the beginner scripting one

median hatch
sour fulcrum
#

anything can happen in the apple machine 😄

median hatch
#

xD

median hatch
#

you'll learn way more than any tutorial

split plover
#

I'll try to just continue working on what i was planning to make originally

#

though idk how ill get multiplayer to work i'll probably just watch a tutorial

median hatch
#

multiplayer?

sour fulcrum
#

i wouldn't do multiplayer

median hatch
#

youre crazy cat boi

split plover
#

its just so i could play it with my friends

median hatch
#

i wouldnt recommend it as your first expierence

split plover
#

its not gonna be any insane stuff infact i'll probably just use lan

median hatch
#

it adds a new layer to everything

#

and its a thick layer

sour fulcrum
#

even then i would recommend doing a little solo thing first

split plover
median hatch
#

just saying because single player games are already crazy enough

median hatch
#

its okay if your goal is multiplayer games

#

but i'd learn unity at least intermediate level first

split plover
#

I dont even think i've learnt unity at a beginner level 👍

median hatch
#

try to make a small project first

#

with everything

split plover
median hatch
#

sounds, game juice and one or two features

split plover
#

not super basic but like

median hatch
#

i promise you'll be way more confident tackling multiplayer after

split plover
#

I think the fact i want to do multiplayer first makes me confident enough but i definitely lack the skill

median hatch
#

so you know my first game was multiplayer

split plover
median hatch
#

gave up when i realized i couldnt sync things dropping on the floor

#

but if you wanna give it a try

split plover
#

Its fine if stuff is a little delayed, my original idea was rblx but i do not wanna do that after i saw how absolutely abysmal the delay is there

median hatch
#

do you know stuff like client side and server side concerns?

split plover
#

yeah

median hatch
#

TCP or UDP protocols?

split plover
#

dunno what those are

#

if they're security stuff i dont need to worry i atleast hope none of mmy friends would try to hack eachother

median hatch
#

its not

#

if its just between your friends security isnt a problem

#

just use peer to peer connection or sth

sour fulcrum
#

They wanna do lan stuff it’s fine

median hatch
#

yea no worries then

#

give it a shot

split plover
#

Now that i think about this, this is a HORRIBLE idea, my internet is complete shit

#

it'll probably work anyways

median hatch
#

it should still work

split plover
#

but yeah i'll listen to your idea though, i'm going to make a basic singleplayer game first

median hatch
#

and if you wanna in the future you can add a co op feature to that basic singleplayer

#

brotato did that

split plover
#

Alright im gonna write this down so i dont forget cause its 8 am and i started trying to learn how to code like 9-10 hours ago so i am really sleeping

oblique gale
#

public class EagleDetector : MonoBehaviour
{
    [SerializeField] private EagleScript _eagleScript; // Reference to the eagle script to notify

    private void OnTriggerEnter(Collider other)
    {
        Debug.Log(other.name);
        if (other.CompareTag(_eagleScript.playerTag))
        {
            Debug.Log("Player in range");
            _eagleScript.OnPlayerDetected(other.gameObject);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag(_eagleScript.playerTag))
        {
            Debug.Log("Player out of range");
            _eagleScript.OnPlayerLost(other.gameObject);
        }
    }
}

I don't understand how does OnTriggerEnter() only detects collider of a charactercontroller and not other types of colliders as well?

polar acorn
oblique gale
#

both have charactercontroller, does it need either charactercontroller or a rigidbody to be detected by a collider?

keen dew
#

You asked about a case when there isn't a CC. What components do the objects have when it doesn't work?

polar dust
#

in order for a collider to "see" that an object has collided with it, that other object needs to be a rigidbody

oblique gale
#

OOOOH so that's why

acoustic belfry
#

Hi, how i can put an animation clip inside a function wich is referenced? i mean the thing inside the ()

oblique gale
#

wait, can an object have both rigidbody and charactercontroller at the same time??

shut swallow
#

is there a way of seeing the boxcast box visually? For some reason my Boxcast isn't returning anything: if (Physics.BoxCast( center: castCenter, halfExtents: vector3HalfExtents, direction: slashDirection, hitInfo: out _meleeHitRegister, orientation: Quaternion.identity, maxDistance: 1.25f, layerMask: attackLayer )) { Debug.Log("Hit confirmed"); if (_meleeHitRegister.transform.TryGetComponent<StandardEnemy>(out StandardEnemy T)) { T.TakeDamage(attackDamage); Debug.Log("Enemy hit confirmed"); } }

#

context: ``` var updirection = motor.CharacterUp;
var slashDirection = castCenter - cameraTarget.position;
var slashDirectionQuaternion = Quaternion.LookRotation(slashDirection, updirection);

eager elm
shut swallow
eager elm
#

probably, ye

shut swallow
#

I've check the sizes before, and they seem to be good

#

only problem that I have is I don't know how to check collision layers

#

I want to exlcude all except one

sour fulcrum
eager elm
#

LayerMask is somewhat tricky to set up, are you getting any hits if you remove it?

clever oar
#

hello, i have very basic question. When the variable with Quaternion data type is defined, what is its default value after definition? null?

shut swallow
sour fulcrum
#

What do you mean by that

shut swallow
#

Layer -> attackLayer

sour fulcrum
#

thats how layers work yeah

shut swallow
#

ah ok

sour fulcrum
#

for most things in Unity that layer is used for both rendering and physics which is a little stupid and dumb and nowadays some things seperate it but

#

thats the goto

shut swallow
#

I've read the OnCollisionEnter API and didn't even understand a speck of it

eager elm
#

you should just have it as a reference and attach it to your gameObject instead of Instantiating it, then before casting make sure the position and rotation is set correctly and use boxCollider.Cast() for getting the data.

hexed terrace
#

Layers is the "normal" layers that have been in forever, just too large to fit expanded

sour fulcrum
#

yee i know nowadays they are trying to split it up

hexed terrace
#

appologies, I totally missed the end of your msg

shut swallow
#

I have multiple melee hits that are detached from the player

#

I can't parent a hitbox and call it a day

eager elm
#

can you add the boxCollider to the projectile / melee hit itself?

shut swallow
#

the projectile is also an instance, so no(?)

                    (
                    vfx_slash,
                    position: castCenter,
                    rotation: slashDirectionQuaternion,

                    );
                Destroy(slashvfxinstance.gameObject, 1);```
#

At least, I'm not aware of any method that will work

charred spoke
#

What do you mean you can just add a collider to your prefab

shut swallow
eager elm
#

Is vfx_slash a gameObject? You should be able to add it to it, or even better make a new class called "Projectile" or something that holds both a reference to the VisualEffect and the collider.

#

after all, it should be the slash itself that handles the hit detection, not the player.

charred spoke
shut swallow
charred spoke
#

If you do not know how to do this stuff I suggest you !learn

naive pawn
#

so you can add colliders to that

eternal falconBOT
#

:teacher: Unity Learn ↗

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

naive pawn
shut swallow
naive pawn
#

no, not at all

#

you've already added the collider to the prefab, no? you're instantiating the prefab twice here

#

Instantiate with a component clones the entire gameobject the component is attached to

shut swallow
#

so even if I instantiate VisualEffect slashvfxinstance it has a collider?

naive pawn
#

yes

polar acorn
polar acorn
#

Then the thing you instantiate will also have a collider

shut swallow
polar acorn
#

If it's solid that's what it's supposed to do

naive pawn
#

if neither are set to trigger and they interact, yes

#

you can just make it a trigger though

shut swallow
#
{
    [SerializeField] private int attackDamage = 1;

    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log("Slash hit!");
        // register hit
        if (collision.collider.TryGetComponent<StandardEnemy>(out StandardEnemy T))
        {
            T.TakeDamage(attackDamage);
            Debug.Log("Enemy hit!");
        }
        Destroy(gameObject);
    }

}``` had this script attached to my prefab, doesn't seem to work
polar acorn
shut swallow
#

ohh

#

either

naive pawn
#

yeah, so use OnTriggerEnter instead

shut swallow
#

nvm

#

yea

split plover
eternal falconBOT
polar acorn
shut swallow
#

if anything large, use a code dump like !code

eternal falconBOT
split plover
#
using UnityEngine;

public class MovementStateManager : MonoBehaviour
{
    public float movementspeed = 3f;
    [HideInInspector] public Vector3 dir;
    float hzInput, vInput;
    CharacterController controller;
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }
    void Update()
    {
        GetDirectionAndMove();
    }
    void GetDirectionAndMove() {
        hzInput = Input.GetAxis("Horizontal");
        vInput = Input.GetAxis("Vertical");

        dir = transform.forward * vInput + transform.right * hzInput;

        controller.Move(dir * movementspeed * Time.deltaTime);
    }
}

I know this is probably stupid but can someone tell me why this is working 😭
followed a tutorial but i have zero idea why it works because none of the movement keys that are moving the character are even in the code. I thought i would just be able to type it out and look at the code to figure it out but i really have no clue