#💻┃code-beginner

1 messages · Page 471 of 1

summer stump
#

Then you may not be helped here
Why you would want to use garbage is beyond me

frosty hound
#

@shrewd hill If you're not using a properly configured IDE, you cannot use this discord.

shrewd hill
#

which one do i use

summer stump
#

The one you ARE using

#

Just finish the guide

frosty hound
#

Visual studio, install it from Unity Hub.

shrewd hill
#

i did

steep rose
#

configure your !ide

eternal falconBOT
summer stump
shrewd hill
#

im using visual studio

summer stump
#

If you can guarantee you completed all three steps of configuration (after installing), then click regenerate project files in external tools while vs is closed

steep rose
#

then configure it

#

click this Visual Studio (Installed manually) in the bot message

#

then scroll down and follow the steps

#

Now that i think of it ive never used these links, idk why my ide came configured (unless i did)

languid snow
#

knowing an objets rotation (quaternion) how can i set its RigidBody2d velocity in that direction?

#

i tried using transform.up and transform.forward but it doesnt really work

#

waittt i might get it working

summer stump
#

Why not use the transform.forward instead of rotation?

#

Ah, there was lag.
Yep, I think that way is good, and it WILL work if that forward is cached in the right spot

languid snow
#

forward is red arrow right?

rich adder
#

in 2d forward is depth

summer stump
#

Blue is forward. Red is right.
You are in 2d

languid snow
#

im stupid 🔥

#

ok thanks

summer stump
#

No. Just learning

languid snow
#

alr it works

#

thank you again

static wasp
#

yo, how do i add a offset to a quaternion

toxic cloak
#

hello is there any way to start a timer and check when the game is paused

toxic cloak
static wasp
#

i have a quaternion and i want to give it a offset

eternal needle
toxic cloak
#

m a beginner i guess i would make a parent of the object and offset the child and rotate the parent instead of the child

static wasp
#

how

eternal needle
static wasp
#

i don't quite understand that

steep rose
#

thats it

toxic cloak
static wasp
#

it worked thx for yall

steep rose
#

dont thank me thank bawsi

#

lmao

eternal needle
eternal needle
steep rose
#

anywho i gotta go now

static wasp
toxic cloak
toxic cloak
eternal needle
summer stump
toxic cloak
#

sorry english is not my main language so i get lost in the docs explanation

summer stump
toxic cloak
summer stump
toxic cloak
#

yes when paused i meant sorry if i interpreted it incorrectly

summer stump
#

No worries. Just added a link to unscaled time

eternal needle
summer stump
#

Oh haha, I thought that was what I linked the first time. Should have looked closer at what I was linking lol

toxic cloak
#

Thank you that what i was looking for

prime cobalt
#

I know you can make raycasts ignore triggers but can you make raycasts ignore non triggers?

eternal needle
prime cobalt
slender nymph
#

set itself to another layer for the duration of the raycast

eternal needle
#

You could even use something like RaycastAll or try to start the ray so it wont hit the current object

#

Is this in 2d?

prime cobalt
#

Nah 3d

eternal needle
# prime cobalt Nah 3d

Then you're raycast shouldnt really be hitting the object it's starting inside in the first place

austere hazel
#

Also I have my own question, I was following a guide for flappy bird and I am supposed to add a script to a button, but I can't pick a function when I do.

#

The guides component

austere hazel
#

but this is what mine looks like

slender nymph
#

your inspector is in debug mode

austere hazel
#

oh, how do I unclick that, I must've done it a while ago

#

nvm

#

i figured it out, I was wondering why I couldn't do other stuff like the anchor

#

thanks

#

must also be why my fonts aren't working but ill figure that out

marble hemlock
#

quick question
this is the first time I've written that bit underlined

this isnt really a "something is wrong" question, but to clarify i dont have to declare the variable beyond this?

slender nymph
#

that is declaring the variable

marble hemlock
#

and the variable represents whatever its hitting?

slender nymph
#

no, it "represents" the NPCInteract component that TryGetComponent will attempt to find on the collider that was detected with the raycast

marble hemlock
#

ah

#

i dont have to use a variable in this situation then right?

#

i could simply just say the component name

teal viper
#

It is a variable

#

You're already using a variable there

slender nymph
marble hemlock
#

i think im a little confused hold on

#

OH

#

okay so its like when i declare a variable like public GameObject blah;
except in this case, the type is NPCInteract

#

or am i going the wrong way with this

slender nymph
#

yes, a variable of type NPCInteract. but it is a local variable rather than a field

marble hemlock
#

okay thank you

waxen adder
#

How do I create a custom path for a NavMeshAgent given some Vector3s without using something like SetDestination?

slender nymph
#

create an object of type NavMeshPath and pass it to SetPath() on the agent

teal viper
waxen adder
marble hemlock
#

time to figure out dialogue boxes notlikethis

slender nymph
marble hemlock
#

i vaguely remember starting that at some point and then getting irritated
i think it needed to be coded in a way where it would keep going through an array and selecting new dialogue choices every time they click

#

it wasnt irritating because it didnt work, but because i didnt fully understand what i was doing

waxen adder
# slender nymph ah yeah, you're right looks like that is only created internally. but also why d...

That's fair. Reason for using navmeshes is that I like the path calculation logic for the most part of navmeshes. Just had to translate down the corners it has into a list of appropriate grid points and get rid of any redundant points. I do have a list of grid points to work with, so like you said I can just move the object along the points instead of relying on the agent for movement at this point.

slender nymph
waxen adder
#

Oh! Right! Would I still need the surface/obstacles?

slender nymph
#

yes, that is all still used to create the navmesh

waxen adder
#

Nice, but I can do away with the agent component. One less thing to worry about

fathom bramble
#

what in the unity voodoo magic is going on here

#

this is so weird, it only happens on windows builds, on webgl builds I upload to itch.io it doesn't

#

when the player plays again, the next time the game says gameover, it's like it's doing it twice

slender nymph
#

show relevant code

fathom bramble
#

can coroutines cause this?

modest dust
#

You most likely have two coroutines running

slender nymph
#

at a guess i'd say you're starting the coroutines twice. also that is one of the worse ways to reveal text over time. if you're using TextMeshPro objects just assign the text property all at once then modify its maxVisibleCharacters property over time

fathom bramble
#

Hmm okay. Is there anyway to stop the coroutines?

#

like maybe within the OnDestroy

#

method

slender nymph
#

but also just address what is causing it to start more than once

modest dust
#

Save your coroutine in a Coroutine variable and stop that to make sure only one is running at a time

fathom bramble
#

when the game restarts

#

I checked

#

the object does destroy

slender nymph
#

what calls this method

fathom bramble
#

and the methods do unsubscribe

slender nymph
#

ah so it's an event. then most likely it is multiple subscriptions

fathom bramble
#

a subscription calls it

#

but the subscription is lost when the game is over

#

Oh

#

wait

#

I see the issue

#

is it calling the coroutine when unsubbing

#

LOL

#

going to test if that's the issue

hollow lance
#

hi peeps.... so umm... im following this tutorial... https://www.youtube.com/watch?v=BccG8MSb9OU and uh, i was wondering,,. when they got to the camera part, how'd they tie camera movement to the player? i mean like, forward being where the camera(player) is facing

In this video, we start our FPS game development series in Unity by focusing on essential character mechanics. In this part you'll learn how to create smooth character movement, jumping and sprinting abilities, how to implement dynamic footstep sounds for different terrains, and add an immersive camera shake effect.

---------------------------...

▶ Play video
slender nymph
#

follow the instructions in the camera section to find out

hollow lance
#

i did

#

their camera code didnt even work at first, it was missing a code snippet i got from the comment section

#

it also mentions how movement is seperate from cam orientation, which is what i wanna fix

#

maybe its missing a code snippet that rotates the player along with the camera?

slender nymph
#

if you need help with your setup then you need to show how you've got everything set up and the relevant code. i doubt anyone wants to watch an entire tutorial just to see what you copied from (and may not even necessarily have 100% of)

hollow lance
#

oh sorry, lemme send the code here

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine; 

public class PlayerController : MonoBehaviour
{
    [Header("References")]
    private CharacterController controller;
    [SerializeField] private CinemachineVirtualCamera virtualCamera;


    [Header("Movement Settings")]
    [SerializeField] private float moveSpeed = 5f;

    private float xRotation;

    [Header("Input")]
    [SerializeField] private float mouseSensitivity;
    private float moveInput;
    private float turnInput;
    private float mouseX;
    private float mouseY;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    private void Update()
    {
        InputManagement();
        Movement();
    }

    private void Movement()
    {
        GroundMovement();
        Turn();
    }

    private void GroundMovement()
    {
        Vector3 move = new Vector3(turnInput, 0, moveInput);

        move.y = 0;

        move *= moveSpeed;

        controller.Move(move * Time.deltaTime);
    }

    private void Turn()
    {
        mouseX *= mouseSensitivity * Time.deltaTime;
        mouseY *= mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;

        xRotation = Mathf.Clamp(xRotation, -90, 90);

        virtualCamera.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);

