#💻┃code-beginner

1 messages · Page 494 of 1

buoyant knot
#

2D cameras might just need to pan when a cursor hits an edge

rough orbit
#

yes

polar acorn
#

@tulip nimbus any chance you can get a video of what it's currently doing?

rough orbit
#

no, 748 times

buoyant knot
#

my point is that you can make good arguments for 2D cameras to just do them custom.

#

but writing your own camera from scratch for 3D? fuck that

polar acorn
rough orbit
polar acorn
buoyant knot
#

i’d also search Time.TimeScale via IDE to know if you’re messing with it

tulip nimbus
#

Okay for a bit more context if you dont mind me still asking this:

There is a prefab which is called. The shown code is in its Awake() function. So everytime the prefab is created(like a bullet) it aims at the cursor once, and then the prefab travels towards the position it got at the moment it got Instantiated.

However, as stated, they all aim And only then at the Plane Camera when i give it the "Main Cam" tag

rough orbit
tulip nimbus
#

Again thanks for your help, patience and time

polar acorn
#

You can use unscaledDeltaTime instead, or find where you're setting it to 0 and just not do that

#

since it seems like you never intended to

polar acorn
silk night
rough orbit
silk night
#

just as a suggestion by the way, for stuff like "animating" volume over time there are good "tweening" libraries out there, they are convenient (BUT not always the best performance wise)

tulip nimbus
#

The Plane is in the "follow" space inside the Cinemachiene Virtual Camera component

rough orbit
#

Thanks digiholic and sidia. I'll find another way to prevent stuff from happening in the background.

#

Prob just disable enemy updates

polar acorn
polar acorn
# tulip nimbus

I don't think the virtual camera needs the main camera tag but I also don't think that would affect anything since it doesn't have a camera component on it

tulip nimbus
#

oh yeah i also gave it the tag but it didnt change much :(

silk night
polar acorn
#

Maybe it is facing the mouse, but the wrong side of it?

tulip nimbus
#

do you mean movement? Because i didnt programm that yet

#

they just stand still atm

polar acorn
#

No, I mean the sprite you're using. You're angling the green arrow towards the mouse

#

Can you show the inspector of a bullet with the transform gizmo visible?

tulip nimbus
#

like this?

polar acorn
#

In the scene too, to see where the arrow is

steep rose
#

he may be using global gizmos

#

unless they are always local (i think it defaults to global)

polar acorn
#

Right, make sure you're on local.

tulip nimbus
#

im so sorry if this isnt right. ITs like this on local and global

polar acorn
steep rose
#

what how

polar acorn
#

It's facing world up

tulip nimbus
#

i have an itch that the solution is really simple and im just not showig you guys the right things haha

polar acorn
#

so they're the same right now

tulip nimbus
steep rose
#

oh, then your good

polar acorn
#

Let me try to construct a scene as close to what you have as I can and see

tulip nimbus
#

or parts of it

polar acorn
#

It'd probably be faster for me to just rebuild it

tulip nimbus
#

i dont want you to download anything but perhaps there is a function to share or smth

steep rose
#

then you cant

polar acorn
#

I have it mostly done, I just need to have the cinemachine camera follow something

tulip nimbus
#

yeah you guys are the pros here haha

patent imp
steep rose
rough orbit
polar acorn
#

Yeah, with the camera following an object, and the script you've shown put in Update on a sprite, orthographic camera, using cinemachine, I'm getting exactly what you'd expect, the arrow faces the mouse cursor even as the circle moves. There is definitely something else going on here. Can you share the full script for the bullet?

#

Ah, the screenshot didn't include the cursor, but it's pointing at the cursor and not the circle

tulip nimbus
#
 void Update() 
 {

     FaceMouse();
 }

 void FaceMouse() 
 { 
     Vector2 mousePosition = Input.mousePosition;
     mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

     Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);

     transform.up = direction;
 }

This is basically all the code, i replaced it to this again, before the big part was in the Update function since i wanted to put some other stuff there but it works the same ig

polar acorn
#

It looks like your bullets are facing the plane, rather than the mouse

queen adder
#