        transform.Rotate(Vector3.up * mouseX);    
    }

    private void InputManagement()
    {
        moveInput = Input.GetAxis("Vertical");
        turnInput = Input.GetAxis("Horizontal");
        mouseX = Input.GetAxis("Mouse X");
        mouseY = Input.GetAxis("Mouse Y");
    }    
}
#

*mouse sens is placeholder value for now

slender nymph
#

mouseSensitivity * Time.deltaTime; well that's wrong. mouse input is already framerate independent so multiplying it by deltaTime just ends up with stuttery controls that are dependent on the framerate.
seems like this is a pretty flawed tutorial overall, you may want to consider finding one without so many mistakes

hollow lance
#

perhaps

#

do you have any suggestions?

slender nymph
#

i do not keep a list of tutorials because i don't use them myself

hollow lance
#

fair

#

not even recommended channels?

slender nymph
#

my recommendation for learning how to use unity is to follow the pathways on the unity !learn site to learn how to use the engine at a fundamental level then read the documentation for further information

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hollow lance
#

fair. thanks!

fathom bramble
#

@slender nymph Okay I found out the issue, alot of my subscribers were not unsubscribing when the game was over. I don't know which one caused the issue exactly but making them all unsubscribe fixed it

#

I'll look at your suggestion on how to better animate the text though

#

thanks for the help!

thorny junco
#

I just tried spawn object like this but ıt's not working 😦

languid spire
#

maybe put your switch INSIDE the for loop ?

#

also never check a float for equality

thorny junco
#

It's in 😦

wintry quarry
thorny junco
wintry quarry
#

Also yeah

#

That timer

#

Will never equal 5

#

So that doesn't make any sense either

languid spire
thorny junco
#

wha 😭

wooden minnow
#

private int notPlayerLayerMask = ~(1 << 23 << 24 << 25 << 26 << 27 << 28); this will collide with anything that isnt in the 23rd-28th layers right?

eternal needle
wooden minnow
eternal needle
wooden minnow
#

ok ty

formal sable
cosmic edge
#

hello anyone can help me my code doesnt work

fossil drum
# cosmic edge

Setup your !ide, there is a bunch of thing's named incorrectly.
Setting up your IDE will help you a lot.

eternal falconBOT
cosmic edge
ripe shard
#

pick one

cosmic edge
#

i already have visual code

#

o its not for install

#

its guide

cosmic edge
#

do i need to install sdk?

fossil drum
cosmic edge
#

you mean the color?

#

but i did all the thing

fossil drum
cosmic edge
#

i just restarted now

fossil drum
#

Once half your code is red underlined, you know it works.

cosmic edge
#

it make me an error

#

it talk about sdk

#

idk why

teal viper
cosmic edge
#

.net thing is installed

teal viper
#

How did you install it?

cosmic edge
#

i just writed on google sdk i installed i use the .exe thing and installed sdk and i restarted vs studio

cosmic edge
#

no

languid spire
#

do it

cosmic edge
#

ok

cosmic edge
teal viper
cosmic edge
#

ok

#

i dont have the error

#

but i dont know if it gonna work im gonna try

#

i have new error

#

failed to restore solution
c#dev kit

#

and now my program have error

languid spire
#

that is absolutely correct

cosmic edge
#

so why i have error if it dont have error?

languid spire
#

you do have errors, look at the difference between line 11 and line 14

#

you need to learn to read error messages, they do not lie

cosmic edge
#

yes but they say me Getcomponant does not exist but it exist

languid spire
#

not it does not, look how you spelt it

cosmic edge
#

o yes thx im not english so i didnt see it

#

i found the second error too

#

and now only the last

#

done thank you

#

i corrected all the thinh

#

thing

languid spire
#

hopefully now the ide will help you not to make such simple errors

cosmic edge
#

yes im new to unity so i wasnt understand the thing with code

cosmic edge
#

in the video it make the character move

#

and me it dont work

languid spire
#

so post the !code and DO NOT post a photo of the code

eternal falconBOT
cosmic edge
#

ok

#

but it gonna be long i have discord on phone

languid spire
cosmic edge
#
{
public float moveSpeed;

public float jumpForce;

private Rigidbody2D rb2d;

void Start()
 {   
           rb2d = GetComponent<RigidBody2D>();
}


void Update()
{
    float MoveInput = Input.GetAxisisRaw("Horizontal");
    transform.position += new Vector3 (Moveinput,0,0) * moveSpeed * Time.deltaTime;


    if (Input.GetKeyDown(KeyCode.Space) && Mathf.Abs(rb2d.velocity.y) < 0.001f)

{
      rb2d.AddForce(new Vector2 (0, jumpForce), ForceMode2D.Impulse);
}

}






}


#

@languid spire

#

i dont have discord on my pc

#

no need help i fixed it

lethal meadow
#

ive been doing unity for like 6 days now and this is my 4th project

#

maybe 5th i forgor

#

idk what to do with it

#

i did what i wanted to

#

what could i do/try

grand badger
#

ship it!

lethal meadow
grand badger
#

make a full game and sell it

lethal meadow
#

💀

#

nobodys paying for that shit

#

im new not stupid

grand badger
#

yeah :p actually selling it might be overambitious, but ship it is viable -- you could make a portfolio project

lethal meadow
#

eh idk

grand badger
#

join a game jam with a team and learn together with others (and FROM others)

#

or challenge your solo skills if you're feeling confident for some reason 😆

grand badger
lethal meadow
#

alr

#

any game jam works?

#

or would i need a unity centered one

#

might try make a mobile game but idk how

#

just because it would be kinda cool to have my own app on my phone

grand badger
#

my biggest motivation when I was starting to code was to pimp my QOL up

#

be it phone apps or PC apps, or even games to play

lethal meadow
#

i just play siege 💀

scenic saffron
#

why is my effect not facing the normal vector of the hit object?

lethal meadow
#

i dont need any of this i do it because im bored

indigo hull
#

This is probably a simple question, but on linux (Ubuntu) what is a good IDE or editor for C#?

lethal meadow
grand badger
#

@indigo hull bingalicious is right

#

for C# both VSCode and Rider are great

#

but Unity for Linux is just terrible

sage abyss
#

Hey, why when I use StopCoroutine while WaitForSeconds is processing, it will still invoke the event after the settled time?

lethal meadow
#

windows is fine

#

you can get activation keys for like 2 pounds

grand badger
#

linux is great, windows is horrible

lethal meadow
#

how so

grand badger
#

I mean.. your PC can close because windows wants to auto-update

lethal meadow
#

ive genuinely never had that happen to me

grand badger
#

shitton of vulnerabilities and bugs

lethal meadow
#

idk maybe im simple but the only bug ive noticed was when my taskbar completely stopped working

#

along with other basic fundemental things

#

happened like twice though

grand badger
#

not to mention I can't be sure my key presses and mouse movements aren't being logged to help improve Microsoft Services

lethal meadow
#

yeah i dont see how that would help them

#

but its still the best overall

grand badger
#

oh but it's kinda toggled on by default anyway

lethal meadow
#

ive never used linux but isnt it incompatable with a lot of things

grand badger
#

it is, yeah -- highly because of compatibility

lethal meadow
#

i know the siege anti cheat doesnt work with linux

#

not that it works anyway

indigo hull
#

It isn't a money thing. I can install windows on this today if I wanted to.

#

I just have Linux on this laptop ATM.

steep rose
#

Actually linux itself isn't highly incompatible when it comes to gaming, when proton came out all a developer had to do was incorporate it into their game. But big companies dont want to do that for some reason

#

Well incorporate it into their anti cheat system

scenic saffron
#

how do i wait before calling a function

steep rose
#

Corountines

#

Search them up in docs

willow scroll
scenic saffron
#

i tryed but im stopid

willow scroll
# scenic saffron i tryed but im stopid
public void Invoke(float delay, Action action)
{
    StartCoroutine(InvokeCoroutine());

    IEnumerator InvokeCoroutine()
    {
        yield return new WaitForSeconds(delay);

        action?.Invoke();
    }
}
scenic saffron
#

ok

willow scroll
#

You can also make it a static extension method, which will require a MonoBehaviour as a parameter

steep rose
#

I would recommend looking it up on docs to learn

scenic saffron
#

ok

willow scroll
#
public static void Invoke(MonoBehaviour source, float delay, Action action)
{
    source.StartCoroutine(InvokeCoroutine());

    IEnumerator InvokeCoroutine()
    {
        yield return new WaitForSeconds(delay);

        action?.Invoke();
    }
}
steep rose
#

Not sure if they need all of that

#

For a simple wait

willow scroll
steep rose
#

Yes, they are simple but effective.

willow scroll
#

You can use this instead of creating an additional Coroutine for every method, which has to be delayed once

#

Also, I am a type of person to do extensions and assistance methods for everything

steep rose
#

While yes its is far more useful I'm not sure a beginner would know what it is and how to use it. But I can agree with you that it's way better to have something like that then make a new one every time 😅

#

I might use that myself