What scripting (C#) tutorial do you guys reccomend? English isnt my first language so keep that in mind.

polar acorn
# tulip nimbus

Eh, let's see the !code for Plane Behaviour as well. Maybe it's doing some shenanigans to the prefab that's affecting all of the children of it? I'm not sure what but at this point all the things I've expected it to be have all been fine so I'm gonna just check everything

eternal falconBOT
queen adder
#

What scripting (C#) tutorial do you guys reccomend? English isnt my first language so keep that in mind.

tulip nimbus
# queen adder What scripting (C#) tutorial do you guys reccomend? English isnt my first langua...

Idk your level but As a beginner "Brackeys" on YT. His main language also isnt english so he explains it pretty simple imo

But as i can imagine you heard that before i can also greatly recommend: Code Monkey and this Video: https://www.youtube.com/watch?v=GhQdlIFylQ8&t=5785s

This course will give you a full introduction into all of the core concepts in C# (aka C Sharp). Follow along with the course and you'll be a C# programmer in no time!

⭐️ Contents ⭐️
⌨️ (0:00:00) Introduction
⌨️ (0:01:18) Installation & Setup
⌨️ (0:05:03) Drawing a Shape
⌨️ (0:17:23) Variables
⌨️ (0:30:06) Data Types
⌨️ (0:37:17) Working With S...

▶ Play video
polar acorn
#

Probably !learn but I can only vouch for the english-ness of it

eternal falconBOT
#

:teacher: Unity Learn ↗

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

tulip nimbus
polar acorn
#

At this point I'm too baffled to be snarky

#

I just wanna see what's going on with this tbh

tulip nimbus
#

oops

#
void Update()
{

    
    //CONTROLLS
    if (Input.GetKey(KeyCode.A))
    {
        dir = 0.05f * TurnSpeed;
    }
    else if (Input.GetKey(KeyCode.D))
    {
        dir = -0.05f * TurnSpeed;
    }
    else
    {
        dir = 0;
    }
    //FUEL BOOST
    if (Input.GetKey(KeyCode.LeftShift) && boosterFuel > 0)
    {
        MoveSpeed = BoostSpeed;
        boosterFuel -= 1;
    }
    else
    {
        MoveSpeed = CurrentdefaultMoveSpeed;
        boosterFuel += 1;
    }

    //SHOOTING CONTROLL
    if (Input.GetKey(KeyCode.Mouse0) && Ammo > 0)
    {
        shootDelayGun1 -= Time.deltaTime;

        if (Gun1 == true && shootDelayGun1 <= 0)
        {
            shootDelayGun1 = Gun1shootspeed;
            Audio_Source.PlayOneShot(ShootGun1);
            ShotGun1();

        }
    }
    else
    {
        shootDelayGun1 = Gun1shootspeed;
    }


    //Passive Movement
    transform.position += transform.right * MoveSpeed * Time.deltaTime;

    //Turns
    transform.Rotate(0, 0, dir);

}

void ShotGun1()
{
    Instantiate(BangVX, transform.position, Quaternion.identity);
    Instantiate(BulletGun1, transform.position,Quaternion.identity);
        

}
#

I havent checked out IEnumerators and Invokes so i still used simple Variables and time.Deltatime for my seconds

polar acorn
#

Send it in a pastebin, under "Large code blocks"
!code

eternal falconBOT
polar acorn
#

I can't Ctrl+F a discord message or a screenshot

tulip nimbus
jade tartan
#

@deft grail @polar acorn I see...

polar acorn
#

Have I looked at the inspector for the main camera yet?

#

Unsure if I've asked for that

tulip nimbus
steep rose
#

just to test something

steep rose
queen adder
#

i gotta split it up

steep rose
queen adder
tulip nimbus
# queen adder ITS 4 HOURS?

thought the same when i started a few weeks ago but when you follow the steps and listen time goes by fast

polar acorn
# tulip nimbus

Ah! Projection - Perspective. You said it was 2D so I've been using Orthographic

tulip nimbus
queen adder
#

now u understand it completely?

tulip nimbus
polar acorn
steep rose
#

just tell me what happens

queen adder
#

and screen time

#

take will take me weeks to watch

steep rose
#

best get crackin

polar acorn
#

It's not something you just know after 20 minutes

tulip nimbus
polar acorn
#

It's a skill that will take literal years to progress

polar acorn
steep rose
#

we have a over 700 hours of coding !learn

tulip nimbus
#

That was it

steep rose
eternal falconBOT
#

:teacher: Unity Learn ↗

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

tulip nimbus
#

Thank you guys so much

#

All of you

queen adder
#

!idonthavetimehelpme

polar acorn
#

Yeah, a perspective camera has the mouse at the position of the camera. It won't actually be able to detect the mouse movement

queen adder
#

😭

polar acorn
#

it'll always be at the same spot, where the perspective converges

#

you'd need to manually offset the mouse position to use perspective, but for a 2D game you probably want orthographic anyway

queen adder
#

ive spent all my money on a preorder of the iphone 16

#

so i cant afford unity pro

polar acorn
polar acorn
#

At no point has anyone suggested anything that costs money

steep rose
#

also why would you spend all of your money on a phone

queen adder
#

cuz i mine

#

and i needed to upgrade

#

ive got 0.4 bitcoin

polar acorn
#

On a phone

queen adder
#

yes

frosty hound
#

@queen adder We don't need the life story, nor do you need Unity Pro.

polar acorn
#

hah

queen adder
#

and some overclocking

polar acorn
#

None of this is relevant

#

How you choose to waste your money is irrelevant to the time it takes to learn to code

queen adder
#

why cant i say the word ''k''

tulip nimbus
# queen adder 😭

It was really really demotivating for me when i started. Im lucky because i have alot of time on my hands currently since i just graduated.

Even if you do a bit every day and if you dont give up it adds up.

The start was the hardest part. I also recommend learning by just doing. You get faster and better over this time even if its just a little. Plus it is productive. When it comes to coding you NEVER stop learning and you can always improve. The hard part is always starting. But even when you have little time you will thank youself that you started.

im still a beginner but i learned so much by just doing this current project and asking people that really know

queen adder
#

for me it is

polar acorn
queen adder
#

english isnt my first language

#

my language looks nothing like english

tulip nimbus
queen adder
#

it took me 3 years for common english language

queen adder
warped prawn
#

I have a solid grasp of code fundamentals (statements, variables, functions) when it comes to interacting with unity.

But I struggle with code architecture and understanding "higher level" OOP concepts such as classes, singletons, serialization.

any suggestions for resources that might help?

verbal dome
tulip nimbus
# queen adder mongolian

Thats intresting and i see the problem that there are not many tutorials in mongolian (if any) on programming. Maybe just follow what the people in the tutorial are doing for now. Programming (in my opinion) is alot more about logic than english. So if you know what each code block does and you can learn to combine them

#

English also isnt my first language but i learned it by watching youtube and taking courses and i got better

queen adder
tulip nimbus
#

Im not saying you should pay to improve tho

polar acorn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

you see

#

that website is also blocked

#

i have wifi tho

#

so yeah

polar acorn
#

Seems more like you just don't have internet, rather than it being blocked

queen adder
#

working and fine

polar acorn
#

¯_(ツ)_/¯

tulip nimbus
#

what about a VPN?

#

a free one if your PC has it integrated

polar acorn
#

Then I guess you'll just have to figure it out from the documentation

tulip nimbus
#

not something like NordVPN

#

(Also dont break any laws i have no clue tho)

polar acorn
#

If you physically cannot access the websites then there's nothing we can really do here

queen adder
#

so im not taking any risks

polar acorn
#

Then there's nothing we can do

queen adder
#

there are almost zero Mongolian coders

#

most people in mongolia get their jobs of their parents

tulip nimbus
queen adder
#

and there isnt really a mongolian scripting family

fickle plume
# queen adder

Wi-fi connection doesn't mean that Wi-fi device has internet access. Also most of this is off-topic to the channel.

tulip nimbus
#

If you can open the Unity API and other libraries containing information about Unity, the best way is to just code and try anything. Its hard but i beliebe this is the only way

queen adder
#

i did use a banned way of getting unity software

#

a imported usb

tulip nimbus
#

lets go to off-topic

queen adder
#

yeah

frosty hound
#

There is no off topic. Take it to DMs.

queen adder
#

@tulip nimbus ive gotta eat

tulip nimbus
#

yeah, no worries ill send you a few DMs

stuck palm
#

what is a field offset?

polar acorn
wintry quarry
north scroll
#

hey I think my VSC is broken. Its not showing any red squigglies and its also not suggesting autocompletion things like functions of a class and whatnot. I tried looking up stuff for intellisense cuz I think thats the right area but still not working. Anyone got any help ?

verbal dome
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

verbal dome
#

Other than that I'm not sure, it hasn't broken for me in a long time

#

First I'd try restarting vscode and unity

zealous geode
#
    public virtual void Attack(Microorganism target, Vector3 knockbackDirection)
    {
        target.GetDamaged(Damage);
        Debug.Log(Health);

        if (KnockbackActive)
        {
            Rigidbody targetRb = target.transform.GetComponent<Rigidbody>();
            ApplyKnockback(targetRb, knockbackDirection);
            KnockbackActive = false;
            StartCoroutine(KnockbackCooldown(targetRb, KnockbackTime));
        }
    }

    private IEnumerator KnockbackCooldown(Rigidbody rb, float knockbackTime)
    {
        yield return new WaitForSeconds(knockbackTime);
        KnockbackActive = true;
        if (rb.transform.GetComponent<NavMeshAgent>() != null)
        {
            rb.transform.GetComponent<NavMeshAgent>().isStopped = false;
            rb.transform.GetComponent<NavMeshAgent>().updatePosition = true;

        }
    }

    private void ApplyKnockback(Rigidbody rb, Vector3 knockbackDirection)
    {
        if(rb.transform.GetComponent<NavMeshAgent>() != null)
        {
            rb.transform.GetComponent<NavMeshAgent>().isStopped = true;
            rb.transform.GetComponent<NavMeshAgent>().updatePosition = false;

        }
        rb.isKinematic = false;

        rb.AddForce(knockbackDirection * 1500f);
    }
public class Hurtbox : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Hitbox"))
        {
            Microorganism target = other.transform.parent.GetComponent<Microorganism>();

            if(target != null)
            {
                Vector3 oppositeDirection = (target.transform.position - transform.position).normalized;

                target.Attack(this.transform.parent.GetComponent<Microorganism>(), oppositeDirection);
            }
        }
    }
}

Hello everyone, I have this class which holds some methods used by my player and my enemies. Each element holds a hurtbox and a hitbox.

#

The thing is that my enemies are controlled by a navmesh and their rigidbody is kinematic. And when trying to apply a knockback, it gets pretty buggy, even disabling the path following and making it dynamic.

#

Is there any efficient way to handle knockback with navmesh controlled elements?

north scroll
verbal dome
#

Either a class member variable or at least replace this:cs if (rb.transform.GetComponent<NavMeshAgent>() != null) { rb.transform.GetComponent<NavMeshAgent>().isStopped = false; rb.transform.GetComponent<NavMeshAgent>().updatePosition = true; }
With this:cs if(rb.TryGetComponent(out NavMeshAgent agent)) { /* agent.thisAndThat */ }

#

(The .transform is redundant too)

vagrant fjord
#

hey guys, 2 questions here. first, why is my animation not speeding up even tho i made it faster and also why is my enemy not displaying a particle when struck?

verbal dome
#

How did you make the anim faster?

#

As for the second question, no one can answer that without seeing code etc.

zealous geode
vagrant fjord
#

i just sped it up the actual anim and tried to increase speed in animator

wintry quarry
#

What does "I just sped it up" mean

vagrant fjord
#

i made the actual anim shorter

verbal dome
#

Scaled the animation keyframes horizontally, I assume

vagrant fjord
#

yeah that

verbal dome
#

Show the inspector of the animation state in #🏃┃animation , it doesn't seem like a code issue

#

Note: Animation state, not animation

vagrant fjord
#

okay, for my 2nd one ill paste code