willow scroll
steep rose
#

True, I might need to check into extension methods 😅

They look really useful

steep rose
#

I can stick with corountines lmao

#

Although it would be good dive into their source code and how they work so anyone can make one

willow scroll
#

I don't think it's available

steep rose
#

Hey at least I see no cpp in there

willow scroll
#

They probably do use it

iron blade
#

        const float skinWidth = 0.015f;
        Vector3 capsulePosition = transform.position;
        float pawnHalfHeight, pawnRadius;
        pawnHalfHeight = (collider.height / 2) - collider.radius;
        pawnRadius = collider.radius;

        Vector3 capsuleTop = capsulePosition + new Vector3(0, pawnHalfHeight, 0);
        Vector3 capsuleBottom = capsulePosition - new Vector3(0, pawnHalfHeight, 0);

        Collider[] collisions = Physics.OverlapCapsule(capsuleTop, capsuleBottom, pawnRadius, canCollideWith);
        if(collisions.Length > 0)
        {
            Debug.Log("StartPenetrating");
            OutHit.bStartPenetrating = true;
            return true;
        }
        
        if (bSweep)
        {
            if (Physics.CapsuleCast(capsuleTop, capsuleBottom, pawnRadius - skinWidth, Delta.normalized,
                    out RaycastHit hit, Delta.magnitude + skinWidth))
            {
                if (hit.distance <= skinWidth)
                {
                    return false;
                }

                OutHit.bBlockingHit = true;
                OutHit.hit = hit;
                transform.Translate(Delta.normalized*(hit.distance - skinWidth));
                return true;
            }
        }

anyone know why after

transform.Translate(Delta.normalized*(hit.distance - skinWidth));
        Collider[] collisions = Physics.OverlapCapsule(capsuleTop, capsuleBottom, pawnRadius, canCollideWith);
        if(collisions.Length > 0)
        {
            Debug.Log("StartPenetrating");
            OutHit.bStartPenetrating = true;
            return true;
        }

returns true

#

could it be floating point issues?

deft grail
iron blade
#

so im trying to create a kinematic character controller

 const float skinWidth = 0.015f;
 if (Physics.CapsuleCast(capsuleTop, capsuleBottom, pawnRadius - skinWidth, Delta.normalized,
                    out RaycastHit hit, Delta.magnitude + skinWidth))
            {
                if (hit.distance <= skinWidth)
                {
                    return false;
                }

                OutHit.bBlockingHit = true;
                OutHit.hit = hit;
                transform.Translate(Delta.normalized*(hit.distance - skinWidth));
                return true;
            }

this checks for if i can fully move through vector Delta without colliding into something, ie a wall

if im not wrong this should put my character right up against the wall

but for some reason on the next frame

     Collider[] collisions = Physics.OverlapCapsule(capsuleTop, capsuleBottom, pawnRadius, canCollideWith);
        if(collisions.Length > 0)
        {
            Debug.Log("StartPenetrating");
            OutHit.bStartPenetrating = true;
            return true;
        }

this returns true, which means my character is inside something

teal viper
iron blade
#

its colliding with a wall

#

the highlighted wall

teal viper
#

Log it. What's the point of that debug log about starting penetration then? It would be much more informative to log the colliding objects in there

iron blade
#

but its not supposed to collide with it

teal viper
#

Great. Keep your logs informative.

#

Debug the hit distance.

teal viper
iron blade
#

and

#

suddenly

#

it stopped colliding

#

i changed literally nothing in the code

teal viper
#

Stopped colliding? You mean went through the wall?

#

Clipped through it?

iron blade
#

hit.distance seems to be correct in stopping at 0.015f

#

maybe its the overlap capsule

teal viper
iron blade
teal viper
#

Also, that value is not less than your skinWidth.

teal viper
iron blade
#
        const float skinWidth = 0.015f;
        Vector3 capsulePosition = transform.position;
        float pawnHalfHeight, pawnRadius;
        pawnHalfHeight = (collider.height / 2) - collider.radius;
        pawnRadius = collider.radius;

        Vector3 capsuleTop = capsulePosition + new Vector3(0, pawnHalfHeight, 0);
        Vector3 capsuleBottom = capsulePosition - new Vector3(0, pawnHalfHeight, 0);

        
        Collider[] collisions = Physics.OverlapCapsule(capsuleTop, capsuleBottom, pawnRadius, canCollideWith);
        if(collisions.Length > 0)
        {
            Debug.Log("StartPenetrating");
            Debug.Log(collisions[0].name);
            OutHit.bStartPenetrating = true;
            Debug.Break();
            return true;
        }
        
        if (bSweep)
        {
            Debug.DrawLine(capsuleTop, capsuleTop + new Vector3(0,pawnRadius,0), Color.magenta);
            float dist = Delta.magnitude + skinWidth;
            Debug.DrawLine(transform.position, transform.position+ Delta.normalized);
            if (Physics.CapsuleCast(capsuleTop, capsuleBottom, pawnRadius - skinWidth, Delta.normalized,
                    out RaycastHit hit, dist, canCollideWith))
            {
                Debug.Log(hit.distance);
                if (hit.distance <= skinWidth)
                {
                    Debug.Break();
                    return false;
                }
                OutHit.bBlockingHit = true;
                OutHit.hit = hit;
                transform.Translate(Delta.normalized * (hit.distance - skinWidth), Space.World);
                return true;
            }

            OutHit.bBlockingHit = false;
            transform.Translate(Delta.normalized * Delta.magnitude, Space.World);
            return true;
        }
teal viper
#

So, according to the value that you get, there seems to be no problem.

#

What's the issue?

iron blade
#

when i re-enable

        Collider[] collisions = Physics.OverlapCapsule(capsuleTop, capsuleBottom, pawnRadius, canCollideWith);
        if(collisions.Length > 0)
        {
            Debug.Log("StartPenetrating");
            Debug.Log(collisions[0].name);
            OutHit.bStartPenetrating = true;
            Debug.Break();
            return true;
        }

it says that its penetrating

teal viper
#

Does the hit distance print less than skinWidth before that happens?

iron blade
#

no

teal viper
#

Shouldn't you be adding that instead?

#

Or at least not subtracting.

iron blade
#

i wanted to start the capsulecast inside the collider

#

maybe i swap it around

teal viper
#

Isn't that argument corresponding to the radius of the cast capsule? In this case I don't see how it's related to where it starts.

iron blade
#

https://www.youtube.com/watch?v=YR6Q7dUz2uk&t=433s
im following this tutorial and he says he starts the collision check inside the collider to avoid clipping through things due to floating point inaccuracies

How to make actually decent collision for your custom character controller. Hopefully you find this helpful and people will finally stop saying "jUsT uSe DyNaMiC rIgIdBoDy!!!1!!11!!"

Chapters:
00:00 - Intro
01:09 - Algorithm
05:11 - Implementation

Improved Collision detection and Response (Fauerby Paper):
https://www.peroxide.dk/papers/collisi...

▶ Play video
teal viper
#

The radius of the capsule is unrelated to where the cast starts.

#

Anyways, I'm off to sleep.

iron blade
#

what i meant by that is that the cast size is slightly smaller than the collider

queen adder
#

Heyo, I've been trying to create a simple mechanic of stepping into a trigger and being pushed away, like this one: https://youtu.be/Z4Heqe0AKD4?t=99
I've tried a couple different things from looking around online but none seem to work, I'm using this little bit of code: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerStay.html
as well as the unity provided third person player controller package. I've put rigid bodies on the box collider and the player and it doesn't seem to be triggering, any suggestions?

foggy yoke
#

I got this error when trying to make a Raycast2D: Argument type 'UnityEngine.Ray2D' is not assignable to parameter type 'UnityEngine.Vector2'
This is my code for the Raycast:

if (Physics2D.Raycast(ray, out hit))
        {
            Debug.Log("Something was hit!");
        }```
My ray: `ray = new Ray2D(player.position, Input.mousePosition);`
#

I work in 6000.0.1f1

foggy yoke
#

And now this error: Argument is 'out' while parameter is declared as 'value'

#

im really doing something wrong here

static wasp
#

is there a way to have 2 OnCollisionEnters in different script

cosmic dagger
#

no . . .

#

what are you trying to do?

static wasp
#

i want an OnCollisionEnter in the player script, and another one in the bullet collision script

cosmic dagger
#

yes, you can do that. each script is its own . . .

static wasp
#

when i do that, it tells me

Script error: OnCollisionEnter
This message parameter has to be of type: Collision
The message will be ignored.

cosmic dagger
#

sorry, i thought you meant 2 different OnCollisionEnter methods in one script . . .

cosmic dagger
#

collision and trigger methods have a parameter . . .

static wasp
#

well it is type collision

cosmic dagger
#

show code. no way for us to see . . .

static wasp
#

ok, one sec

#

this is in the player script

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            is_jumping = false;
        }
    }

and this is in the bullet collision script

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Bullet" && collision.gameObject != gameObject)
        {
            Destroy(collision.gameObject);
        }
    }
polar acorn
#

Do you have a script named Collision

cosmic dagger
#

do you have a script name Collision?

static wasp
#

yes

#

oh

#

is it because of that

polar acorn
#

You should probably not ever have classes with the same name as Unity classes unless you want to fully qualify every type name which is just annoying to write and read

#

so you should just not do that

cosmic dagger
# static wasp yes

you have the same class, Collision as the UnityEngine.Collision class. it will use your class instead because it's within your projects namespace . . .

static wasp
#

ok, i changed it to bullet_collision

#

lemme check if it works

foggy yoke
#

I got this error: Assets\Scripts\PlayerShooting.cs(18,52): error CS1615: Argument 2 may not be passed with the 'out' keyword I dunno what it means

deft grail
verbal dome
#

Show code

cosmic dagger
verbal dome
#

Oh its the raycast

foggy yoke
#

okay nvm, i realised

lethal meadow
#

idk what to do

#

i have guns

#

and a flashbang

deft grail
static wasp
#

thx

summer stump
wild cargo
#

I am trying to randomly generate items from a list of objects. I want some variance between some of the object variables, so after it is copied from a list, I alter some properties. The problem is, whenever i generate a duplicate object, it is overwriting the previous alterations and I don't understand why.

in as simple terms as I can explain, in the following scenario:
randomObjectA = objectA
randomObjectA.RandomlyAdjustVariables();

randomObjectB = objectA;
randomObjectB.RandomlyAdjustVariables();

randomObjectA gets overwritten to what randomObjectB changed. I want them to stay different.

I can show code if needed

verbal dome
#

So you want a copy instead of modifying the original?

wild cargo
#

yes

cosmic dagger
verbal dome
#

I assume that the object is a class (not a struct) then. Classes are reference types, if you want a copy then use a struct, or manually copy the values to a new instance of that class

maiden chasm
#

How to male good water

verbal dome
maiden chasm
#

With animation an code

cosmic dagger
# wild cargo yes

you need to create a new instance of objectA and assign that to each random object . . .

verbal dome
maiden chasm
#

And another questions is who to make an mg for a plane game with prefabs

#

My Gun is so buggx

verbal dome
#

Machine gun?

tawdry quest
#

How do i check if an android device is connected to the internet and then check if its connected via Wifi or via Mobile Carrier ?

maiden chasm
#

Yed

#

Yes

verbal dome
maiden chasm
#

The gun spawns in my plane

#

Sorry I must be go off

#

I haven't time

tawdry quest
#

To check if internet its recommending pinging a website, since the internal option only checks if were connected to a network, not actually online

#

and there doesnt seem to be any way to check if wifi or LTE

wild cargo
rancid tinsel
#

hey guys im experimenting with fixed joint 2d and im trying to set up an attachable barrel, but when the run rotates the barrel kind of.. wiggles? any idea what might be causing that

#

this is how im rotating the gun

#

oh wait i actually stumbled on a fix i think

#

made the barrel a child of the gun

verbal dome
#

When dealing with rigidbodies, you should not use transform

rancid tinsel
#

so now the script affects both of them

rancid tinsel
#

i want to make a game where you can build your weapon out of parts at runtime, do you know of a better way of attaching objects in 2d?

verbal dome
#

Child/parent is probably the simplest way

rancid tinsel
#

actually thinking about it now youre probably right

#

since ill have to manually assign the position anyway i think

verbal dome
#

You could have some script on each part that store "sockets" and "plugs" for attaching

rancid tinsel
#

especially since the plan is for the player to be able to build wacky/op weapons with lots of parts

verbal dome
#

Each of those plugs/sockets could have a local position, angle, and probably some ID/tags for checking if an attachment is valid

hasty pine
#

heya, I am relatively new to unity but have developed games in other engines.
Right now I use scriptable objects to spawn "enemies", each enemy has its own health and the damage it is supposed to do

what would be the best practice to store immutable data? Like base damage, base health of a particular enemy

polar acorn
#

You'd make a ScriptableObject file in your project with the base stats and attach that to a MonoBehaviour that initializes its data from the SO (but doesn't change it) and tracks its own individual health and stats

hasty pine
#

Ohh i see, i can have both immutable and mutable data in the same i believe?

#

Like currenthealth and base health

#

or you mean something else?

deft grail
hasty pine
#

ohh that makes sense

eternal needle
hasty pine
#

alright thanks

hasty pine
#
using UnityEngine;


public class CharacterHealth : ScriptableObject
{
    public int baseHealth; 
}
using UnityEngine;

public class HealthManager : MonoBehaviour
{
    public CharacterHealth characterHealth;
    private int currentHealth;

    void Start()
    {

        currentHealth = characterHealth.baseHealth;
    }

    public void TakeDamage(int amount)
    {
        currentHealth -= amount;
        if (currentHealth < 0)
            currentHealth = 0;
    }

    public void Heal(int amount)
    {
        currentHealth += amount;
        if (currentHealth > characterHealth.baseHealth)
            currentHealth = characterHealth.baseHealth; 
    }

    public int GetCurrentHealth()
    {
        return currentHealth;
    }

}```
#

something like this i believe

deft grail
#

so just a int baseHealth; baseHealth = characterHealth.baseHealth;

abstract copper
frank delta
#
                    void PlayerLook()
        {
            //this get direction of mouse from center of screen(can be visualized by the white line below the character feet)
            direction = (new Vector2(Input.mousePosition.x, Input.mousePosition.y) - new Vector2(Screen.width / 2f, Screen.height / 2f)).normalized;
            //this get the angle between the red block(forward) to the targeted direction vector
            float deltaAngle = Vector3.SignedAngle(transform.forward, transform.position + new Vector3(direction.x, 0, direction.y), Vector3.up);
            //^^^ the above works correctly, vvv whichever under is not for some reason

            //intended to just snap the rotation and stop completely to avoid overshooting
            if(Mathf.Abs(deltaAngle) < (_rotSpeed * 1.1f))
            {
                //snapping
                transform.LookAt((transform.position + new Vector3(direction.x, 0, direction.y)));
                return;
            }
            //turning L, R respectively
            if(deltaAngle < 0)
            {
                transform.Rotate(0, -_rotSpeed, 0);
                return;
            }
            if (deltaAngle > 0)
            {
                transform.Rotate(0, +_rotSpeed, 0);
                return;
            }
        }

How is it once I move, this codes just break

verbal dome
# hasty pine alright

IMO both ways are fine, just different "overhead"
Storing the value on the class directly takes more memory
Vs the overhead of accessing the value via the SO

#

Both are very small in this case

#

SO is often used so that you dont need to store the same values in each instance of your class but shared in the SO instead

steep rose
#

i would recommend taking a look at the line that the error says there a problem

abstract copper
#

I mean it says its trying to access something deleted but idk what else then spawn area

#

And spawn area is not being deleted

#

destroyed if u will

#

I think I found out

#

I didn't know that object are still in the list as null

limber grail
#

So i have a Main Menu that i want to load when i start the game in unity. One idea of me was to have it shown at the beginning and then to turn it off via script. But when i want to restart the Level i get it again because i just reload the Scene from the beginning but if i put in the line to make the Main menu invisible it does not work and stays visible. The OnClick() function is the restart.

willow scroll
rich adder
wooden slate
#

guys, can i animate object without animator, like i want to have only idle animation . can i do it without creating everytime new animation controller?

bold nova
#

Im trying to change scenes in unity. I do with with SceneManager.LoadScene(.., LoadMode.Single). But something strange happens. It seems like the game goes through only one game loop (meaning that only start and one update method call) that nothing happens. No changes, no method calls. But when I load scene from scene folder directly, everything works. I don't use any scripts that I don't destroy onLoad. What might be the problem?

static wasp
#

guys, do collisions just not work for planes, it works with a cube, but not a plane

verbal dome
#

The unity plane mesh is one-sided

static wasp
#

i used a box collider tho

verbal dome
#

What do you mean with "plane" then

#

I thought you mean the default unity plane mesh

static wasp
#

the floor here

verbal dome
#

First, try giving it some thickness (size y) so it's not nearly zero

static wasp
verbal dome
#

Or make the box way thicker and move it downwards

static wasp
#

it's not a box tho

#

it's a plane

verbal dome
#

Box collider.

static wasp
#

still doesn't work

short hazel
#

Make sure you're moving the object that's supposed to collide with the plane in a physics-friendly way

#

Using the Rigidbody

static wasp
#

wdym by physics-friendly way

short hazel
#

If you teleport it around by changing its transform.position, it won't work, changing the position ignores physics!

static wasp
#

i'm using this way to move it

transform.position += bullet_direction * bullet_speed * Time.deltaTime;
short hazel
#

Yep that's why

static wasp
#

then why does it work on a cube

short hazel
#

Because the cube is big enough for the physics engine to catch that both colliders intersect

static wasp
#

oh ok

#

so should i use transform.Translate?

short hazel
#

If your bullet is small enough, on one frame it'll be above the plane, and on the next frame it'll be below
No Transform manipulations at all, use a Rigidbody