#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CollisionDetection : MonoBehaviour
{
public WeaponController wp;
public GameObject HitParticle;

private void OnTriggerEnter(Collider other)
{
    Debug.Log(other.name);
    // Use IsAttacking instead of isAttacking
    if (other.tag == "Enemy" && wp.IsAttacking)
    {
        other.GetComponent<Animator>().SetTrigger("Hit");
        Instantiate(HitParticle, new Vector3(other.transform.position.x, transform.position.y, other.transform.position.z), other.transform.rotation);
    }
}

}

verbal dome
#

Psst, use "inline code" from this bot message: !code

eternal falconBOT
vagrant fjord
#

goyt it will do next time

verbal dome
#

You could edit your previous message
Anyways, does the Debug.Log ever log anything?

vagrant fjord
#

nope

verbal dome
#

Are you using 3D or 2D colliders/rigidbodies?

vagrant fjord
#

rigidbody and capsule collider for player and box collider for enemy

verbal dome
#

Yeah just making sure you have the correct components for 3D

vagrant fjord
#

will do

amber nimbus
#

I have this code:

    private void Update()
    {
        mouseX = Input.GetAxis("Mouse X") * mouseSens * Time.deltaTime;
        mouseY = Input.GetAxis("Mouse Y") * mouseSens * Time.deltaTime;

        transform.rotation *= Quaternion.Euler(0, mouseX, 0);

        camRotation -= mouseY;

        Mathf.Clamp(camRotation, -90f, 90f);
        mainCamera.transform.rotation = Quaternion.Euler(camRotation, 0, 0);
        
    }

But the Mathf.Clamp() is not clamping. The camera just rotates past 90degrees I cant figure out why

deft grail
#

your doing nothing with the result

amber nimbus
#

oh you are right

verbal dome
#

Also don't multiply mouse input with Time.deltaTime or it will be inconsistent

#

Mouse delta is already framerate independent

amber nimbus
amber nimbus
verbal dome
#

Yeah, but make sure to make mouseSens about 50-100x smaller after removing thet deltatime multiplication

amber nimbus
#

aight thanks :D

vagrant fjord
#

NullReferenceException: Object reference not set to an instance of an object

verbal dome
#

Which line?

wintry quarry
vagrant fjord
#

tried the different ones and im getting this error

hollow slate
#

very easy to find the cause too. Double-click on the error @vagrant fjord

#

takes you to the place it happens. Usually isn't too hard to figure out why.

vagrant fjord
#

did that and showed this

#

any help? sorry im super new

wintry quarry
#

the error will also contain a filename and line of code

#

you need to look there

vagrant fjord
#

i downloaded the enemy from asset store i think its that

#

its super confusing and i might just try it on a cube

wintry quarry
#

you can figure out the error and fix it

#

it's not hard

#

you just have to try

vagrant fjord
#

i got no clue bro but ill try

wintry quarry
bold saffron
bold saffron
#

whoops

#

line 21

wintry quarry
#

you used =

#

instead of ==

#

= is assignment

#

so it's returning what you assigned, and then trying to use that as a bool

bold saffron
#

omg im so stupid this is like the third time

wintry quarry
#

DirectionsList is not a bool

bold saffron
#

It's not like i'm new to proggraming or something, I used to use python so much, but I still make this mistake SOOOOO much 😭

slow hollow
vagrant fjord
#

(Graph) is the thing that showed up when i double clicked

verbal dome
#

Oh, that's just a Unity UI bug

#

Probably Definitely from the Animator window

#

Reset your layout, should fix it

#

Window > Layouts > Default

vagrant fjord
#

thanks!

verbal dome
#

Np - next time show the full error

#

We assumed it was from your own code but it was Unity's

vagrant fjord
#

just restarted: error gone but still not working?

snow warren
#

i want a suggestion

#

anyone active?

short hazel
eternal falconBOT
snow warren
#

its about multiplayer

#

i want to know how to start

#

but first want to know what it is actually

wintry quarry
#

"multiplayer" is quite vague

#

Multiplayer just means a game with more than one human player.

snow warren
#

i heard that servers are costy

wintry quarry
#

Why are you jumping to "servers are costly"

#

You can make it peer to peer or use distributed authority

#

dedicated servers are not the only option

snow warren
#

i am new
i did my research

#

but i still have my doubts and incomplete info

wintry quarry
snow warren
#

like what is the difference between dedicated server, server hosting, multiple server hosting and peer to peer connection

snow warren
#

so i thought this place would be ok

wintry quarry
#

That's networking

#

And networking is certainly NOT a beginner topic

snow warren
#

can we port over?

verbal dome
hybrid tapir
#

how do i play an animation clip in code? like
if (input.getkey(keycode.e)) {
animClip.Play();
}
something like that

wintry quarry
mighty compass
#

Hello good people, I'm having great troubles, and have been struggling with this issue for awhile in Unity. It seems that I cannot nail down getting smooth camera movement with player movement, specifically in fps. I got fed up of reading the docs trying to figure it out, and asked chatGPT, but it wasn't able to come up with a working solution for me.

wintry quarry
mighty compass
#

So all movement is smooth, but as soon as I attempt to rotate the player/camera by moving the mouse, everything looks jank, and as if it's lagging behind

#

I think the camera is updating its position too many times in relation to the RB, and this is causing it to jump around

wintry quarry
#

Isn't it just a child of the player?

mighty compass
#

I'm pretty good at Java, javascript, HTML, CSS, but I'm new to C# as hindsight

wintry quarry
#

Second - because you';re doing this:

playerObject.transform.Rotate(0, mouseX, 0); // Horizontal rotation on player.```
You are breaking your Rigidbody interpolation
#

so that will immediately lead to jitteriness

#

you should never touch the Transform of a Rigidbody directly

mighty compass
#

yes, I assumed I had to move the camera seperately from the RB in order to prevent x axis rotation of the RB

#

ah

wintry quarry
#

To fix the Rigidbody interpolation issue you can replace that rotation code with:

rb.rotation *= Quaternion.Euler(0, mouseX, 0);```
#

You'll also want to double check that interpolation is enabled on your Rigidbody

mighty compass
#

I also usually use notepad++ and I find visual studio really annoying because it keeps formatting my code and doing stuff for me lol, know how to disable it?

#

Thankyou

#

I just dont want my entire playermodel to rotate on the x axis, is the only thing, that's why im doing it to the camera only

wintry quarry
mighty compass
#

I have

short hazel
mighty compass
#

Ill try your fix

#

It's just basic stuff like this: private void UpdateCameraPosition() { cameraObject.transform.position = playerObject.transform.position + new Vector3(0, headAdjustmentMeasurement, 0); }

#

I would write this to look cleaner imo like: private void UpdateCameraPosition(){ cameraObject.transform.position = playerObject.transform.position + new Vector3(0, headAdjustmentMeasurement, 0); } xD

mighty compass
#

Just how I'm used to it in Java

wintry quarry
#

I do the same

#

it's K&R style

#

(I'm also an ex-Java dev lol)

mighty compass
#

KK, I'll find where to disable that

short hazel
#

Yes this can be configured

mighty compass
#

lol nice

short hazel
#

Settings > Text Editor > C# > Code Style
or something

mighty compass
#

Thankyou, I actually spent a lot of time searching for it before, and couldn't find it xD

#

What's the option that automatically fills words for you, sometimes I will have a Class name with a keyword in it, and it tries to fill my code with my classname instead, when I'm trying to use the keyword.

wintry quarry
#

Intellisense

mighty compass
#

is it "Word Based Suggestions in files handled by TextMate grammars"?

#

kk

short hazel
#

Intellisense code completion
As long as the name you type is cased roughly identically to the keyword, it'll prioritize the correct one

mighty compass
#

It seems to be broken for me xD

short hazel
#

If you have a class Int { } and type "Int", it's going to prioritize Int over int because it's closer

#

Don't name types the same as keywords or common identifiers

mighty compass
#

I don't, but sometimes I will have a keyword in a class name like for example IncrementPlayerInt or something, and it'll just keep suggesting it lol

short hazel
#

It also bases itself on usage, stuff you used before will appear more frequently. Not sure if there's a way to change that behavior

mighty compass
mighty compass
#

Because I'm quite new to programming, I've only been studying it for about a year, year and a half

#

So the extra reps of typing helps me consolidate it

wintry quarry
mighty compass
#

Not sure how to fix that

#

Maybe if I interpolate the camera position update?

#

I'll just mess with this, and come back if I hit another brick wall lol

dusk agate
#

Wello, does anybody know how to call a function of a certain preset from another script?

polar acorn
dusk agate
#

Well I have presets that spawn and I want to have it so when I click on one it gets selected

polar acorn
#

Still not sure what you mean by "preset"

#

Do you mean prefab?

wintry quarry
dusk agate
polar acorn
dusk agate
#

The one the code detects I clicked on, but most I can figure out is that it knows it's name

polar acorn
dusk agate
eternal falconBOT
nocturne kayak
#

I have a script to create a plane when a player clicks an object, and raycast from the camera to mouse position checking fo collisions on that plane

#

However, it's never registering collision

#

Can anyone take a look to see what might be the problem here?

dusk agate
# polar acorn Show !code
using UnityEngine;
using UnityEngine.InputSystem;

public class InputHandler : MonoBehaviour
{
    #region Variables

    private Camera _mainCamera;

    #endregion

    private void Awake()
    {
        _mainCamera = Camera.main;
    }

    public void OnClick(InputAction.CallbackContext context)
    {
        if (!context.started) return;

        var rayHit = Physics2D.GetRayIntersection(_mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue()));
        if (!rayHit.collider) return;

        Debug.Log(rayHit.collider.gameObject.name);
    }
}```
polar acorn
#