limber grail
# willow scroll I've read it 4 times, but I still don't get it fully

I have a Main Menu UI that i want to show when starting the Game and when pressin on the Menu butten in a Game Over screen. The Problem is that if i don't hide it, it will show again when i reset the level with a Restart Button. I tried just writing it to be unactive via .SetActive(false). But it didn't work and still showed. And i was looking for a solution for that. I hope this explains it better.

static wasp
short hazel
#

Mass can be set to nearly zero, and gravity can be disabled per-Rigidbody

static wasp
steep rose
#

it uses physics

static wasp
#

ok, thanks

short hazel
#

It uses the physics engine, which has a prediction system built in, so it can detect collisions that are about to happen

limber grail
rich adder
#

bool is probably not even necessary but you should probably make the object a singleton if you plan on reloading the same scene you put DDOL in or it just keeps creating new DDOL on each reload

limber grail
#

ok thanks for the help will do

real heart
#

So I have updated all 3 files to work with Vector3 but the generation still works the same, the chunks do not vertically connect with eachother.

I'll link all 3 updated scripts here for brevity: Chunk.cs and NoiseGenerator.cs and ChunkManager.cs @frosty hound

Also it becomes very slow now, like after some point it starts getting very laggy.

weak cedar
#

You could make it so that only the chunks in the cameras pov load

frosty hound
real heart
#

I do have a view distance slider, I suppose I can turn that down to 1

summer stump
real heart
real heart
weak cedar
#

I think unity has a built in one, but if not, just not render the chunks behind you

#

It had a specific name I forgot whats it called

real heart
#

For now I'm suprised it's this fast.

weak cedar
#

There are also many resources regarding performance issues about voxel games made with unity

#

Voxel games use chunk system as well (like minecraft)

slender nymph
real heart
weak cedar
slender nymph
#

but if you are experiencing performance issues you need to use the profiler to determine where those issues may be coming from

real heart
#

I see, thank you very much. Well it's currently smooth cause I've dropped the view distance to 2. It's the most I can go cause if I drop it to 1 it only generates other chunks if I start moving around 😁

#

@verbal dome So this is how it works now after I have updated the code, the chunks are no longer connected properly even horizontally, and vertically they are still separated from eachother.

verbal dome
#

Something wrong about the noise coordinates still. Looks like chunks on the same Y level are identical to each other

carmine narwhal
#
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class BallMoveMent : MonoBehaviour
{
    private Rigidbody2D rb;
    public float startSpeed = 100f;
    public float speedIncrease = 1f;
    private Vector2 currentSpeed;
    private int collisionCount;
    private float bouncOffset = 0.1f;
    private float minX = -0.5f;
    private float minY = -1f;
    private int maxX = 1;
    private int maxY = -1;   

    
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        StartMoveMent();
    }

    private void StartMoveMent() 
    {
       
        float x = Random.Range(minX, maxX);
        float y = Random.Range(minY, maxY);
       
        Vector2 direction = new Vector2(x,y).normalized;
        rb.velocity = direction * startSpeed * Time.deltaTime;
         // got a tip on discord to negate the velocity but i dont know where he ment i was supose to do it. it does not work here.
        Debug.Log(direction);
        currentSpeed = direction * startSpeed;
       

    }
    public void OnCollisionEnter2D(Collision2D collision)
    {
       
        
        collisionCount++;
        if(collisionCount % 5 == 0) 
        {
           // is this the right way to negate velocity? cause it does not work anywhere rb.velocity = -rb.velocity;
            rb.velocity *= speedIncrease * bouncOffset;
        }
       
      

    }
}
``` Help im confused.
verbal dome
#

@real heart Show your current scripts including the NoiseGenerator (especially GetNoise)

verbal dome
#

So the coordinate that you changed from Vec2 to Vec3 seems to drip all the way down to GenerateNoiseLayer, where it is passed into the compute shader:cs NoiseShader.SetVector("_NoiseOffset", globalOffset);
I suppose that the compute shader is still expecting a Vector2, not Vector3. You'd have to make it work with Vec3 (float3 in shader)

real heart
#
//Assets/Scripts/Compute/Includes/MetricsCompute.compute
static const uint numThreads = 8;

int _ChunkSize;
int _Scale;

int indexFromCoord(int x, int y, int z)
{
    return x + _ChunkSize * (y + _ChunkSize * z);
}
static const uint numThreads = 8;

int _ChunkSize;
int _Scale;

int indexFromCoord(int x, int y, int z)
{
    return x + _ChunkSize * (y + _ChunkSize * z);
}
// Assets/Scripts/GridMetrics.cs

public static class GridMetrics
{
    public const int NumThreads = 8;

    public const int Scale = 32;

    public const int GroundLevel = Scale / 2;

    public static int[] LODs = {
        8,
        16,
        24,
        32,
        40
    };


    public static int LastLod = LODs.Length - 1;

    public static int PointsPerChunk(int lod)
    {
        return LODs[lod];
    }

    public static int ThreadGroups(int lod)
    {
        return LODs[lod] / NumThreads;
    }
}

I also have some additional files like these, I have to updte these as well ?

#
// Assets/Scripts/Compute/NoiseCompute.compute

#pragma kernel GenerateNoise //Computation which will be executed repeatedly, in parallel (on multiple threads)

#include "Includes\FastNoiseLite.compute"
#include "Includes\MetricsCompute.compute"

RWStructuredBuffer<float> _Weights;

float _NoiseScale;
float _Amplitude;
float _Frequency;
int _Octaves;
float _GroundPercent;
int _GroundLevel;
float2 _NoiseOffset;  // Added this line
int seedValue;  // Declare this at the top where you declare other variables

[numthreads(numThreads, numThreads, numThreads)]
void GenerateNoise(uint3 id : SV_DispatchThreadID)
{
    fnl_state noise = fnlCreateState();
    noise.seed = seedValue;  // Add this line to set the seed value. Replace "seedValue" with the actual variable name if different.
    noise.noise_type = FNL_NOISE_OPENSIMPLEX2;
    noise.fractal_type = FNL_FRACTAL_RIDGED;
    noise.frequency = _Frequency;
    noise.octaves = _Octaves;
    float3 pos = (id * _NoiseScale) / (_ChunkSize -1) * _Scale + float3(_NoiseOffset.x, 0, _NoiseOffset.y);  // Modified this line
    float ground = -pos.y + (_GroundPercent * _GroundLevel);
    float n = ground + fnlGetNoise3D(noise, pos.x, pos.y, pos.z) * _Amplitude;  
    _Weights[indexFromCoord(id.x, id.y, id.z)] = n;
}
}```
And this one too.
verbal dome
#

You need to convert everything that uses XZ to use XYZ instead

cosmic dagger
eternal falconBOT
verbal dome
#

@real heart ```cs

  • float3(_NoiseOffset.x, 0, _NoiseOffset.y);```
    Pretty sure that should just be + _NoiseOffset
    You want to use all of the components of the vector: x, y, z
real heart
#

Not they're seamless again.

verbal dome
#

Did you change NoiseOffset to float3 too?

real heart
#

I don't think so, vertically they are still the same.

#

I'll check if I did that.

#

I have it like this now:

// Assets/Scripts/Compute/NoiseCompute.compute

#pragma kernel GenerateNoise

#include "Includes\FastNoiseLite.compute"
#include "Includes\MetricsCompute.compute"

RWStructuredBuffer<float> _Weights;

float _NoiseScale;
float _Amplitude;
float _Frequency;
int _Octaves;
float _GroundPercent;
int _GroundLevel;
float3 _NoiseOffset;
int seedValue;