Get the component you want and call your function on it

vagrant fjord
dusk agate
nocturne kayak
verbal dome
vagrant fjord
#

just figured it out, but the particles arent displaying

verbal dome
#

Still, show code

vagrant fjord
#

kk

sullen perch
#

SO i have this script here, i was following a tutorial and for some reason its wrong, can somewone help?

polar acorn
slender nymph
#

you also appear to be using variables that simply do not exist in the code

sullen perch
#

oh

#

ok thx

verbal dome
#

The ray that ScreenPointToRay gives is on the camera's near clipping plane, not (always) exactly on the camera

#

And the direction is not always the camera's forward, unless if it's an orthographic camera I guess

#

Have you confirmed that the raycast code is running?

#

Okay your issue stems from here:cs initialMousePosition = Input.mousePosition; // ... dragPlane = new Plane(targetObject.transform.up, initialMousePosition);
Input.mousePosition is in screen space but you are using it for a world space plane

vagrant fjord
#

update, i made 2 enemies but only one is displying [aticles

verbal dome
#

Is HitParticle a prefab or an object in the scene?

#

And what logs do you get when colliding with the enemy that doesn't display particles?

#

Including errors

nocturne kayak
mighty compass
#

https://gdl.space/rekupufowi.cs Okay, I interpolated my camera for smooth movement, and I can see it coming out of the player model, and the playermodel sortof glitching all over the place while moving, not sure why

verbal dome
mighty compass
#

First Person

#

Just getting the basics down, the movement is so jank, it looks like the player model bounces back and fourth

verbal dome
#

I don't see why you are lerping the camera position in UpdateCameraPosition

mighty compass
#

I don't need to, I know

verbal dome
mighty compass
#

xD

#

I wanted the camera stable so I could sortof see what's going on

#

And now I can, and I see the playermodel glitching back and fourth really quickly when moving in one direction (the shadow)

verbal dome
#

Is there a reason to have the camera and playercamera objects separately?

#

Also a video of the issue would help

mighty compass
#

playerCamera is the camera, player is the player object/model

#

kk

verbal dome
#

Ah, I just saw MainCamera and thought that's used here too

#

Btw this will break interpolation IIRC: ```cs
rb.rotation *= Quaternion.Euler(0, mouseX, 0); // Horizontal rotation on player.

mighty compass
verbal dome
#

rb.MoveRotation would respect interpolation

#

If you want to continuously rotate a rigidbody use MoveRotation instead, which takes interpolation into account.

mighty compass
#

eventually I'd like to make it multiplayer, so each player object is spawned in with their own cameras, I know I'm very new, but just for possibilities in the future

#

okay, thankyou

verbal dome
#

Try commenting out the whole rb.rotation = code for a moment, see if it still jitters when you walk

livid gale
#

Hello. I am trying to use this script to control a character in 1st person 3d with player input. But for some reason no button works despite no error in the console. Player object looks like this.

slender nymph
#

dang is the bot dead

polar acorn
#

Bot is kill

verbal dome
polar acorn
verbal dome
mighty compass
verbal dome
#

Although I'm not sure if you really need to rotate a capsule

mighty compass
verbal dome
#

Yeah was about to say, you could just rotate the player graphics separately, have them as a child

#

In case the rb rotation doesn't work properly/smoothly

mighty compass
#

I was going to make a shooter, and I wanted hit boxes to be somewhat accurate

#

so I would want the objects to rotate

#

I think that's how you would do it?

livid gale
slender nymph
verbal dome
#

(FPS game)

#

This way I have full control over the rotations and they won't interfere with each other

mighty compass
#

just the playermodel rotation

livid gale
verbal dome
#

I just checked and I do rotate the rigidbody, although I probably don't have to

slender nymph
mighty compass
#

I'll keep at it, I'm attempting to make a game with similar core mechanics to Rust eventually

jagged coral
#

Is line 5 creating an instance of the ScoreManager class above it and just naming it instance?

livid gale
mighty compass
#

Looking at rust, I'm like how the hell did they manage to do all of this

slender nymph
slender nymph
livid gale
#

So do I share a link of it instead?

slender nymph
#

considering that is the only instruction for sharing large blocks of code, obviously yes

jagged coral
#

cool thank you :)

languid spire
livid gale
livid gale
slender nymph
#

next time try reading the instructions provided instead of skipping over literally the part that was relevant to you

jagged coral
livid gale
mighty compass
#

Are there any examples of large unity game projects out there? With access to the project. I'm curious how developers organize all of their scripts and assets, and also how they write scripts for different objects.

livid gale
#

I see the entire code when I sent it here

slender nymph
livid gale
slender nymph
languid spire
mighty compass
#

I'm just sortof clueless when it comes to organizing a large project

livid gale
slender nymph
#

This server has guidelines for a reason, don't bitch when someone points them out to you.

livid gale
jagged coral
#

dude, why are you being condescending ot people in code-BEGINNER

#

not fucking code-expert

slender nymph
polar acorn
#

No one's expecting people to be good at code but reading instructions should be pretty easy

jagged coral
#

i just don't think it's nice to be condenscending to people trying to learn something new is all

#

doesn't help anyone

polar acorn
mighty compass
polar acorn
slender nymph
languid spire
polar acorn
mighty compass
languid spire
verbal dome
#

If you lack the experience to design it beforehand then you just have to go with trial and error

polar acorn
#

Zero planning is actually better than poor planning

polar acorn
#

If you don't know enough to do it right, you'll cause more damage than you'll fix

mighty compass
#

I was basically asking, so that I don't develop any bad design habits

#

To see if there's conventions of project organization to follow or something

slender nymph
mighty compass
#

How do you guys usually design your code structures before writing them? Do you write them out on paper, or like type up a pseudo code block example?

livid gale
#

When am I allowed to repost my request?

hollow slate
#

learning when to do what comes down to experience

polar acorn
#

You give me far too much credit

hollow slate
#

so start doing!

mighty compass
#

I see 😂

polar acorn
#

I just winchester mansion scripts into being until I eventually finish the project or abandon it

mighty compass
#

Thankyou guys

polar acorn
#

||usually the latter||

polar acorn
steep rose
#

if not then i go back to planning, or fix my trash code

livid gale
#

Hello. I am trying to use this script to control a character in 1st person 3d with player input. But for some reason no button works despite no error in the console. Player object looks like this. And script is: https://hastebin.com/share/xujuzimaha.csharp

mighty compass
steep rose
mighty compass
steep rose
polar acorn
eternal needle
mighty compass
steep rose
#

im currently working on a A* pathfinding type thing

#

so i kinda have to do this

livid gale
polar acorn
livid gale
polar acorn
#

There's a lot of ways to interact with the new input system. Polling, events, messages, bindings

polar acorn
#

to choose which function it calls in the inspector

#

I don't remember what it is called

#

But it's something in that dropdown

livid gale
polar acorn
#

Events are the usual way to use the new input system. Polling is basically just what the old Input Manager does, and should probably be avoided

hollow slate
#

New input system has a suprisingly high bar. It's not easy to use if you're new to Unity...

livid gale
hollow slate
sullen perch
#

Ik iv asked this before but i realy need to know how i can change nthis script so that when i collect all 25 start captuals, it changes scene.

livid gale
hollow slate
#

there are many ways of doing this.
I would suggets searching for a tutorial on Youtube.
Maybe something like "Unity, collect system".

#

actually I think CodeMonkey has a good one

#

watched it long ago

sullen perch
#

I have looked for tutorials but nothing works

steep rose
#

use a list or array

#

ah nvm not useful for this case

sullen perch
#

i have to have it done in 30mins, how would i go aboutusing a list?

steep rose
#

what doesnt work with the script you have now?

#

just check if Coin is higher than a threshold then change scene

sullen perch
#

im realy new to unity, how do i do that?

slow hollow
#

wouldnt it should be if 25 =25 then change the scene?? ohh btw put this code when coin gets collected

devout flume
#

Is it possible to have a BaseMaterial, whose color is ffffff, and then apply this material on different rendered gameObjects, and be able to change each object's colors without having to clone the said material?

steep rose
sullen perch
#

thx

#

so do i put 25 in the threshhold?

slow hollow
steep rose
#

so make a variable for it and change it in inspector

hollow slate
sullen perch
#

oh, ok

steep rose
ember tangle
#

my command pattern is making the player movement sluggish when there is a lot in the buffer from AI movement commands, is their an elegant solution to this?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

sullen perch
#

ok

slender nymph
# devout flume Is it possible to have a `BaseMaterial`, whose color is `ffffff`, and then apply...

if you want to change the color on a single object then you will need to instantiate its material so it does not affect the other objects using the same material. getting its renderer.material will automatically instantiate the material. or you can do it manually using Object.Instantiate
(this information is assuming you want to do this at runtime, edit time requires separate material assets)

hollow slate
#

I don't think that's where your issue is though, unless you've already optimized like crazy.

slow hollow
steep rose
devout flume
devout flume
verbal dome
#

Though the doc of MaterialPropertyBlock says something about it not being too performant with SRP, but it's worth checking out

ember tangle
verbal dome
#

It also sounds a bit like your movement depends on framerate

steep rose
#

quake all over again

hollow slate
verbal dome
#

It's usually an easy fix

devout flume
# verbal dome Though the doc of MaterialPropertyBlock says something about it not being too pe...

My main project is to make a creation game in which you would be able to position elements around, change a lot of properties I define. Color is one of them. I developed the project in ROBLOX to realize that the platform kind of sucks, specifically when it comes to the physics engine, and I'm not even talking about the overall way the platform treats developers. Trying to see if Unity is a good choice but it's definitely not the same ideology behind 😅

#

Thank you for your help

steep rose
#

or deltatime for other movement method other than RB

#

depending on what you are doing ofc

ember tangle
# verbal dome It also sounds a bit like your movement depends on framerate

fps is 200 - 400, the command itself is very simple ```public class MoveDirection : ICommand
{
Vector3 direction;
Entity entity;
public MoveDirection(Vector3 direction, Entity entity)
{
this.direction = direction;
this.entity = entity;
}
public void Execute()
{
entity.rigidbody2d.AddForce(direction);
}

}```

steep rose
#

deltatime isnt framerate dependant afaik

verbal dome
#

Well you'd normally only use deltaTime (fixedDeltaTime) with MovePosition or rb.position, not with forces or velocity

#

Since addforce already uses deltatime by default

steep rose
slow hollow
steep rose
#

im not saying use deltatime for forces, im saying use it other than RB movements so like Move() or something along those lines

devout flume
#

Thanks a lot, I really appreciate it ! VaroHeart

slow hollow
steep rose
#

I cant promise that, as I am away sometimes

verbal dome
#

Yeah I won't promise I'm here for long, but probably again tomorrow

ember tangle
# verbal dome Is execute called only once?

This is what the command invoker looks like: ```public class CommandInvoker : MonoBehaviour
{
private static Queue<ICommand> commandBuffer;

void Awake()
{
    commandBuffer = new Queue<ICommand>();
}

void Update()
{
    if (commandBuffer.Count > 0)
    {
        ICommand command = commandBuffer.Dequeue();
        command.Execute();
    }
}
public static void AddCommand(ICommand command)
{
    commandBuffer.Enqueue(command);
}

}```

devout flume
#

Yes for sure ! I ofc expect you to have lives, that's completely normal. You're kind enough to help people, that's already a huge thing

verbal dome
slender nymph
#

the only time AddForce should be called in Update is when it is a one-off Impulse force

steep rose
#

just look at quake for example and what framerate dependency does to games

verbal dome
#

It's a decent idea to keep your AI stuff in fixedupdate anyway, althought I've never seen anyone mention it except me

#

Or your own update loop but that's more complex

ember tangle
# verbal dome It's a decent idea to keep your AI stuff in fixedupdate anyway, althought I've n...

hmm. I do have the AI get the command through a fixed update: ```private void FixedUpdate()
{
foreach (var entity in entities)
{
//get cell where entity is at
Cell currentCell = flowField.GetCellFromWorldPosition(entity.transform.position);
//get move direction from flow field cell
Vector3 moveDirection = new Vector3(currentCell.bestDirection.direction.x, currentCell.bestDirection.direction.y, 0);

    ICommand command = new MoveDirection(moveDirection * 1000f * Time.deltaTime, entity);
    CommandInvoker.AddCommand(command);
}

}```

verbal dome
#

Yeah that doesn't help if you're executing it in Update

ember tangle
#

the thing is the movement works perfect when I apply the AddForce at the keypress

#

it just doesnt work as a command

verbal dome
#

Not directly related but worth mentioning that by default, AddForce will already be multiplied by fixedDeltaTime

#

So you have some redundant multiplications there

ember tangle
#

Do I need a seperate command invoker for player inputs? I dont want to do an anti-pattern with the commands.

verbal dome
#

Can't you execute the command from FixedUpdate instead?

#

Or if you need some commands to be executed in Update then you could have two different commandbuffers

#

Btw are you doing flowfield pathfinding or something? For an RTS?

ember tangle
#

I do have flowfield pathfinding in the project for now. its a roguelite that may have a lot of enemies / pathfinding projectiles etc

verbal dome
#

That's fine in FixedUpdate, because deltaTime actually returns fixedDeltaTime, which is constant, when in FixedUpdate

#

But in Update it will change with your framerate

#

I must say I have never seen the command pattern used for continuous movement 🤔

mighty compass
#

delta time so far has never seemed to fix a single one of my issues

#

It seems almost useless

silk night
mighty compass
#

I think just using the update functions correctly will eliminate the need for delta time. I also know nothing about this editor so far though lol

verbal dome
mighty compass
#

Can barely get smooth movement

verbal dome
#

Top 2 things you shouldn't use deltaTime with is mouse input and forces

mighty compass
#

Like what does it do

verbal dome
#

Want to add 1 to a float over 1 second? Add Time.deltaTime to it in each Update

mighty compass
#

Doesn’t just give you the time in seconds from the last frame?

#

I see

verbal dome
mighty compass
#

Ah

verbal dome
#

If the frame took longer to finish then deltaTime will be greater

#

So it will account for that

mighty compass
#

That’s pretty cool, but isn’t the update function supposed to do that anyways?

#

It occurs every frame?

verbal dome
#

Nope, it just runs each frame

mighty compass
#

Ohh I see now

#

So it keeps track of calculations regardless of the frame rate

#

So if there’s massive frame drops, there’s no lag in calculations or logic that would’ve occurred

verbal dome
#

Lets say you add 0.1f to your float each update
If you have 10 fps then it will take 1 second to reach 1
If you have 100 fps then it will take 0.1 seconds

mighty compass
#

Ah

#

So it’s useful for server side logic, or anything where your client has to keep track of things over realtime basically

#

Man there’s so much I don’t know about these engines xD

verbal dome
#

Not sure about that. Pretty sure that server side logic happens at fixed intervals

#

But I'm no networking expert

primal halo
#

can someone help me im having issues

astral falcon
rich adder
primal halo
#

oops

#

pl

#

ok

ember tangle
pastel knot
#

Thread

verbal dome
#

Forgot to mention that you should probably do HandleInputs in FixedUpdate too, so you don't get multiple move commands for one physics frame

#

But your issue might be something else

acoustic arch
#

planning to make a 2D story game with a general map, and buildings to enter in etc

#

is it recommended i use scenes to travel between these events or should I just manage what in game event is going on based on code and have the master scene control everything?

rich adder
glad ferry
#

im trying to learn unity, Im having a hard time finding good ways to learn though because on youtube it shows how to write the code but its difficult to not just copy it and find a way to test yourself, does anyone know of any rescources on how I can actually learn instead of just copying

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ripe shard
glad ferry
#

@languid spire thank you but is there any others? I have tried that before but I dont love it, due to the website

pastel knot
#

Hey, I'm planning to change the serialization method of data in one of my data types. The data type is used in several prefabs, and I want to maintain the data in the changing format. Is there any straightforward way to do this?

glad ferry
#

@ripe shard thank you

ripe shard
pastel knot
#

Set yourself a goal (a game you want to

#

This allows you to intercept

gaunt solstice
#

Hello, I'm using the code below on an enemy in a game I'm making so that it will walk to random points forever until it spots the player, but I was wondering if anyone had any ideas for making this a bit more realistic. It doesn't need to be anything crazy but right now there are many instances where it will just keep walking back and forth and I want it's path to be a bit more realistic than that

    {
        Vector3 randomPoint = center + Random.insideUnitSphere * range;
        NavMeshHit hit;

        if (NavMesh.SamplePosition(randomPoint, out hit, targetDistance, NavMesh.AllAreas))
        {
            result = hit.position;
            return true;
        }

        result = Vector3.zero;
        return false;
    }

    void Patrol()
    {
        if (agent.remainingDistance <= agent.stoppingDistance)
        {
            moveRange = Random.Range(2, 5);

            if (RandomPoint(transform.position, moveRange, out point))
            {
                targetPos = point;

                agent.SetDestination(point);
                Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f);
            }
        }
    }```
slender nymph
#

define "realistic"

steep rose
#

you mean you wait before you go to another point?

#

do you want the enemy movement slower when patrolling?

#

give details

gaunt solstice
#

well realistic was a poor choice of words

rich adder
#

give your enemy some random times to pause and do something else instead of just hitting each point like a clock

teal viper
#

Make it go grab a coffee every now and a while to make it more realistic.

rich adder
#

one my enemy reaches a patrol point it usually looks around, picks a random look at target and IK turns its body or does something before going onto next point

verbal dome
#

I did that just recently

steep rose
#

i am in the making of a custom navigating enemy and what i do is it just to stay still for 5 seconds

#

then to go to another point

gaunt solstice
#

since the point where it will walk appears at a random point within a certain radius from the npc, sometimes those points will appear directly behind it and it'll do a full 180 and walk towards it, and then do it again so its just walking back and forth. so I mainly just want points to not appear directly behind it that much

verbal dome
#

Pauses do sell it quite well, but turning around constantly can still look a bit odd

rich adder
teal viper
verbal dome
steep rose
#

you could just make it so it cannot pick the previous point twice

#

i mean you could also increase resolution of points so it practically cannot create the same point twice 🤷‍♂️

rich adder
gaunt solstice
#

yeah since they're random and the enemy keeps moving it's already extremely rare it'll hit the same point twice

verbal dome
#

Theres a very small chance that it would pick the same point, its using insideUnitSphere

steep rose
verbal dome
#

Hence the suggested angle/dot product check

steep rose
#

wdym which resolution

rich adder
#

you said "resolution of points"

verbal dome
#

Yeah it's not on a grid, the resolution is "infinite" or as large as floating points allow

steep rose
rich adder
#

limit which ones would get added as possible

verbal dome
#

I use a custom A* for this that has a higher "cost" for points you recently visited

steep rose
rich adder
#

indeed. done it before, I'm sure it works

#

a while loop and enough of a high number for "maxTries" just incase something goes wrong :p

gaunt solstice
steep rose
#

vector.dot

rich adder
#

generate a point, check the dot if its within range add it to the possible points. If not keep iterating

verbal dome
#

Yeah compare the dot product of (playerPos - lastPos).normalized and (playerPos - randomPos).normalized

#

If it's too high (say, over 0.5) then generate another point

rich adder
#

sorry poor drawing skills lmao

verbal dome
#

You can also use Vector3.Angle instead of Vector3.Dot if that's more clear to you

gaunt solstice
#

thank you, i will try some of these out

rich adder
# gaunt solstice thank you, i will try some of these out

you see the blue is the number on the right, the dot product cs float dot; Vector3 dir; private void Update() { if (target == null) return; dir = (target.position - transform.position).normalized; var forward = transform.forward; dot = Vector3.Dot(forward, dir); }
closer to 1 = infront / closer to 0 = sides and anything below 0 is behind
replace the target.position for the generated point and do the rest based on dot or angle

steep rose
#

what is on the right side of your screen ❓

rich adder
#

playing around w shaders

steep rose
#

thats some cool color banding

rich adder
timber tide
#

circle pixels

rich adder
ashen frigate
rich adder
ashen frigate
#

ive ask gpt for that function so i have no idea how AnimatorStateInfo works

rich adder
#

it tells you info about the current state lol

ashen frigate
#

im using changeAnimationState mostly

rich adder
#

aka animation clip inside the animator

ashen frigate
#

to play the animation

rich adder
#

also probably better to learn this stuff instead of gpt

#

this part looks sus && stateInfo.normalizedTime >= 1.0f;

steep rose
rich adder
#

well maybe it works but I only needed to check the name in update, I suppose that gives extra check

steep rose
#

my AImeter was ticking

rich adder
#

the idea is somewhat correct, the execution is mid

rich adder
#

you would have to check if those are even hitting / waiting

#

combination of checking animator and prob putting it into a bool you can debug

ashen frigate
rich adder
#

nothing to do with animations, Im talking about code

ashen frigate
#

yea working with the code animation is so confusing

rich adder
#

also possiblity to just use animators built in exit states from FSM

#

or Animation Events

steep rose
#

if you do, then it wont

mighty compass
wild raptor
#

can someone help me, i cant get the unity 2d grid to show and nobody knows why it isnt showing

wild raptor
nocturne kayak
#

Hitting on a (you got it) bit of snafu

#

I have a script that creates a virtual plane, and i should be able to drag an object along that plane

#

I want it to only be able to be dragged in one axis, so, in all of my wisdom, implemented Vector3.Project

#

However.

#

!code

eternal falconBOT
nocturne kayak
#

This is the script running on that

#

Thing is, if at line 54 i replace "Vector3.Project(hitPoint, transform.up);" with just hitPoint, it drags fine, just not on that axis

#

So, what am i not getting about the Vector3 Project?

teal viper
nocturne kayak
#

Huh

#

How should i proceed then?

teal viper
#

You could transform that point into the object local space, project it on the direction vector, then inverse transform it back into world space.

#

Or just assign it to transform.localPosition instead of the last step

#

Though, you might need the direction vector to be in local space as well🤔

#

Don't have much time to think about it.
You should do some math/ sketching on paper before actually writing the code.

nocturne kayak
#

Yeah

#

I'm trying to look into TransformPoint but no luck there

#

I'll try editing that tomorrow

hybrid gust
#

is mouse delta supposed to stop working when the mouse winds up at the edge of the screen?

hybrid gust
pliant pecan
#

how do i make a two dimensional array with x rows and y columns?

private int[,] layout = new int[x,y];

This doesn't seem to be working...

pliant pecan
#

It's only making two rows, but the number of columns is right

teal viper
pliant pecan
#

uh oh

#

maybe my printing code is wrong

#
    private void PrintGrid()
    {
        string line = "[";
        for (int i = 0; i < rooms*2; i++)
        {
            //print("i" + i);
            line += "" + i + ":[";
            for (int j = 0; j < rooms * 2; j++)
            {
                //print("j" + j);
                line += layout[i, j] + ",";
            }
            line += "]\n";
        }
        line += "]";
        Debug.Log(line);
    }
#

trying to print the whole array into the debug console, only two lines show up

#

dog

#

can i be so real

#

the editor only shows two lines

#

after i clicked on it you can see all the lines

#

i've been on this for 15 minutes

#

thank you

#

😭

teal viper
# pliant pecan

Good opportunity to discover that error and info messages have more info than you can see in the list.

near wadi
#

🤦‍♂️ today is the first time i've used the VS 'Code Cleanup' button. would not have minded utilizing it earlier

north kiln
#

I'm constantly hitting the reformat button in Rider

cloud oak
#

Thanks

swift elbow
eternal falconBOT
cloud oak
#
    {
        if (lastTemperature1 != null && lastTemperature2 != null)
        {
            // Check if lastTemperature1 is colder than lastTemperature2
            if (lastTemperature1 > lastTemperature2)
            {
                // Change the LineRenderer's material to reflect cold temperature
                lineRenderer.material = coldMaterial;
            }
            else
            {
                // Change the LineRenderer's material to reflect warm temperature
                lineRenderer.material = warmMaterial;
            }
        }
        else
        {
            // If no temperature data is available, use the default material
            lineRenderer.material = defaultMaterial;
        }
    }```
#

Is this right way to change line renderer material in run time?

teal viper
near wadi
#

#💻┃code-beginner message Oh, i love the Format Document option and use it regularly. 🙂 differently, this particular Code Cleanup button follows preset, definable rules, and in this case just removed the unused usings at the top. it can do much more, but that was all this particular file needed

cloud oak
#

It is displaying 3rd material only

teal viper
cloud oak
#

I have 3 material to choose from

#

I have assigned them respectively and it always shows the index 2 material

teal viper
#

Where does it show it? Does your code actually run?

cloud oak
#

Taking inputs

teal viper
#

What inputs? I don't see any inputs in that code? How do you know that the shared code is running?

cloud oak
#

Can I share my log

teal viper
#

Sure. Follow the !code sharing guides

eternal falconBOT
cloud oak
#
UnityEngine.Debug:Log (object)
BallController:UpdateMaterialBasedOnTemperature () (at Assets/hehe/BallController.cs:129)
BallController:TracePath () (at Assets/hehe/BallController.cs:119)
BallController:FixedUpdate () (at Assets/hehe/BallController.cs:52)

Drawing with warm material.
UnityEngine.Debug:Log (object)
BallController:UpdateMaterialBasedOnTemperature () (at Assets/hehe/BallController.cs:145)
BallController:TracePath () (at Assets/hehe/BallController.cs:119)
BallController:FixedUpdate () (at Assets/hehe/BallController.cs:52)

Collided with ice cube. Temperature: 99
UnityEngine.Debug:Log (object)
BallController:OnCollisionEnter (UnityEngine.Collision) (at Assets/hehe/BallController.cs:63)
UnityEngine.Physics:OnSceneContact (UnityEngine.PhysicsScene,intptr,int)

Both temperatures already assigned.
UnityEngine.Debug:Log (object)
BallController:OnCollisionEnter (UnityEngine.Collision) (at Assets/hehe/BallController.cs:82)
UnityEngine.Physics:OnSceneContact (UnityEngine.PhysicsScene,intptr,int)```
#

It says drawing with warm material

#

I think I did something stupid somewhere along the environment

teal viper
#

Where is that log printed from? I don't see it in your shared code.@cloud oak

cursive ice
#

Hey can someone help me with my code? its not working for some reason.. (its my first day)
I can screen share it
but i asked someone else who doesnt use unity and he said it looks like the code doesnt exist
so if anyone wants to hop on call and help me that would be appriciated :D

near wadi
#

a recap of what was said in the General room

vagrant fjord
#

my project got corrupted, whole scene is gone but the code is still there. any help to recover?

north kiln
#

Don't open the project, if you do there is no path to recovering the scene

cursive ice
near wadi
cursive ice
teal viper
near wadi
teal viper
near wadi
#

!code

eternal falconBOT
cursive ice
#

wait how do i sent it in the black background

near wadi
#

follow the bot message

north kiln
cursive ice
#

ok tysm!! <3

vagrant fjord
#

hello, just fixed my scene and now have another issue lol

night valve
#

Wouldn't using revision control help with such issues like missing scene?

vagrant fjord
#

my animation isnt speeding up and i have tried speeding it up in animator and actually making the frames closer together. any help?

near wadi
night valve
fiery plume
#

Using the line renderer i have drawn Lines. The line renderer is on a UI Object in the Canvas and i want the lines to either follow the camera or the object its attached to but if i turn off world space the lines will no longer render.

cursive ice
# teal viper You'll need to explain the issue better and provide the relevant code.

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
private RigidBodt2D rb2D;

private float moveSpeed;
private float jumpForce;
private bool isJumping;
private float moveHorizontal;
private float moveVertical;

// Start is called before the first frame update
void Start()
{
    rb2D = gameObject.GetComponents<Rigidbodt2D>();
    moveSpeed = 3f;
    jumpForce = 60f;
    isJumping = false;
}

// Update is called once per frame
void Update()
{
      moveHorizontal = Input.GetAxisRaw("Horizontal");
      moveVertical = Input.GetAxisRaw("Vertical");
}

void FixedUpdate()
{
    if(moveHorizontal > 0.1f || moveHorizontal < -0.1f)
    {
       rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
    }

}

}`

languid spire
#

Rigidbody2D not Rigidbodt2D

cursive ice
#

oh wow.. just a simple typo..

languid spire
#

if your ide did not highlight this you need to configure it

cursive ice
#

Thanks so much steve!

#

Im not really sure what this means..

#

This is my inspector

north kiln
#

these scripts can't be found, if you're not using whatever was here any more you should remove them

cursive ice
north kiln
#

If you're not seeing errors underlined in red and autocomplete then you need to configure it

#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

north kiln
#

Warnings and errors in Unity are generally unrelated to IDE setup

languid spire
#

did you look at the TryGetComponent docs?

night valve
#

To specify the type for generic method you need to place it <here>(before regular parameters)

fervent abyss
#

hell no i js noticed i put () instead of <> 💀

hollow quest
#

do I just follow docs or there better source for learning like in youtube?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hollow quest
teal viper
static cedar
#

I'd suggest to use docs once you understand basic concepts.

#

Use tutorials to properly get started first.

hollow quest
#

🫡

sand snow
#

um i need help

kind rover
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;

public class Tile : MonoBehaviour
{
    List<GameObject> hitCollider;
    int x=0;
    // Start is called before the first frame update
    void Start()
    {
        hitCollider= new List<GameObject>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter(Collider other) 
    {
        if(this.name=="Tile")
        {
            //x++;
            //Debug.Log(""+other.name);
            hitCollider.Add(other.gameObject);
            /*if(x==4)
            {
                foreach(string c in hitCollider)
                {
                    //Debug.Log(""+c);
                }
            }*/
        }
    }
    public GameObject[] Collisioni()
    {
        return hitCollider.ToArray();
    }
}

PlayerManager.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter(Collider other) 
    {
        GameObject[] collisioni=other.gameObject.GetComponent<Tile>().Collisioni();
        foreach(GameObject col in collisioni)
        {
            Debug.Log(""+col.name);
        }
    }
}

#

Guys am having a strange issue with my code, basically my PlayerManager code calls the function Collisioni() from Tile.cs when it touces the tile and should return an array containing the object that that object is touching, but it only returns half of what is touching. I already tried debugging and the results are:
if i try to print the elements of the list at the end of OnTriggerEnter of Tile.cs it gives all the collisions ( is 4 object in this case), but when i print on Collisioni in Tile.cs it only gives me 2 of them.

sand snow
#

whenever i try to make a new script it cant open, and im pretty sure its because unity cant find my visual c++

astral falcon
sand snow
#

no it just says "check external application preferences"

#

and when i got to preferences i see the thing to change it to visual c++ but visual c++ isnt an option

#

the only option is "open by file extension"

astral falcon
kind rover
#

i thought of that and i tried to do a while statement in the Collisioni function while(hitCollider.count<2){ Debug.Log("waiting") }
but it just gives an infinite loop

sand snow
#

should i just delete unity and visual c++ and just reinstall? i feel like there has to be a better way to fix this

astral falcon
astral falcon
#

Did you install it with unity hub along with a unity version?

kind rover
#

isnt it what am doing? passing the collisions of the tile through Collisioni() ??

sand snow
kind rover
#

oooh you mean that

#

i did that before and gives the same issue i switched up to gameobject to see if it was a problem of collisions

astral falcon
# kind rover isnt it what am doing? passing the collisions of the tile through Collisioni() ...

Physics system is firing both ontriggerenter at no specific order, so you dont know, when the actual collision gets added. The tile should call the player, not the player ask the tile on its own collision detection. Lets say, player hits tile (collision 0 happens) and gets the collions of the tile, its 1, but then the tile progresses its own ontrigger check and adds to the list, but the list has already been fetched by your player.

#

Not sure its clear. The player got the current list before your tile was able to add and check its own collisions. shorter version 😄

languid spire
#

Also, the List is only created once and added to, so the count will increase with each Trigger

kind rover
#

yeah but by adding a while statement inside Collisioni() in Tile.cs shouldnt it wait until for example hitCollider.Count > 2 so for atleast this case should give me all 4 collision

#

but it just gives an infinite loop

astral falcon
kind rover
#

like this for example

#

in this case the collision are 4 so it shouldnt give an infinite loop

#

i did this and it shows me that it prints the results before it could even insert the collisions in the list

#

so the issue is that

#

the first 2 logs in the console are the Debug.Logs of Player.Manager

#

is there a way to make the playerManager wait or should i approach it in an other way

sand snow
#

@astral falcon I ended up fixing it somehow thank the lord

#

i just started unity literally yesterday and everything is so overwhelming

astral falcon
sand snow
kind rover
#

in VS code?

sand snow
#

yeah

kind rover
#

use c# and unity and unity snippets extension

hexed terrace
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

hexed terrace
sand snow
astral falcon
kind rover
#

what if i use a boolean in Player where it only call the function Collisioni when its true , and the bool its true only once all the collision of Tile are stored in the list?

#

but at this point i should use OnCollisionStay instead of OnTriggerEnter

#

it works now like this @astral falcon thanks for help ❤️

#

just asking but how do i know if an object registred all collisions, cause in this case i said if ontriggerenter has been executed 4 times its all of them but if the collision are 3 or even 5 what do i do

#

whats the condition

neon ivy
#

I'm getting stuck with vectors.
I have a vector which is (moveInput.x,0,moveInput.y).
I'm trying to rotate this vector based on which way the freelook camera is looking, ignoring the y direction.

I tried to do

Vector3 output = Quaternion.AngleAxis(Vector3.Angle(Vector3.forward, new Vector3(mainCam.transform.forward.x, 0, mainCam.transform.forward.z)), Vector3.up) * new Vector3(moveInput.x, 0, moveInput.y);
``` but this doesn't work and starts to mix up controls when the camera is rotated.

I think Vector3.Angle is messing with me but I have no clue how to fix it. anyone know?
echo sand
#

why cant i add my InvSys class?

ivory bobcat
echo sand
ivory bobcat
#

The file name looks correct but if the class isn't the correct type, you'll not be able to drag the file to the inspector field.

languid spire
#

you are dragging the script. You need to drag an instance of the script

echo sand
#

hmm, idk what i did wrong tho

#

ohh

#

mb lol, ty works now

wooden sky
#

any idea why this is happening?

#

the rules do work, but it spawns the whole palette infinitely

wintry quarry
#

This is what I would do^

neon ivy
#

I'm not sure I understand the ProjectOnPlane and LookRotation

harsh wadi
#

Hello folk
My question is about platform jump. When player jump through a platform, it jumps normal but when the player tries to jump through edges of the platform, the player jumps less than normal. I am gonna share the script and an image to clarify it better. Thank you in advance.

{
    public float jumpForce;
    public float jumpSpeed;
    private Rigidbody2D _playerRb;
    private bool _isGrounded = false;

    private void Start()
    {
        _playerRb = FindObjectOfType<Rigidbody2D>();
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Player") && !_isGrounded)
        {
            if (_playerRb.velocity.y <= 0)
            {
                _playerRb.AddForce(Vector2.up * jumpForce, ForceMode2D.Force);
                _isGrounded = true;

                foreach (ContactPoint2D contact in other.contacts)
                {
                    if (contact.normal.y <= 0.5f)
                    {
                        if (_isGrounded)
                        {
                            _playerRb.AddForceAtPosition(jumpSpeed * Vector2.up, _playerRb.transform.position, ForceMode2D.Impulse);
                            if (this.gameObject.layer == 6)
                            {
                                if (TryGetComponent<DestroyBreakFromTop>(out var _destroyBreak))
                                    _destroyBreak.DestroyBreakPLatform();
                            }
                            _isGrounded = false;
                        }
                    }
                    break;
                }
            }
        }
    }
}```
wintry quarry
wintry quarry
harsh wadi
wintry quarry
#

you're adding additional force for each contact in the collision

#

the scenario where you're hanging half off the platform has fewer contacts

#

so less force is being applied

#

You can do Debug.Log($"Contact count: {other.contactCount}"); to check

#

There's also a couple of if statements in there

#

so even if the contact count is the same, sometimes not all the contacts will have a force based on this code

languid spire
#

Also the foreach will only ever run once

wintry quarry
#

Oh yeah true - that's wild

#

it should really just be:

var contact = other.GetContact(0);
// do stuff with it

And get rid of the loop entirely

#

so really what's happening is that the first contact in some of these is satisfying the condition, and in others it is not

harsh wadi
#

ok i am trying

neon ivy
wintry quarry
#

that would be more accurate

neon ivy
#

yep

wintry quarry
#

cool

neon ivy
#

now I can also define up based on a normal vector or the inversed gravity direction to support other surfaces

wintry quarry
#

absolutely!

harsh wadi
harsh wadi
wintry quarry
harsh wadi
wintry quarry
#
int times = 0;

Then every time you add force

times += 1;```
#