[numthreads(numThreads, numThreads, numThreads)]
void GenerateNoise(uint3 id : SV_DispatchThreadID)
{
    fnl_state noise = fnlCreateState();
    noise.seed = seedValue;
    noise.noise_type = FNL_NOISE_OPENSIMPLEX2;
    noise.fractal_type = FNL_FRACTAL_RIDGED;
    noise.frequency = _Frequency;
    noise.octaves = _Octaves;

    float3 pos = (id * _NoiseScale) / (_ChunkSize - 1) * _Scale + _NoiseOffset;
    
    float ground = -pos.y + (_GroundPercent * _GroundLevel);
    float n = ground + fnlGetNoise3D(noise, pos.x, pos.y, pos.z) * _Amplitude;
    
    _Weights[indexFromCoord(id.x, id.y, id.z)] = n;
}```
verbal dome
#

Looks better to me. Still some issues or?

real heart
#

Still no connection.

#

Like it still looks like a bunch of sheets on top of each other.

verbal dome
#

Maybe something to do with the "ground" calcualtion in the shader. Not sure.

real heart
#

I didn't update it yet.

#
// Assets/Scripts/GridMetrics.cs

public static class GridMetrics
{
    public const int NumThreads = 8;

    public const int Scale = 32;

    public const int GroundLevel = Scale / 2;

    public static int[] LODs = {
        8,
        16,
        24,
        32,
        40
    };


    public static int LastLod = LODs.Length - 1;

    public static int PointsPerChunk(int lod)
    {
        return LODs[lod];
    }

    public static int ThreadGroups(int lod)
    {
        return LODs[lod] / NumThreads;
    }
}

Same with this one.

verbal dome
#

indexFromCoord looks ok to me

#

The rest are probably fine too

real heart
#

Then that leaves us with only this compute file

#

Maybe it's the settings I'm using ?

scenic saffron
#

how to make a loop

deft grail
#

the easiest loop is foreach

scenic saffron
deft grail
scenic saffron
#

ok

#

like this?

deft grail
scenic saffron
#

!code

eternal falconBOT
scenic saffron
polar acorn
#

It's already framerate independent

scenic saffron
#

ok

#

thx

real heart
# verbal dome Maybe something to do with the "ground" calcualtion in the shader. Not sure.
// Assets/Scripts/Compute/NoiseCompute.compute

#pragma kernel GenerateNoise

#include "Includes\FastNoiseLite.compute"
#include "Includes\MetricsCompute.compute"

RWStructuredBuffer<float> _Weights;

float _NoiseScale;
float _Amplitude;
float _Frequency;
int _Octaves;
float _GroundPercent;
int _GroundLevel;
float3 _NoiseOffset;
int seedValue;

[numthreads(numThreads, numThreads, numThreads)]
void GenerateNoise(uint3 id : SV_DispatchThreadID)
{
    fnl_state noise = fnlCreateState();
    noise.seed = seedValue;
    noise.noise_type = FNL_NOISE_OPENSIMPLEX2;
    noise.fractal_type = FNL_FRACTAL_RIDGED;
    noise.frequency = _Frequency;
    noise.octaves = _Octaves;

    float3 pos = (id * _NoiseScale) / (_ChunkSize - 1) * _Scale + _NoiseOffset;
    
    // Removed the ground calculation
    float n = fnlGetNoise3D(noise, pos.x, pos.y, pos.z) * _Amplitude;
    
    _Weights[indexFromCoord(id.x, id.y, id.z)] = n;
}```
You won't believe it but I think that was it! 
I have updated my code like this and that seems to have solved it! 😮
steep rose
#

neato man great job

carmine narwhal
#

can someone help with this. according to unity.docs reflect works as pic to the left but does that mean it will go as the orange arrow in pic to the right or the black one? excuse my 3 year old drawing 😄

real heart
steep rose
#

that seems to be an issue with your breaking of your terrain

real heart
#

I mean besides that, some parts of the terrain look like they are missing their faces if you pay attention,

real heart
# steep rose that seems to be an issue with your breaking of your terrain

And here when I dig my tunnel, do you see that crease ? That looks like a vertical disconnection in the terrain itself. I wonder if that is caused by me digging or if the terrain is already disconnected like that before I dig ?

Could it be the digging which causes those creases ? I have not updated my digging script after updating the rest of the code to work with Vector3 instead of Vector2.

mint remnant
#

how are you doing the 3d noise? Looks like this is all done in compute shaders

steep rose
real heart
steep rose
#

i only know so much when it comes to procedural stuff, so I applaud you 😅

mint remnant
#

I had been working with attempting to do 3d noise, but only have a 2d version and was going to use 3 planes to generate it at 3 axis. When working with chunks just on 2d I had lots of issues with making edges connected as well. The solution was making sure the predicted max extents on height were normalized across all chucnks globally and not locally tro the chunk

real heart
verbal dome
#

I would start by making a debug option that colors each chunk's mesh with a different color. Easier to debug and present problems to others

mint remnant
#

The next big issue was getting the collision mesh calculated in a timely fashion in a single frame to prevent fps drop. Still haven't really solved that

real heart
real heart
#

Actually hold on, I can link you the guide, would you like that ? @mint remnant Cause it also explains things in detail.

mint remnant
#

yes would love to look at it

real heart
verbal dome
mint remnant
verbal dome
#

Am I making sense?

real heart
verbal dome
#

Don't rely on mesh colliders for the overlap.
Could either:
A. Add a trigger box collider to each chunk so they can be always detected, despite having only "empty" space
B. Use some manual math to check what chunks overlap the digging point+radius

real heart
#

The Chunks seem to be misalgined, so something is probably not calculated right somewhere. At least I know now it's not from the digging script but I wonder what causes this issue to happen now.

#

It looks like an offset issue, like a slight miscalculation somewhere.

verbal dome
#

Yeah something about the voxel coordinates in each chunks is off

#

Like its skipping some voxels between chunks

mint remnant
#

what helped me a little was adding a plane with the noise generated on it as a texture that I could move around in hte scene to see where it matched up verses not

verbal dome
#

Yep - when doing proc gen stuff, visualizing your data is powerful

mint remnant
#

also helped alot to have the offsets into the noise generation on the plane on a slider that updated in real time so you could move it around

real heart
#

Claude suggested doing this.

#

So I've done that and the issue disappeared horizontally, but now I get it vertically lol.

mint remnant
#

when trying to debug issues like this add lots of toggle switches to turn off features and work with as few of chunks as possible to focus only on the problem. it can be a pain to have to rerun lots of extra code each change

real heart
#

I'll try and do that, and also add more debug stuff like you guys said, as in visual stuff. Thank you very much 🙏🏻

orchid kite
#

!code

eternal falconBOT
devout birch
#

Hey ! Right now, I’m trying to create a 2D rogue-like game, but I’m having a lot of difficulties with the attack system for the mobs. I'm not quite sure how to make it work properly... To summarize my attack system so far: The mob chases the player, and when it gets close enough, it stops and attacks using a BoxCollider2D that serves as a hitbox (thanks to the OnTriggerEnter2D() function). However, this isn’t viable because if the player doesn’t move, the BoxCollider2D doesn't trigger anymore, and thus the player doesn’t take damage... I'm not sure if I'm on the right track, so if anyone can help me, that would be great ! (PS : I can show my script if u want)

orchid kite
#

    [SerializeField] private float cooldown;
    [SerializeField] private Transform firePoint;
    [SerializeField] private GameObject[] bananas;
    private MonkeyScript playerMovement;
    private float cooldownTime = Mathf.Infinity;


    private void Update()
    {
        if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())

            Attack();

        cooldownTime += Time.deltaTime;
    }

im getting this error and unity message of no reference: NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)

can someone please tell me how to refrence this the error is on the line of the if statment btw

deft grail
orchid kite
#

private MonkeyScript playerMovement;

deft grail
#

where do you assign it

orchid kite
#

idk what that means sry im so nooby

deft grail
#

right now its null

#

nothing

orchid kite
#

i did not give a value

#

idk what value to give it

deft grail
summer stump
#

Then the value is null. That is the default until you give it a value (for reference types)

deft grail
devout birch
#

I think u need to [SerializeField] private MonkeyScript playerMovement; and attach this script in u other script

orchid kite
summer stump
#

So there is a MonkeyScript on some object. You need to tell the compiler that your variable is pointing at that specific MonkeyScript

deft grail
orchid kite
#

ya i put monkeyscript on my monkey

deft grail
summer stump
orchid kite
#

ya im a bit confused

devout birch
#

attach like this

orchid kite
#

i think i did that

deft grail
devout birch
#

i don't think so because ur Script "MonkeyScript playerMovement;" is "private"

orchid kite
#

oh

#

so do i just make it public

devout birch
#

do [SerializeField] private MonkeyScript playerMovement;

#

or public

tulip parrot
#

I have a problem, I am trying to use the OnMouseOver method but it is never called and I don't understand the reason.

orchid kite
#

alr mister

deft grail
orchid kite
#

thanks guys im very noobdy so this is all new stuff to me

summer stump
# orchid kite alr mister

To clarify, they are describing a "serialized reference" which you can read more of in the guide i linked

orchid kite
summer stump
orchid kite
#

thanks guys appreciate it

eternal falconBOT
#

:teacher: Unity Learn ↗

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

orchid kite
#

oh alr

#

thanks

tulip parrot
rich adder
#

how did you verify its never called

rich adder
#

if its trigger double check these

tulip parrot
#

i make a debug log in that methods

#

never go on

rich adder
tulip parrot
rich adder
tulip parrot
rich adder
tulip parrot
north kiln
tulip parrot
rich adder
#

It should work iirc I haven't used in years, I just use raycast or the built in physics raycaster component with event trigger

#

the built in one I found to be finnicky also no layer filter / hitinfo support

tulip parrot
#

i try using IPointerEnterHandler, IPointerExitHandler but nothing happens

rich adder
#

default usually works with canvas UI

tulip parrot
rich adder
tulip parrot
#

D:<

#

its my camera

rich adder
orchid kite
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonkeyAttack : MonoBehaviour
{
    [SerializeField] private float cooldown;
    [SerializeField] private Transform firePoint;
    [SerializeField] private GameObject[] bananas;
    private MonkeyScript playerMovement;
    private float cooldownTime = Mathf.Infinity;


    private void Update()
    {
        if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())

            Attack();

        cooldownTime += Time.deltaTime;
    }

    private void Attack()
    {
        cooldownTime = 0;

        bananas[FindBanana()].transform.position = firePoint.position;
        bananas[FindBanana()].GetComponent<BananaThrow>().SetDirection(Mathf.Sign(transform.localScale.x));
    }

    private int FindBanana()
    {
        for (int i = 0; i < bananas.Length; i++)
        {
            if (!bananas[i].activeInHierarchy)
                return i;
        }

        return 0;
    }
}