then log it at the end

#

or just print each time it adds force and count the logs

languid spire
harsh wadi
shy lichen
#

hello guys i was following tutorial od 2d tilebased rpg and i have 2 problems with my code if someone is free to help.First is my SpriteRenderer doesnt change my weapon sprite and second is my enemy doesnt follow player for some reason but it goes to starting position.

harsh wadi
wintry quarry
spiral narwhal
#

I'm encountering a strange bug where a TextAsset is not null but when accessed, is null.

        Debug.Log(interaction is null); // false -> The base object
        Debug.Log(interaction?.Dialogue is null); // false -> The TextAsset
        Debug.Log(interaction?.Dialogue.text is null); // NullPointerException because Dialogue is accessed, but is null

How is that even possible

shy lichen
# wintry quarry Focus on one problema at a time and share details/screenshots/code

Alirght so i was following this tutorial https://youtu.be/b8YUfee_pzc?si=ueajmC6Q1P0opadU&t=19275 and weapon changes in game manager and as u can see down on pictures it updates.But physical object in game doesnt.

2024 edit!
I've got a new course teaching multiplayer here on youtube! Check it out
https://www.youtube.com/playlist?list=PLmcbjnHce7Scovukpm2UbvBmhPKvM52uD

--- Livestream alert ----
I'm live every Saturday morning, come say hello
https://www.twitch.tv/n3rkmind

This is a full release of an Top Down RPG course made in Unity 2017

Here's a link ...

▶ Play video
spiral narwhal
#

Is None maybe not the same as null?

languid spire
#

so Dialog is obviously null there

wintry quarry
#

use == null

spiral narwhal
#

Ohhh

wintry quarry
#

Same with the ?. operator