guys i got the same error and making it public/serialized field did not work

NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:16)

the first if statment is where the error is

rich adder
orchid kite
#

what does that mean

rich adder
orchid kite
#

ya

tulip parrot
#

nothing happens

orchid kite
#

please and thank you

rich adder
orchid kite
#

the first if statment

rich adder
#

you have to assign it , either with = or inspector

orchid kite
#

if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())

rich adder
#

playerMovement is null

#

make it SerializeField and drag n drop

orchid kite
#

drag n drop where

rich adder
# tulip parrot

did you put the interface ? can you show a bit of the scene and where is the object when you hover it

devout birch
rich adder
tulip parrot
devout birch
#

ok create a function Start() :
private void Start()
{
playerMovement = FindObjectByType<MonkeyScript>();
}

rich adder
orchid kite
#

im so confused bro

devout birch
#

he said it doesn't work

rich adder
orchid kite
#

ya

rich adder
rich adder
orchid kite
#

i didnt see the slot

rich adder
rich adder
orchid kite
#

yes

rich adder
#

then you should have a field for MonkeyScript

#

drag n drop script from an object inside

verbal dome
#

Is MonkeyScript even serializable/MonoBehaviour?

rich adder
#

also make sure this for MonkeyScript ^

orchid kite
#

i made it serializedfield but i dont hv any playermovement options in unity

rich adder
orchid kite
#

it says no errors just when i click my mouse button in play mode to have the banana throw it gives me that error i showed u before

#

maybe this will help idk

rich adder
#

i made it serializedfield but i dont hv any playermovement options in unity

orchid kite
#

omg no way im so dumb

#

wait so i just drag my monkeyscript code here

rich adder
#

well its probably just lack of knowing what you're expect to see/happen ig

tulip parrot
#

i dont know how to fix this

rich adder
#

I wonder if pixelPerfect is messing with raycaster

tulip parrot
#

i try disabling UI elements and the same, i try deleting and the same result

#

i try a lot of things but nothing happens

#

i dont know if camera has to be down of my blocks

rich adder
orchid kite
rich adder
rich adder
orchid kite
#

like im trynna drag my monkeyscript into that area however its not letting me put it in

rich adder
orchid kite
#

ya

tulip parrot
rich adder
tulip parrot
orchid kite
#

wait i put it on gameobject

rich adder
# tulip parrot

btw UI elements WILL block the raycast with that component (physics raycaster)

tulip parrot
#

i disable any UI elements

#

i try with everything and nothing works

rich adder
#

if you're still having trouble use a regular raycast
var ray = cam.ScreenPointToRay(Input.mousePosition)
var hit = Physics2D.Raycast(ray, etc.

orchid kite
#

ok now i hv to fix so much of that same issue thank you tho @rich adder i rlly appreciate it

orchid kite
#

like i hv the same refrence issues but on my banana throw code cuz my things are on private like boxcollider

rich adder
#

make sure they are assigned like you saw, it should be ez

orchid kite
#

yessir thanks

tulip parrot
#

my UI Input System is right?

rich adder
rocky canyon
scenic saffron
#

why is my character stopping late when i normalize the movement vector?

teal viper
#

If you want it not to do that use GetAxisRaw

scenic saffron
#

get axis raw fixes it for some reson

teal viper
#

Ah, well, I guess normalization magnifies the issue, since it bumps even a very small vector to magnitude 1

summer stump
scenic saffron
#

Ohh makes sense

#

And normalization breaks the soothing

summer stump
scenic saffron
#

Thx guys

tulip parrot
#

Pointer-related actions used with the UI input module should generally be set to Pass-Through type so that the module can properly distinguish between input from multiple pointers (action Move/RightClick[/Mouse/rightButton] is set to Button)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Event System send this warning

snow warren
#

Hello

#

i am facing some trouble

#

i wrote this script as a drag handle

#
using UnityEngine.EventSystems;

public class DragHandle : MonoBehaviour, IDragHandler
{
    private Vector2 Previous = Vector2.zero;
    public void OnDrag(PointerEventData data)
    {
        Previous += data.delta;
        if (data.dragging)
        {
            BorderlessWindow.MoveWindowPos(Previous, Screen.width, Screen.height);
        }
    }
}```
#

on UI
wherever i put this script
if i drag there then it should move the window

#

the window does move

#

but the drag is pretty big

#

and stutters a lot

#

and not correct

#

any helps?

snow warren
#

Anyone??

teal viper
rocky canyon
# snow warren ```using UnityEngine; using UnityEngine.EventSystems; public class DragHandle :...
    private Vector2 previousMousePosition;

    public void OnDrag(PointerEventData data)
    {
        // calculate mouseDelta
        Vector2 mouseDelta = data.position - previousMousePosition;
        BorderlessWindow.MoveWindowPos(mouseDelta, Screen.width, Screen.height);

        // update new position
        previousMousePosition = data.position;
    }

    private void Start() => previousMousePosition = Vector2.zero;

im in agree'ance w/ dlich.. something odd about the way u use previous.. i'd do it this way..

#

the first way gets the delta.. directly tracking the movement between frames
the way u had it accumulates the delta which is the change between the last event..

(minor difference)

#

blabla... compounding errors.. blabla if event handling isn't perfectly smooth.. blabla etc

#

Input: Mouse moves from (100, 100) → (120, 120) → (140, 140).

  • New Delta : Drag 1. No Movement (initial position set), Drag 2. Moves by 20, Drag3. Moves by 20.
  • Accumulative Delta: Drag1. Moves by 20, Drag2. Moves by 40. Drag3 (we'll ur already there)
hybrid gust
#

if I want to get the bounds for an object, but I DO want the bounds to remain the same, even when I rotate said object. Am I supposed to use Mesh.bounds, or Renderer.bounds?

#

feel like my brain is incapable of understanding docs today

#

I'm assuming mesh.bounds

rocky canyon
#

renderer i think

hybrid gust
#

oh?

teal viper
rocky canyon
#

mesh bounds do not account for objects rotation.. (own local space)

hybrid gust
#

like, if I have a rectangle, and I wanted to get the long side via bounds.size

#

I should use Renderer bounds then?

rocky canyon
#

try it and see

#

Use Renderer.bounds to get the bounding box in world space, which includes the effect of rotation. Use Mesh.bounds if you only need to know the bounds relative to the mesh’s local space, without considering the object's rotation.

hybrid gust
#

rog

rocky canyon
#

just copy-pasta.. i'd need to test myself real quick.. but it looks legitimate

hybrid gust
#

i'll try it here in a minute, I think i need brain food cause the brain fog is heavy rn

rocky canyon
#

Vector3 syze = renderer.bounds;
float longestSide = Mathf.Max(syze.x, syze.y, syze.z); would be how u get the longest side i think

fallen compass
#

!cs

eternal falconBOT
eternal needle
queen adder
#

My setup right now is just that default code snippet, a box collider, and the player with a rigid body on it. It simply never enters the if statement because it's not detecting the rigid body, I have to assume it's just to do with where I'm putting it (player armature because I didn't think putting it on the follow camera or parent seemed correct) BobShrug I will look at that link, thank you.

cerulean cargo
#

I am having this issue where when I shoot a raycast from the parent transform of the camera, the raycast one time will hit dead center, then the next it may hit a but lower. I have all scripts controller the camera turned off. And this issue is still happening!

#

`public void Shoot()
{
if (playerCamera == null)
{
Debug.LogError("Player camera is not assigned.");
return;
}

// Cast a ray from the center of the screen
RaycastHit hit;

// Visualize the raycast
//Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.red, 2f);

if (Physics.Raycast(playerCamera.position, playerCamera.forward, out hit, maxDistance, hitLayers))
{
    // Log the hit details
    Debug.Log($"Hit Point: {hit.point}, Hit Normal: {hit.normal}");

    // Check if the hit object has the "Enemy" tag
    if (hit.collider.CompareTag("Enemy"))
    {
        ActivateEffect(bloodEffectPool, hit);
    }
    else
    {
        ActivateEffect(bulletHolePool, hit);
    }
}
else
{
    Debug.Log("Raycast did not hit any object.");
}

}

#

I do not know how to send a code snipped correctly

mint remnant
#

follow steps in this !code

eternal falconBOT
toxic cloak
#

does singleton classes dosent works inside coroutines?

mint remnant
#

nothing special that they wouldn't

#

unless of course you're talking about creating one inside a coroutine, which would be weird

toxic cloak
#

oh sorry nvm my instance was null notlikethis

cerulean cargo
#
{
    if (playerCamera == null)
    {
        Debug.LogError("Player camera is not assigned.");
        return;
    }

    // Cast a ray from the center of the screen
    RaycastHit hit;

    // Visualize the raycast
    //Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.red, 2f);

    if (Physics.Raycast(playerCamera.position, playerCamera.forward, out hit, maxDistance, hitLayers))
    {
        // Log the hit details
        Debug.Log($"Hit Point: {hit.point}, Hit Normal: {hit.normal}");

        // Check if the hit object has the "Enemy" tag
        if (hit.collider.CompareTag("Enemy"))
        {
            ActivateEffect(bloodEffectPool, hit);
        }
        else
        {
            ActivateEffect(bulletHolePool, hit);
        }
    }
    else
    {
        Debug.Log("Raycast did not hit any object.");
    }
}```
#

I do not think its in the code but When I shoot a raycast, it hits in different places even though the camera is not moving at all!

wintry quarry
cerulean cargo
cerulean cargo
cerulean cargo
wintry quarry
cerulean cargo
wintry quarry
#

It would help to understand the hierarchy and which objects are which and which objects are actually moving or not etc

cerulean cargo
#

I dont directly rotate the cameras because I have 2 of them since it is a VR game. I Use one for the left eye and one for the right. So I rotate the camera Parent instead.

#

In this image, the VR Camera rig is the parent of all of the camera stuff

slender nymph
weary belfry
#

oops didnt see that thanks

dense pike
#

Hi I need help creating a trigger enemy animation script

eternal needle
#

if you havent even started trying to do it, then start googling specifically for what youre trying to do

sour fulcrum
#

Is there any reliable initialization-esque call on scriptableobjects in a play mode context? awake and onenable seem off

#

online seeing a lot of suggestions to just use initializeonload type stuff? nvm

#

i hate unity sometimes

nimble apex
#

i had optimized my team project code a bit, currently we need to download game images from our cloud servers, store it into local storage , and use it as texture2D

this is my code to store it

File.WriteAllBytes(filePath, downloadedTexture.EncodeToPNG());```

this is my code to read it and use it as texture2D
```cs
    public Texture2D LoadTextureFromLocal(string fileName, bool isMipMap = false)
    {
        string filePath = $"{Application.persistentDataPath}{agent_image_default_path}{fileName}.png";
        AgentCustomFileVersion sourceImageInfo = LocalDataConfigScript.dataStore.localResourceVersion.agent_customs.Find(x => x.name == fileName + ".png");

        if (!File.Exists(filePath)) { return null; }

        if (isMipMap)
        {
            Texture2D mipMapTexture = new Texture2D(sourceImageInfo.imageWidth, sourceImageInfo.imageHeight, sourceImageInfo.textureFormat, true);
            //mipMapTexture.SetPixels(texture.GetPixels());
            //mipMapTexture.Apply();

            return mipMapTexture;
        }
        else
        {
            Texture2D texture = new Texture2D(sourceImageInfo.imageWidth, sourceImageInfo.imageHeight, sourceImageInfo.textureFormat, false);
            texture.LoadImage(File.ReadAllBytes(filePath));
            texture.name = fileName;

            return texture;
        }
    }```

1. do u guys think i need to specify texture2D in the constructor first? or just a loadimage is fine, or u have a better function to do it

2. do u guys have better solution on mipmap part? cuz i heard getpixels also quite expensive if u use it like this
#

p.s mimap part is not written by myself, im still improving it

snow warren
#

same error

teal viper
snow warren
#

here is the movewindow function i am using

#
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint);```
#

usually int x and y varies between 0 to 10

#

which is drag

#

in my case drag is either tooo much

#

or too low

#

this is the drag i get

grand badger
nimble apex
#

cuz loadimage will just fix it all for me

grand badger
#

ya

nimble apex
#

NICE

#

cuz i afraid it wont do that for me

slender nymph
#

configure your !IDE and you might see the error 😉

eternal falconBOT
slender nymph
#

also it is against server rules to discuss decompilation and modding games and it is clear that this is decompiled/ripped code

arctic brook
#

whoops

cosmic dagger
#

what the hell is that script? 🤔

arctic brook
#

apparently i cant discuss

#

so i couldnt tell youi

sour fulcrum
#

Any suggestions on a solid way to have an awake/onenable/start esque function run on scriptableobjects in play mode with no sort of outside manager esque scripts involved

cosmic dagger
sour fulcrum
#

i dont like that 😦

cosmic dagger
#

best to explain what you're trying to do . . .

teal viper
sour fulcrum
cosmic dagger
#

probably . . .

sour fulcrum
cosmic dagger
#

just use a manager or controller script for them, if necessary . . .

sour fulcrum
slender nymph
#

you haven't actually said what you are trying to accomplish with this though so a proper solution can't be suggested until you do.
https://xyproblem.info/

cosmic dagger
sour fulcrum
#

Yeah I know it's just abit of a rabbit hole that's a whole weird thing to explain, Totally get my responses have been unideal in regards to finding an actual answer

#

the kind of rough tldr is im prototyping a super generic settings system that allows me to have each individual game setting exist as a class stored inside a scriptableobject

#

but trying to figure out a way to properally handle modifications to the class inside the scriptableobject needing to not effect it's defaults

slender nymph
#

why does it specifically need to be in a ScriptableObject

sour fulcrum
#

honestly just to work with Unity in regards to referencing via drag and drop, visualising the info real nicely etc.

slender nymph
#

why do you need to drag and drop? just use a static class, your architecture here just sounds like you are trying to make a static class without making it static

snow warren
#

I have a problem

#

how to get a Rect from the UI

cosmic dagger
grand badger
#

GetComponent<RectTransform>().rect

snow warren
snow warren
#

didnt work

sour fulcrum
#

a static class creates problems for me in regards to making it generic and modular enough to use in any project i throw at it + i want to easily view these settings in the inspector for editing purposes

grand badger
#

try again, it works!

snow warren
#

ok

cosmic dagger
snow warren
#
    {
        Rect rect = this.GetComponent<RectTransform>().rect;
        if (rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseDown && Event.current.button == 0)
        {
            Window.ResizeTopStart();
        }
        if ((Event.current.type == EventType.MouseUp && Event.current.button == 0) || (Window.MoveWindow && !Input.GetKey(KeyCode.Mouse0)))
        {
            Window.ResizeTopEnd();
        }
    }```
slender nymph
cosmic dagger
# sour fulcrum This is correct

you need to create a settings SO with default values. when exiting play mode, assign the actual settings SO values to the default SO values . . .

snow warren
cosmic dagger
#

like the button some games have that will set a specific setting (or all) to default when pressed . . .

slender nymph
snow warren
slender nymph
#

show the inspector

cosmic dagger
slender nymph
#

that too

sour fulcrum
#

hm

Let me ponder my orb abit on that suggestion, doesn't solve what im looking for outright but with some tinkering around it may

#

I can perhaps do something disgusting

snow warren
cosmic dagger
snow warren
slender nymph
#

show the full stack trace for the error

cosmic dagger
snow warren
#
ReSize.Update () (at Assets/bB/ReSize.cs:9)
snow warren
#
using UnityEngine;
using UnityEngine.UI;

public class ReSize : MonoBehaviour
{
    public void Update()
    {
        Rect rect = this.GetComponent<RectTransform>().rect;
        if (rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseDown && Event.current.button == 0)
        {
            Window.ResizeTopStart();
        }
        if ((Event.current.type == EventType.MouseUp && Event.current.button == 0) || (Window.MoveWindow && !Input.GetKey(KeyCode.Mouse0)))
        {
            Window.ResizeTopEnd();
        }
    }
}
slender nymph
#

and which is line 9

snow warren
#
if (rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseDown && Event.current.button == 0)```
slender nymph
#

exactly, so the GetComponent line works just fine and so does getting its rect (which is a value type so that cannot be null)

#

you don't have an EventSystem in your scene

cosmic dagger
#

hmmm, do you have an event system?

snow warren
#

i thought the code should work without one

#

how to add one?

cosmic dagger
#

nah, box beat me to it . . .

snow warren
cosmic dagger
#

it adds by default when you create a UI element . . .

slender nymph
cosmic dagger
#

make an empty GameObject and add the EventSystem component to it . . .

snow warren
slender nymph
#

you can only have one

snow warren
#

ok lemme add it

#

yoooo

#

it already has an event system

cosmic dagger
#

you can add via the dropdown menu: GameObject > UI > EventSystem . . .

slender nymph
#

oh wait wtf, your code is using Event.current not EventSystem.current

#

that's for IMGUI

snow warren
#

what to do?

slender nymph
#

what are you trying to do

snow warren
#

as i removed the borders using C++ user32 lib

#

so its now a frameless window

#

now i am trying to rescale window with no borders

slender nymph
#

so based on the screenshot you previously posted then deleted, it seems you are trying to make some sort of launcher program in unity. which is not the appropriate technology for that. so good luck 🤷‍♂️

sour fulcrum
cosmic dagger
sour fulcrum
#

yeah thats fair

#

def. could end up not sticking with my weird nitpicks just kinda trying to feel it out and see what i actually want here