#πŸ’»β”ƒcode-beginner

1 messages Β· Page 656 of 1

queen adder
#

😭

#

yea js a box collider to the bullet

meager siren
#

Whats a good way to learn C#. without unity learn. And Youtube Videos that are discontinued. And is there any way to practice unity C# code without having Unity installed?

north kiln
#

The intro to C# link (that's currently under maintanence for me) that's pinned to this channel

#

You need to have Unity installed to program with Unity. But there's nothing stopping you from learning C# without Unity.

bronze sinew
#

i want it to not change so much either pull the player in the direction of the box, or the player pull the box

wintry quarry
#

when objects physically overlap each other, the physics engine tries very hard to disentangle them

bronze sinew
#

Okk

wintry quarry
#

just from this it looks like the two links are inside one another

bronze sinew
#

So If I add some distance between them ? and disable collisions? will it fix it?

#

Tried changing the mass of each chain to 2 now it seems to be working

tight glen
#

does anyone know why the videos all say No compatible source was found for this media.?

wintry quarry
#

Looks like all the videos on Learn are like that. I would just try again tomorrow

#

no doubt someone will fix it soon

tight glen
#

haha thank you

#

I am excited to start learning πŸ™‚

modest harness
#

I'm using UI Toolkit to make 2 menus, each is parented to a GO which get enabled/disabled
And I ran into an issue that the first menu works, but the second doesn't trigger any clicked events (hovers work)
I could not find what is causing it so right now second menu is literal copy of the working one, and this did not change anything.
OnEnable runs fine, OnDisable unsubscribes the listeners, there are no missing references, but click events never trigger

this is killing me what am i missing?? 😭

fair shore
#

Why did i get the Addcomponent asking for invalid type while the "Draganddropscript." exist and also how do AddComponent works?

north kiln
fair shore
north kiln
#

No there isn't

fair shore
fair shore
north kiln
#

That's not a type

#

That's a file name

north kiln
viral shore
#

Hello, sorry for my question but I'm new there. I have a display bug in the hierarchy tab when I want to hide/display a gameobject, the eye icon is locked and I can't display again my gameobject. Do you know the bug?
To fix it I have to delete manually the file "SceneVisibilityState.asset"
But it's an annoying workaround

swift elbow
viral shore
#

do you know how to fix it without deleting the file please?

#

thx

blissful yew
#

What the heck. I have a serialized variable here in a monobehaviour. Nothing is setting the variable except for me, in the editor. But no matter what, it's reading as the default value

#

(happens on Start)

#

this reads as 0 no matter what the slotnum is

frosty hound
#

SlotPosition is not the same as SlotNum? πŸ€”

blissful yew
#

omfg, accidentally added two variables for the same thing

#

.... pls ignore

#

Got confused because slotNum was serialized while slotposition wasn't (forgot the [field: Serializefield]). So my brain conflated them. Everything works now

willow shoal
#

error on getcomponent any ideas?

this.gameObject.GetComponent().material.color = Color.cyan;
#

what add for?private void Start

frosty hound
willow shoal
#

thanks!

polar acorn
nocturne hawk
#

Hi! I need help setting up damage functions for my area of damage BoxCollider2d, but its not working for me from the tutorials I've watched. Im completely new to Unity and have never programmed before this current project

polar acorn
#

Show code, and be a bit more specific about what isn't working about them

nocturne hawk
#

alr 2 sec

willow shoal
#

hi... i add this for my cube on screen, for other cube for change material and still not working :/

 public Material mat;
 public GameObject gameobject1;
 void OnMouseDown()
 {  
     gameobject1.GetComponent<Renderer>().material = mat;
 }
polar acorn
willow shoal
polar acorn
willow shoal
#

and i add difrent color for this

polar acorn
willow shoal
#

is on other cube

polar acorn
#

This one is irrelevant

willow shoal
#

i click cube and still not change color

#

after start scene

#

i testing, and trying find solution

polar acorn
#

It has a collider, isn't on a canvas, and has all its variables set so it should be running the function

willow shoal
#

nothink after start

#

its should work but not its working

#

no error or anythink after click

#

on log

polar acorn
#

So, you added a log to the function, and don't get the log when you click on this object?

willow shoal
#

yes

#

i test debug

polar acorn
#

Then there is probably something else in front of this object that is receiving the click instead

willow shoal
#

finally i found solution

#

just delete cube and add

#

same cube

#

okey

#

that was a glith or somethink difrent

#

thanks for help!!!

earnest wind
#

if i have a async void, then if i want to make it return something i have to make it a Task<T> right?

slender nymph
#

or Awaitable<T> if you are on unity 6+

earnest wind
slender nymph
#

itdepends on your needs and what you are actually doing. and if you are concerned about performance then use the profiler

earnest wind
#

i guess task will work since i already used it in some other scripts

#

thanks

grand snow
#

I am UniTask 's no 1 fan so ofc I recommend that

late merlin
#

Yo I'm just trying to figure out movement right now and was wondering if I need to download an external app to write code because I can't figure out how to do it in Unity?

polar acorn
#

!ide

eternal falconBOT
late merlin
#

thanks for showing me, i just got it working 😭 πŸ™

glossy crystal
#

Hello, I'm just wondering why my sprite is changing location when I'm running a different animation? I have an idle animatino clip, and a running animation clip. The sprite is offset upwards when I run the running animation clip, why is this? I don't think I encoded any positional data in the animation clip

#

Is there a setting I can modify to manually change the offset to none

slender nymph
#

not a code question, but sounds like the pivot point is wrong

glossy crystal
#

Oh ok my bad

glossy crystal
#

ty)

twin bane
#

any idea why im getting a error on ChangeState saying it doesnt exist

polar acorn
twin bane
#

tutorial i followed the guy just adds it without additional code lol

polar acorn
#

Show code, show error

twin bane
#

solved it, me being a dumbo

#

i swear everytime i ask a question in here, i not long after figure it out

mossy wren
#

hellos! I'm working on a game with a cutscene that triggers upon the player colliding with a trigger. currently, the animation plays on loop immediately upon the start of the scene, and the script doesn't even come into effect. how do i fix this?

polar acorn
mossy wren
#

lemme grab that real quick

#

public class CutsceneScript : MonoBehaviour
{
    [Tooltip("Animator component that controls the cutscene animation.")]
    public Animator cutsceneAnimator;

    [Tooltip("Name of the animation trigger in the Animator.")]
    public string animationTriggerName = "PlayCutscene";

    [Tooltip("Duration of the cutscene in seconds.")]
    public float cutsceneDuration = 5f;

    private bool hasPlayed = false;

    private void OnTriggerEnter(Collider other)
    {
        if (!hasPlayed && other.CompareTag("Player"))
        {
            if (cutsceneAnimator != null)
            {
                cutsceneAnimator.SetTrigger(animationTriggerName);
                hasPlayed = true;

                // Disable player movement
                FirstPersonController movementScript = other.GetComponent<FirstPersonController>();
                if (movementScript != null)
                    movementScript.enabled = false;

                // Re-enable movement after cutscene
                StartCoroutine(ReEnableMovement(other.gameObject, cutsceneDuration));
            }
            else
            {
                Debug.LogWarning("CutsceneScript: No Animator assigned!");
            }
        }
    }

    private System.Collections.IEnumerator ReEnableMovement(GameObject player, float delay)
    {
        yield return new WaitForSeconds(delay);

        FirstPersonController = player.GetComponent<FirstPersonController>();
        if (movementScript != null)
            movementScript.enabled = true;
    }
}
polar acorn
#

Okay, and what about the Animator Controller

mossy wren
#

what do you mean

#

oh

polar acorn
#

Why

#

Why MonoBehaviour

#

that's going to match any component except Transform and Rigidbody

mossy wren
#

that is because i forgot to swap the word monobehavior after i took this code from my class

#

i have edited the message and the code itself

#

anyway here's the animator

#

it just pauses for a second and then rotates

polar acorn
naive pawn
mossy wren
polar acorn
polar acorn
#

Where you set up your animation states and transition conditions

mossy wren
#

well i get a feeling that im starting to see the problem then

#

for i do not have one of those ;-;

polar acorn
#

I can literally see your animator component in the screenshot

#

and it has a controller provided

mossy wren
#

oh

#

idk then

polar acorn
mossy wren
#

how do i check it

polar acorn
#

Open it

mossy wren
#

oh the capsule

#

well this explains a lot.

polar acorn
#

and nothing ever tells it to leave that state

mossy wren
#

yeah i need to add a thing there

#

well i dont need it to, i just need a trigger for it thats not starting the game

grand snow
#

dang thats a LONG cutscene

mossy wren
#

oh yeah its like 3 seconds but i didnt wanna loop it so mu duct tape and super glue answer was MAKE IT LOOOONG

mossy wren
#

i want to add the cutscene script to it so it knows when to swap animations but i can only add a completely new script?

naive pawn
#

on the animation clip

mossy wren
#

i didnt know that was a thing at the time

#

i still dont know how tbh

naive pawn
#

set the animation clip to not loop

mossy wren
#

how?

#

i cant find the button ;-;

naive pawn
#

click the animation clip asset
look at the inspector tab
find the option labelled "loop time"
deselect it

mossy wren
#

thank yous :3

grand snow
mossy wren
#

i already made the cutscene

#

its just turning around

mossy wren
#

or

#

i know what it is, i need to know how to use it

grand snow
#

Its useful to animate things and play custom animations on animators (e.g. animate a character from some point to another and make them play a walk anim)

#

can also control other stuff or make custom clips+tracks

mossy wren
#

well yeah i know what but i need to add my script as a trigger for the animation and i just cant seem to do that

#

it says i need a new script

earnest wind
#

sorry im pretty new with API requests lol
where did i go wrong here?

WWWForm form = new();
        form.AddField("karma", karma);

        UnityWebRequest webRequest = UnityWebRequest.Post($"https://g-{Settings.server.gameId}.modapi.io/v1/games/{Settings.server.gameId}/mods/{ModID}/comments/{CommentID}/karma", form);
        webRequest.SetRequestHeader("Authorization", $"Bearer {UserData.instance.oAuthToken}");
        webRequest.SetRequestHeader("Accept", "application/json");

        await webRequest.SendWebRequest();
#

yes its in a async, and i followed the same way as i did .Get, but just added a WWWForm

rich adder
rich adder
#

could be your token

slender nymph
#

yeah seems like you are not authenticated

earnest wind
#
 UnityWebRequest webRequest = UnityWebRequest.Get($"https://g-{Settings.server.gameId}.modapi.io/v1/me");
        webRequest.SetRequestHeader("Authorization", $"Bearer {UserData.instance.oAuthToken}");
        webRequest.SetRequestHeader("Accept", "application/json");

        await webRequest.SendWebRequest();
#

This one works

wintry quarry
earnest wind
rich adder
#

even the website says you can do a Get without token

#

also on their site 403 Forbidden -- You do not have permission to perform the requested action.

wintry quarry
#

In fact it's even a different resource

#

403 is not 401

slender nymph
#

the /me endpoint only requires authentication and the read scope, the endpoint you are getting the 403 on requires write scope

wintry quarry
#

403 means you have a valid token you just don't have permission to do that

rich adder
#

oh sorry yes its 403

wintry quarry
#

Or get a token for a user that does have permission

#

Very little context here so it's hard to say more

slender nymph
earnest wind
slender nymph
#

how did you authenticate

earnest wind
#

dont see anywhere where you can set up the write scope though

earnest wind
slender nymph
#

welp, guess you gotta find their support then since this isn't a unity issue at this point πŸ€·β€β™‚οΈ

earnest wind
#

im gonna ask, thanks

mossy wren
#

could i get some info on this? i dont seem to have the option to do anything

rich adder
mossy wren
#

i want to make it so there's a trigger for new animation

earnest wind
mossy wren
#

so when the player touches a hitbox the animation plays

earnest wind
#

by making another account, commenting, i can like/dislike it, just not my own comments

mossy wren
#

thank yous :3

#

wait i read through it all

#

i still dont get it, i cant do anything with the parameters once i make them

#

i want to put a trigger parameter on the board between enter and new animation

slender nymph
#

you can't. Enter transitions immediately without conditions to the default state that is set. which you've set to New Animation

#

create an empty state for the default state and transition from that to New Animation (which really needs a better name)

mossy wren
#

oh thank you

#

if i find further issues i'll go there, sorry

steep canyon
#

ok I'm trying to disable movement if it's outside some bounds like this

Vector3 move = transform.position + moveDir * (speed * Time.fixedDeltaTime);
if (!bounds.Contains(move)) return;```

it seems to be falling through no matter what, I have some gizmos drawing what the bounds should be but the player appears to be able to exit them somehow so I think I'm using the Bounds class wrong
#

the code for applying movement is below that snippet

keen cargo
#

Hey yall, so I have this list of sprites meant for the UI, however they're currently stored in Resources, which I know is a big no-no, however what is the alternative and how would I implement it for something as simple as the following?:

Sprite newSprite = Resources.Load<Sprite>($"Graphics/UI/{lvl}");
  if (newSprite != null)
    currentRoom.transform.Find("WallNumber").GetComponent<SpriteRenderer>().sprite = newSprite;
  else
    Debug.Log("No image found");
polar acorn
keen cargo
#

it's an int variable from the same script

#

and every UI element is named after a number, so just "0", "1", etc.

polar acorn
#

Perfect, then you can make an array of Sprites and do .sprite = levelSprites[lvl]

high summit
#

I have managed to get it so it's only affecting the emission of the object I want it to (not all lights in the scene of the same type)

#

But as you can see it is NOT flashing the emission at the correct time and seemingly random?

north kiln
#

What do you mean the correct time, and seemingly random? Your code literally does it at random between two times

high summit
#

Yes but the emission change isnt in time with the light going off

#

If you watch the video the emission should be 'white' when the light is on

#

and black when it's off

north kiln
#

Do you have many of these lights?

high summit
#

Yeah

#

but they are unaffected as it's object based

#
 emissiveMaterial = objectToChange.GetComponent<Renderer>().material; objectToChange = null;
north kiln
#

Your code just sets it to white when the timer ticks over

#

And sets it to black at all other times

high summit
#

Oh thats the issue it's only when the timer ticks over

#

not during

north kiln
#

You need to toggle it in the lower if based on the light's state

high summit
#

Yeah basically when light = off emission off so it looks normal

high summit
#

It doesnt show white at all just black the whole time

north kiln
#

You haven't done what I said at all

#

Put the emission toggling code in the same if as the light code, and do it based on the state the light is in

high summit
#

Oh so like a

if (lightOB.enabled == true)
#

This seems to have got it, thanks!

grand snow
#

that first if is pointless as it will go below 0 and then be given a new value above 0...

north kiln
#

That's not in your if statement, it will be unnecessarily called every frame

grand snow
# high summit This seems to have got it, thanks!

A more streamlined version of your logic:

void Update()
{
    timer -= Time.deltaTime;

    if(timer <= 0f)
    {
        bool newState = !lightOB.enabled;
        lightOB.enabled = newState;
        emissiveMaterial.SetColor("_EmissionColor", newState ? Color.white : Color.black);
        timer = Random.Range(minTime, maxTime);
    }
}
#

Notice how we only change the emission color when we change the light state

steep canyon
polar acorn
steep canyon
#
[SerializeField] private Bounds bounds;

Just a serialized field in my player

private void FixedUpdate() {
  waves.Value.positionList.Add(new(transform.position.x, transform.position.z));
  fire.rotation = Quaternion.identity;
  fire.localPosition = Vector3.zero;
  if (movement.magnitude <= 0.1f) return;
  Vector3 moveDir = movement.x * cam.right + movement.y * cam.forward;
          
  Vector3 move = transform.position + moveDir * (speed * Time.fixedDeltaTime);
  if (!bounds.Contains(move)) return;
          
  fire.position = transform.position + moveDir;
  transform.position = move;
  transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(moveDir), .25f);
  transform.eulerAngles = new(0, transform.eulerAngles.y, 0);
}

this being the full function

steep canyon
#

easiest issue to test is going below the bounds

polar acorn
#

Okay, so, after the return, try logging move and bounds.Contains(move)

#

See what those values match what you are expecting to happen

steep canyon
#
private void OnDrawGizmosSelected() {
  Gizmos.DrawWireCube(bounds.center, bounds.extents);
}```

this is what I use to see my bounds
torpid bronze
#

hey very new to this discord and I have no idea where to ask this question so sorry if im in the wrong place, anyone know how to deal with the CommandBuffer texture type 3 not found warning ?

steep canyon
#

the bounds end at 0 on -y

polar acorn
steep canyon
#

the center is set to y+10

polar acorn
#

The center is set to 10

steep canyon
#

meaning it should be checking for 0 to 20

polar acorn
#

and the extents are 20,

#

so it contains -10 to 30

steep canyon
#

whuh

polar acorn
steep canyon
#

so my gizmo code is gaslighting me lmao

polar acorn
#

Extents are the distance from the center point in each axis

steep canyon
#

oh weird ok

#

ight I timed the extent by 2 in the gizmo code that should be accurate now

#

ok now it stops correctly

#

ty

acoustic hawk
#

This is a quick issue: I have an object as a cursor for a simple game i'm making, and I want the block to go back to it's initial state, but instead makes a loop

Here's a string:

    IEnumerator MoveCursor()
    {
        Vector3 startPosition = transform.position;
        Vector3 targetPosition = new Vector3(startPosition.x, startPosition.y, -1.0f); // Cambiado a Z: -1.0

        // Move to Z: -1.0
        while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
            yield return null;
        }

        // Move back to initial position
        targetPosition = startPosition;
        while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
            yield return null;
        }
    }
}
acoustic hawk
#

When I click on the cursor, which serves as a bat, the Z movement I've programmed (with the help of AI, I admit and apologize in advance) does the movement, but goes from point A to point B nonstop.

cosmic dagger
acoustic hawk
#

i'll get footage

#

hold on

cosmic dagger
#

Also, in both while loops, during the MoveTowards method, you use transform.position instead of startPosition . . .

acoustic hawk
#

nvm, the problem gets worse

rich adder
#

good lesson on not letting "AI" let write code for you

#

when you don't understand how any of it works, and if it breaks ur stuck where you are

acoustic hawk
acoustic hawk
#

and nop, the problem persists.
When it goes from point A to Point B, the "bat" stays in the point B and now it can't follow my mouse

weak isle
acoustic hawk
# acoustic hawk yeah, not the ideal tool for beginners.

another proof why AI can't never be your ideal tool is because I specified them like 6 times to fix an action and it makes it worse

the action was that: after going to point B, the "bat" immediately goes back to point A and I can click on it all the times I want without looping. What the AI did was the same, but with the cost of the movementg never happening again after the second click

acoustic hawk
teal viper
# acoustic hawk another proof why AI can't never be your ideal tool is because I specified them ...

I wouldn't be so categorical as to say "never".
AI output depends a lot on your ability to explain the problem and the desired outcome as well as providing the correct context.
Ironically, the better you are as a developer, the easier you can implement something, the easier it is to get a desirable output from an LLM.
But when the ai can finally sit at your chair and see the whole context of your project it would definitely be able to solve your problem and even more.

sour fulcrum
#

AI does not know how to code, AI knows how to brute forcefully feed off other peoples work and discussions in an attempt to find enough relevant data to compose an answer that might answer your question

odd barn
#

In my asteroid clone I'm using the following code to create and fire the ship's laser, and it works.

public GameObject bulletPrefab;
public Transform bulletOffset;

if (Input.GetKey(KeyCode.Space) && !bulletOnCooldown)
{
    StartCoroutine(BulletCooldown());
    Instantiate(bulletPrefab, bulletOffset);
}

But I'm using very similar logic to try and create smaller asteroids when a large asteroid is destroyed in the following code-

 public GameObject medAsteroidPrefab;

 public Transform medOffsetOne;
 public Transform medOffsetTwo;

private void OnCollisionEnter2D(Collision2D col)
{
    if (col.collider.CompareTag("laser"))
    {

        if (gameObject.CompareTag("bigAsteroid"))
        {
            Instantiate(medAsteroidPrefab, medOffsetOne);

            Instantiate(medAsteroidPrefab, medOffsetTwo);
        }
        
        Destroy(gameObject);
    }
}

but the smaller asteroids aren't being instantiated. I put debug.log's before each should be instantiated to make sure that if statement is actually being executed, and it is. It feels like I'm overlooking something simple?

sour fulcrum
#

show the code w/ the debug logs and show the inspector of whatever that second script is

odd barn
#

!code

eternal falconBOT
odd barn
teal viper
odd barn
#

the transforms for the offsets are pulled from children of the prefab

#

The only difference between the ship and the asteroids as far as I can tell is that the ship isn't a prefab, but I don't think that matters

warped delta
teal viper
# odd barn In my asteroid clone I'm using the following code to create and fire the ship's ...

If it is being executed, then it is instantiated. It's likely being destroyed immediately, or maybe instantiated in the wrong place. You can confirm the former by adding a script with OnEnable and OnDisable in the prefab and printing something meaningful inside.
To check the latter, pause your game after they are supposed to be spawned and inspect the hierarchy(can use the search bar too).

odd barn
teal viper
#

It would also make it clear if they are instantiated in the first place.

odd barn
#

yeah, they're being instantiated

#

gonna try to check if they're in a collision when they're created with OnCollisionStay2D

teal viper
odd barn
#

Nope. I tried

print("Asteroid position:" + transform.position);

and it's giving correct positions too.

odd barn
odd barn
teal viper
odd barn
teal viper
# odd barn

Select a log message and take a screenshot again

odd barn
#

oh it tells you what script it's coming from

teal viper
# odd barn

See that info below? That's very important. More important than the list of messages above.

odd barn
#

I didn't know you could select them

#

lmfao

teal viper
#

It contains the path to the code line and the callstack that led to that line being called.

#

Now, I don't see any destroy messages. Did you print anything in on disable/destroy?

odd barn
#

I didn't then, I was too busy trying to figure out what a callstack is lmao

#

but I did now, and nothing was printed after they were instantiated

#

but when I shot an asteroid that was spawned via the asteroid spawner which isn't bugged, it did print the message

#

so I don't think they're being destroyed?

teal viper
#

Add a second parameter this to your logs. Debug.Log("small asteroid instantiated", this);. Then try clicking the message when it appears. This should select the object in the hierarchy.

#

Make sure to "uncollapse" you messages in the console.

odd barn
#

I must have missed something, they're definitely being destroyed. All of these messages come from shooting one "big" asteroid.

teal viper
odd barn
#

It doesn't say anything different unfortunately

#

I feel like when the big asteroid that instantiates the two medium ones executes the Destroy(gameObject) from its OnCollisionEnter2D it's also destroying the prefabs it instantiated

#

The medium asteroids it instantiates shouldn't be children of it though. But they get their transforms from empty objects that are children of it.

polar acorn
odd barn
#

@teal viper thanks for going through that with me. I learned a lot about debugging!

teal viper
polar acorn
#

Yes I explicitly set one, of course it's going to have one

teal viper
#

For some reason I thought that medOffset variables were vectors...πŸ˜…

odd barn
#

lol! My thought process was that I was giving it the position of the medOffset objects transform. Like, this is your transform.position now. Not transform.parent. I know better now.

glossy crystal
#

hello, this is a noob question and not really unity specific but I've only made simple learning projects so far, and haven't had too many objects on the screen. If I have say hundreds of object A on the screen, moving, and an object B always seeking the nearest object A, how should I go about this?

I want to say that I should make object A a prefab, and during instantiation, add them to some data structure to store them in, some kind of entity manager class? I want to use something basic, like a list, but looping through the entire map to find the closest thing seems bad. I want to separate my game into grid chunks, and maybe store a list of enemies in each chunk during each update frame, and simply search for the nearest enemy starting from object B's current cell, and expanding from there. Is this even worth doing if I'm only going to ever be searching through 100-200 things at a time? If I wanted to repeat this process for say, each object A, would that warrant doing some sort of spatial partition?

rich scroll
#

You should probably look into object pooling. I used one on about 500 objects, always looking for the closest, and it was fine

#

Just make sure to use a for loop for getting the closest instead of a Linq expression

#

With pooling implemented and a for loop, garbage collection would be at a minimum, and usually thats the thing that slows down the game the most

glossy crystal
#

Okay thank you! I see the benefits of pooling now

glossy crystal
charred spoke
#

Depends on the amount of monsters but yes

#

For large amounts of monsters some sort of spatial partition structure should be used to get the n-closest

meager hinge
#

Can someone please help me stop my unity from crashing? it does it randomly in play mode for 1 project only...
If needed i can put my editor.log here

#

this prob isnt beginner sorry

eternal falconBOT
#
πŸ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

burnt vapor
meager hinge
#

do you want me to dm you the editor.log file? I dont want to put it here since its huge

burnt vapor
#

You can use a paste site
!code

eternal falconBOT
charred spoke
#

There should also be a Crash!!! Section that is relevant

meager hinge
charred spoke
#

Then paste that

meager hinge
#

<RI> Initialized touch support.
Loaded scene 'Temp/__Backupscenes/0.backup'
Deserialize: 3.502 ms
Integration: 183.005 ms
Integration of assets: 0.002 ms
Thread Wait Time: 0.009 ms
Total Operation Time: 186.518 ms
TrimDiskCacheJob: Current cache size 0mb
Crash!!!

#

I've done alot if googleing

visual linden
#

Hunch tells me you've got a loop somewhere that never exits and never yields

charred spoke
#

What is the stacktrace after the crash ?

meager hinge
#

========== OUTPUTTING STACK TRACE ==================

0x00007FFD59CF981D (nvwgf2umx) NVENCODEAPI_Thunk
0x00007FFD59F8803F (nvwgf2umx) SetDependencyInfo
0x00007FFD59F87F9F (nvwgf2umx) SetDependencyInfo
0x00007FFD59F7C87D (nvwgf2umx) SetDependencyInfo
0x00007FFD5A47034A (nvwgf2umx) NVDEV_Thunk
0x00007FFD5A90ECCA (nvwgf2umx) NVDEV_Thunk
0x00007FFD6D3CE8D7 (KERNEL32) BaseThreadInitThunk
0x00007FFD6F5314FC (ntdll) RtlUserThreadStart

========== END OF STACKTRACE ===========

charred spoke
meager hinge
charred spoke
#

Studio or game ready ?

visual linden
#

@meager hinge Is it a large project? If you try to enter play mode in an empty scene, does it still crash? Can you disable half of the gameobjects in your hierarchy and see if one half or the other disabled stops the crash? (If we'd assume for a second that maybe the crash is caused by some script)

charred spoke
visual linden
charred spoke
#

So why do you doubt my statement that the nvidia drivers are crashing when the crash happens from them ?

visual linden
#

Because there's no sign that the drivers are "crashing". Some code in some dll is, I'm guessing, throwing an exceptionβ€” Likely due to the Editor becoming unresponsive (Because It crashed). It still tells us nothing of the cause of the crash

#

I'm not saying it can't possibly be some obscure nvidia driver issue. Just that that's not the first place I'd look.

meager hinge
visual linden
#

I would probably just start disabling objects and scripts in the scene until you found the one causing the crash, and that would give you a place to start in terms of debugging.

meager hinge
#

oke

#

its a basic wip level editor scene so i think it has 2 different scripts rn

#

Oke ive it still crashed with the scripts disabled

#

i disabled the object with the script on it and then the canvas

#

seperatly

#

they crashed

visual linden
#

πŸ€” But if only this scene crashes, there must be some code executing there specifically causing it

teal viper
meager hinge
#

it dosent give me any, it just closes and opens the crash reporter window

teal viper
meager hinge
#

Oh yeah i have that

#

text from crash.dmp

#

The thread tried to read from or write to a virtual address for which it does not have the appropriate access.

meager hinge
#

can i send it here? its a small enough file

teal viper
meager hinge
#

its not text

#

i can maybe send a ss?

teal viper
#

You can yes

meager hinge
teal viper
#

And thread name

#

Though, I feel like it's not gonna show much info without debug symbols

meager hinge
teal viper
meager hinge
#

You mean theese?

teal viper
meager hinge
#

wait the second one gave me this

teal viper
#

Hmmm... Does the crash happen in a new empty project? And when exactly does it happen in your project?

meager hinge
teal viper
meager hinge
teal viper
meager hinge
#

oke

#

ngl i forgot how to upgarde lol its been awhile

meager hinge
next spruce
#

Hi,

I've been trying to perfect a kinematic Rigidbody-based movement system for an ant-style character that can crawl on any surface - walls, ceilings, trees, etc - while still responding to gravity when β€œreleased.” (fall of on commmand) I’ve tried averaging multiple downward raycasts for rotation to align both pitch and roll, but the model still sometimes flips into geometry or falls through. There is also a camera system where camera movement dictates yaw rotation (third person shooter like).

It's been forever and I can't seem to fix it

Any help would be greatly appreaciated!

The player movement script: https://pastebin.com/TuNdUTkY
The camera rotator script: https://pastebin.com/spgTaESs

A short video of the occurring problems: https://drive.google.com/file/d/1KoaRe_C3i-wWBSYOMuixJP1oIyIGfIZN/view?usp=sharing

grand snow
#

Ideally we would have some unity code in the stack to better tell what went wrong

visual ginkgo
#

hi guysss, is htere a way to speed up unity? the compiling tooks too much time D:::: i saw some assembly definitions but idk how to use em hahahaha

queen adder
#

I'm always struggeling with unityEvents. I don't know why this isn't working. I have 2 Scripts. One (theManager) holds the event and handels invoke. The other is a Prefab Object, that should one add himself as a listener. If i link the event to a funtion inside the Manager, it works. Only the funtion on the prefab don't get called ````

///Script One - Manager

//The Event
public UnityEvent<bool> QuestTypInNeedTEST;

//Test function to invoke event
[ContextMenu("TestEvent")]
public void TestEvent()
{
    QuestTypInNeedTEST.Invoke(false);
}

//My test, if event works on manager ifself - yes it does 
public void TESTFORTEST(bool da)
{
    Debug.Log("INVOKE IN MANAGER ITSLEF WORKS");
}

//Link event 
protected override void Awake()
{
    base.Awake();
    QuestTypInNeedTEST.AddListener(TESTFORTEST);
}



///Script Two Prefab 
void Start()
{
    QuestManager.Instance.QuestTypInNeedTEST.AddListener(TESTCHECK);

     //prints out 0 - every time, even with 10 prefabs in the scene 
    Debug.Log(QuestManager.Instance.QuestTypInNeedTEST.GetPersistentEventCount());
    
}

//Dont't get called when event is invoked 
public void TESTCHECK(bool needTEST)
{
    Debug.Log(needTEST +" : "+ gameObject.name);
}
teal viper
teal viper
teal viper
verbal dome
#

Yep, subscribing via code isn't persistent

visual ginkgo
#

hi guys! is there away to speed up unity? the compiling is soooo slow D:::

verbal dome
#

When you compile, unity does a domain reload which can trigger a bunch of stuff. So it might not even be compilation taking that long

#

Profiling it can help find out the issue

teal viper
teal viper
queen adder
queen adder
#

Okay thank you. I will try my luck with a debugger then

teal viper
#

The only thing I can assume is that the event you subscribe to is not the one that is being invoked.

#

Logging object names or IDs during subscription and event invocation could help confirm it. Or check it in the debugger.

visual ginkgo
#

thank u guys!

#

i'll figure it out

muted pawn
#

anyone know a good way to get curved colliders for a ramp?? The polygon only gives me trouble and I tried downloading this custom collider pack but it doesnt work anymore its like 10 years old I think lol

glossy crystal
#

Hello, do people typically use Enums for states? Or do you make actual state classes

verbal dome
#

And you didnt specify 2d or 3d (i assume 2d?)

muted pawn
#

omg mb Im so used to coming to this channel xd its 2d

#

@verbal dome

naive pawn
muted pawn
queen adder
naive pawn
naive pawn
teal viper
naive pawn
verbal dome
#

So that would be current frame + 4 frames, right

queen adder
verbal dome
#

Waiting for an arbitrary amount of frames seems shady though

naive pawn
hexed terrace
somber elm
#

ok sorry

ember tangle
#

Random Vector3 math question: Is the Vector3 ( 1, 0 , 0 ) already normalized since has a value of 1? Is Vector3 ( 1, 1 , 0 ) normalized?

brave compass
ember tangle
#

so if normalized the second vector would be (0.5, 0.5, 0) right?

#

hmm acutally maybe not if I draw it on graph paper...

final forge
#

No look at the definition of the l2 norm

brave compass
#

The length of a vector is calculated by taking the square root of the squares of each component combined. In code, that would look like this: Mathf.Sqrt(x*x + y*y + z*z)

#

So the length of (0.5, 0.5, 0) is Mathf.Sqrt(0.5*0.5 + 0.5*0.5 + 0*0) -> Mathf.Sqrt(0.25 + 0.25 + 0) -> Mathf.Sqrt(0.5) -> 0.707106

#

The length of (1, 1, 0) ends up being the square root of 2, which is 1.41421.

A normalized version of (1, 1, 0) can be calculated by dividing (1, 1, 0) with its length, 1.41421. That ends up being (0.707106, 0.707106, 0).

ember tangle
#

I get it now, thanks for the insight!

#

How expensive is Vector3.Normalize() to compute?

brave compass
#

Normalizing a Vector3 is the same as calculating its length and then dividing by that length. Calculating its length is a square root, three multiplications and two additions. Compared to a multiply and addition operation, a square root and divide can be much slower. But this is all relative. A modern CPU blazes through all of this. It only starts to matter when you're talking about millions of these operations per frame.

high summit
#

Bit confused by trying to create a timer here, If somebody could help me understand the logic that would be awesome.

#

Basically, on on trigger enter, zombie pops up, timer starts at one second, and then when timer hits 0, zombie vanishes (jumpscare)

#

^ That's what I want to happen

rich adder
high summit
#

I was just about to say that yeah

rich adder
#

you can do for example
if(timer > 0) {timer -= Time.deltaTime}

high summit
#

in my light flicker script I did something similar but the issue is this wont run on update

#

Or i dont want the timer to run as soon as the script starts

rich adder
#

the timer -= Time.deltaTime isn't behind any condition ofcourse it will run right away

#

thats why you need a boolean condition , like exmaple I shown or you can create another bool

high summit
#

Is there a way to make the timer only run once ontrigger enter?

#

Ah

rich adder
#

there are also coroutines you can use for these 1 off things

high summit
#

I think i'm getting somewhere?

#

Zombie seems to not appear though or vanishes in the blink of an eye i can't tell

rich adder
#

You did a completely different thing here..

#

why did you change timer > 0 from if(timer <= 0)

polar acorn
# high summit

Work through it in your head. One line at a time. You set the timer to 1, you enable the object, and set the bool to true.

Now, with those values in mind, walk through your update function. What happens, line by line?

#

(for the sake of math assume deltaTime is 0.1)

high summit
#

Okay so starting from fresh

#

is it's running, I need to subtract from it

rich adder
#

the whole idea was

if(isRunning)
timer -= TIme.deltaTime;
//only start timer when ready

if(timer <=0) // should go in the isRunning bool so it doesnt do something when starting with timer = 0 value
if timer has reached 0 //do the thing

polar acorn
high summit
#
    void Update()
    {

        if (isrunning)
        {
            timer -= Time.deltaTime;
        }
#

Then this to subtract from it

frigid sequoia
#

But like, you want to spawn something and make it dissapear soon after?

high summit
#

Yeah

#

It's a jumpscare

#

Popup in your face then vanish

frigid sequoia
#

Why don't you just add a timer on the spawned item to destroy it?

polar acorn
high summit
#

I need to check if timer = 0

#

in a seperate if I assume

rich adder
#

should be in the isRunning bool

high summit
#

Oh yeah!

#

That makes sense

rich adder
#

because you start with 0

polar acorn
high summit
#

Ah equals or less than

polar acorn
#

And go into negatives

polar acorn
rich adder
#

hiding already hidden object is no big deal, but what if you added other logic to happen after ?. So its better you put hiding logic (time reaches 0 or under) also within timer running bool

high summit
#

messed up some syntax here

#

sorry new to c#

polar acorn
#

that one's formatted correctly

rich adder
#

I mean you already did all this before? you should know how to write lol

high summit
#
          if (timer <= 0) {


            }
frigid sequoia
#

I am just still wondering the "isrunning" part. What is running? do you really need that?

high summit
#

I dont know I think it's because i'm trying to follow 2 peoples approaches lol

rich adder
polar acorn
#

There are multiple ways to do this, but this is also a good way to demonstrate code flow so working with this solution is probably the most instructive

high summit
#

this is what i'm at

rich adder
frigid sequoia
#

Sure, but in what case would you not want to be running the timer? Isn't this meant to just poop and vanish in a second?

high summit
#

^ Yeah

rich adder
#

well going by the assumptions that we have no idea where this script is right now..
(it can be recycled to multiple objects/jumpscares for example)

high summit
#

It works also, But it's triggable multiple times, so i guess id need another bool like 'hashappened'

#

Its just a stationary jumpscare

rich adder
frigid sequoia
#

Attach the script to a collider that spawns the thing when entering on it, then spawn the zombie prefab with a timer on update that destroys it after a second. Destroy the spawner script in the same call that spawns the zombie

high summit
#

this seems to be functioning as I need it to

rich adder
#

how ? that if has happened is doing absolutely nothing but preventing timer to = 0.3

high summit
#

Thats a good point...

#

I swear it's working unless I didnt save correctly lol

rich adder
#

you could technically do if(hasHappened == true) return;

polar acorn
#

I mean, it will work, once

#

But once hasHappened is true, it'll activate the object without actually setting the timer

#

so it'll deactivate itself immediately

high summit
#

Yeah my bad

#

I find it so bizzare that an If will include the very next line but nothing else if not wrapped in curlys

#

I guess it's just something I gotta get used to

glossy crystal
#

How do I decide when to put things in awake and start? If I have a state machine for enemy behavior, should I set the initial state in awake? in case I need it in start? Or should I put it in start and swap it to awake if I ever need it to be done first?

rich adder
#

c# quirks

rich adder
glossy crystal
#

o ok ty

polar acorn
glossy crystal
#

ya makes sense, thanks!

frigid sequoia
polar acorn
#

So, a script getting a component from the object it's on? Awake. Getting a reference from a singleton? Start

rich adder
#

also Awake runs always (unless gameobject is disabled) even script is disabled, Start does not run when is disabled until enabled again

high summit
polar acorn
frigid sequoia
rich adder
#

yup especially if you have 10s or 100s of objects initializing

frigid sequoia
frigid sequoia
# high summit

Also, also "hashappened" is already boolean, you don't need to compare it to a other boolean

#

You can just do "!hashappened"

#

Also, camelcase, but you can name it whatever the heck u want as long as you know what it is

naive pawn
#

also wanting only 1 thing to happen isn't all that uncommon tbh

#

could be something as simple as this

if (a) counta++;
if (b) countb++;
if (c) countc++;
```you wouldn't want `c` to also require `a` and `b`
rich adder
#

also, you can easily put a method instead of braces

#

if(something) MoreStuff()

cerulean epoch
#

I wanna make a railroad and make that train follow it with a throttle and brake

rich adder
acoustic hawk
acoustic hawk
#

here's the current string:

public class Test2 : MonoBehaviour
{
    Vector3 pos;
    public float offset = 3f;
    public float moveSpeed = 5f; // Speed

    Animator anim;

    void Start()
    {
        anim = gameObject.GetComponent<Animator>();
    }

    void Update()
    {
        anim.enabled = false;

        pos = Input.mousePosition;
        pos.z = offset;
        transform.position = Camera.main.ScreenToWorldPoint(pos);

        if (Input.GetMouseButtonDown(0))
        {
            StartCoroutine(MoveCursor());
        }
    }

    IEnumerator MoveCursor()
    {
        Vector3 startPosition = transform.position;
        Vector3 targetPosition = new Vector3(startPosition.x, startPosition.y, -1.0f); // Cambiado a Z: -1.0

        // Move to Z: -1.0
        while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(startPosition, targetPosition, moveSpeed * Time.deltaTime);
            yield return null;
        }

        // Move back to initial position
        targetPosition = startPosition;
        while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(startPosition, targetPosition, moveSpeed * Time.deltaTime);
            yield return null;
        }
    }
}
night mural
#

or I guess since update runs first, it's only the coroutine that will be doing overwriting. maybe that's fine but it seems fragile to me

#

if you also have an animator, it could be overwriting transform values as well

acoustic hawk
#

I've recently disabled Animator and no luck

wintry quarry
#

in both places where you used it.

#

it should be:

transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);```
acoustic hawk
#

it was because I was requested by an user to swap "transform.position" with "startPosition"

wintry quarry
#

well it doesn't make sense there

acoustic hawk
#

now, I'll try to find the way for the cursor to come back to Point A

wintry quarry
#

I mean this isn't really going to work at all

#

because you have transform.position = Camera.main.ScreenToWorldPoint(pos); in Update

#

so your transform.position = code in the coroutine is just going to compete with that

#

you would basically want to set a boolean variable to true while the coroutine is happening and make it so that normal Update movement doesn't happen while the coroutine is running

#

otherwise the two lines of code are just going to fight with each other @acoustic hawk

rotund crown
#

hm, so i was thinking about how to make a 3d rotating platform for a platformer game
the solutions ive seen involve reparenting to inherit transform, or applying velocity, but i dont think rotational velocity is feasible

#

but then i came across this

wintry quarry
rotund crown
#

any advice on how i could implement this? specifically in such a way that if you jumped while on said rotating platform, you'd keep the velocity you would have from jumping off of one

wintry quarry
rotund crown
#

they launched off of a moving platform, but only horizontally

frigid sequoia
#

If I am about to modify the text of a bunch of texts on update, would you recommend me to store them on a list and call them by index or to make a variable for each of them and do it manually?

sour fulcrum
sour fulcrum
frigid sequoia
#

I am aware, but I need to display the stats of stuff on real time

#

I could subscribe every single stat to a "onValueChanged", but that would kinda bloat it a lot and wouldn't really save much, cause basically that's going to be modified pretty frequently anyways

sour fulcrum
#

Fair, that would be ideal though.

Might be worth half implementing that approach and having your text stuff listen to an event but rather than do it on value change you just have some relevant manager/controller invoke it on update?

frigid sequoia
#

It would be fine updating it just once per second or something

#

It's fine if there is a small delay

#

But the question at hand, it's more efficient to have a list with like 10+ values and search on it or having a variable for all of those values?

austere aspen
#

is there anyway I can get help troubleshooting some animation / script issues? (im very new)

sour fulcrum
#

Don’t ask to ask, just ask πŸ˜…

austere aspen
#

LOL MY B

#

im not quite sure why but I made a attack / sword swing script and animations for it and they arent working

zealous geode
#

Hello, I'm having an issue with a spaceship movement-like code for a npc ship. The npc works with a state machine with a patrolling state. Right now the state machine detects a random waypoint and sets it as the travel direction of the object, however, after reaching the first point I can't get to "restart" (in some natural-looking way) the velocity of the ship, or make it turn around naturally to reach a new waypoint, because, after reaching the first waypoint, it seems that the velocity is too high so the npc just orbits around (usually in a big orbit) it's next waypoint.

This is the code:

#
public class NPCSpaceship_Controller : Spaceship_Controller
{
    [SerializeField] Spaceship selectedShip;
    public enum State
    {
        Travelling,
        Chasing,
        Attacking
    }
    [SerializeField] State currentState = State.Travelling;
    [SerializeField] State previousState = State.Travelling;
    [SerializeField] LayerMask targetMask;
    [SerializeField] Transform targetTransform;

    [SerializeField] float detectionRadius = 30f;
    [SerializeField] float attackingRadius = 20f;
    [SerializeField] float travellingRadius = 30f;

    [SerializeField] Vector3 travelPoint;
    [SerializeField] Vector3 travelDirection;
    public override void Initialize(Spaceship spaceship)
    { 
        base.Initialize(spaceship);
    }
    protected override void UpdateRotation()
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(travelDirection, transform.up), Time.deltaTime * 2f);
    }
    protected override void UpdateVelocity()
    {
        rb.AddForce(travelDirection * Ship.Stats.Acceleration * Time.deltaTime, ForceMode.Force);
    }
    private void GenerateNewWaypoint() //travelling
    {
        travelPoint = transform.position + Random.insideUnitSphere * travellingRadius;
    }
    private void UpdateTravelPoint() // chasing/attacking
    {
        travelPoint = targetTransform.position;
        travelDirection = (travelPoint - transform.position).normalized;
    }
    private bool ReachedTravelPoint()
    {
        return Vector3.Distance(transform.position, travelPoint) < 2.5f;
    }
}
#

I tried to summarize the methods working on what I think the problem is, since discord message limit doesn't allow me to paste everything

#

UpdateRotation and UpdateVelocity are being called on FixedUpdate and the TravelPoint methods on the Update and the methods of the state machine (Update)

steel smelt
#

Well you're adding the same linear acceleration from A to B, that will overshoot. If you want to use built in physics, then you need to plan for deceleration at some point.

I'm sure you can come up with a formula if you define a max deceleration rate. From there you can probably derive the distance at which deceleration begins and then apply counter force from there

zealous geode
#

Alright. I'll try that.

#

Thanks

steel smelt
#

more clearly, @zealous geode I think define deceleration = x, then compute the magnitude of the current velocity. Then (vMagnitude * vMagnitude) / (2f * deceleration) should return the distance at which deceleration should begin. Check if you're within that distance from your target, and if so, you can begin decelerating by adding the negated direction * deceleration * dt, instead of accelerating

#

this assumes your ship is going relatively straight

crisp vortex
#

yo does any1 know where i can find a good sprinting script all the tuts ive found didnt help much

wintry quarry
#

they are not there to drop into your project as a working final production-ready solution

#

do the tutorial, learn how it works, then apply it to your game

frigid sequoia
#

Does it make sense to have a general number formating on a gameManager? Would u do that? Or it's weird?

teal viper
frigid sequoia
#

Like 100,000 = 100K and that kinda stuff

teal viper
#

I'd put it in a static utility class

frigid sequoia
#

So... I make an static class? Do I need to place it on a object?

teal viper
#

No. You can't put static classes on objects

#

You can't have instances of static classes

#

It's like unity's MathF or other similar API.

frigid sequoia
#

I don't think I have yet done anything that does not derive from MonoBehaviour

teal viper
#

Well, then it's a good opportunity to start doing that.

frigid sequoia
#

So... like this?

teal viper
sour fulcrum
#

Just wait till you get to extensions πŸ˜„

frigid sequoia
#

What does it even mean making the string static? Isn't it changing depending of what value you pass it?

sour fulcrum
#

static as in the logic inside the scope of the static does not require a living instance to function

#

if you don't need a living instance to use the code you don't need to reference a living instance to use it

teal viper
#

The return type is string

frigid sequoia
#

Seems kinda weird to grasp, I get the class being static, but the methods are always... static within the class for me?

sour fulcrum
#
public class HelperInstance
{
    public string CombineTwoNumbers(int first, int second)
    {
        return (first.ToString() + second.ToString());
    }
}

public class StaticHelperInstance
{
    public static string CombineTwoNumbers(int first, int second)
    {
        return (first.ToString() + second.ToString());
    }
}
public class UsingClass
{
    public void Awake()
    {
        //Using the function implemented inside a instance context
        HelperInstance instance = null;
        Debug.Log(instance.CombineTwoNumbers(1, 2));

        //Using the function implemented inside a static context
        Debug.Log(StaticHelperInstance.CombineTwoNumbers(1, 2));
    }
}
frigid sequoia
#

I dunno, I just understand it as I am not referencing the method within an object, but rather a class that has that method, but the method is not being touched, so it's static

#

But I am clearly wrong

teal viper
#

No you're correct. A reference to an object is a reference to an instance of a class.

sour fulcrum
#

sometimes this word is used in programming in other ways but another way to think about static is using the word global

wintry quarry
#

That's what static means for a class

frigid sequoia
#

What if I make a method static on a non-static class? Can I access that method without an instance?

wintry quarry
#

Yep

sour fulcrum
#

thats what GameObject.Instansiate is πŸ˜„

wintry quarry
#

It's Object.Instantiate

sour fulcrum
#

oh right inheritence

#

ill go hide

teal viper
wintry quarry
frigid sequoia
#

So I suppose I can only use static variables on a static method?

sour fulcrum
#

you control what is required of the method

#

you can pass whatever into the method

wintry quarry
#

But if it's not a parameter, then only statics can be accessed

frigid sequoia
#

I mean not as a parameter, but as like something external on the class, like a counter or something

wintry quarry
#

Yes you can only access statics aside from the parameters

sour fulcrum
#

Worth noting of course in the context of gamedev that can usually include singletons that lead to instances

frigid sequoia
#

Yeah, an static feels kinda similar to a singleton

sour fulcrum
#

singletons use statics to operate yes

frigid sequoia
#

Like just one general class that hovers around

sour fulcrum
#

the reason why a singleton works and why only 1 can exist is because it relies on a static reference to the instance

#

and because it's static its just a singular reference that can only point to 1 thing

timber tide
#

Singletons better than static classes for most cases as they can still be deloaded easily by changing scenes without having to make some deconstructor

burnt vapor
#

Not to mention that methods and data is still tied to an instance, it's just that it's always a single one

#

So it's better to just ensure there is a single instance that you access instead of forcing everything so be one

burnt vapor
# frigid sequoia Seems kinda weird to grasp, I get the class being static, but the methods are al...

This is a very normal feature in C#. Often your code might not rely on a specific instance and is just used generally. Your case despicts a method that is used as a utility, not relying on anything that might despict a state, or something. Everything you need is contained within the method, so therefore it's better to just make it static and not require the user to create an instance of a class to access it.

#

Interesting that you find static methods weird to grasp, though. If a class is static, that means everything inside must by default also be static. This is not the case the other way around, however.

#

TL;DR on the whole conversation, but considering singletons are mentioned I do want to stress that a singleton is completely pointless here and will lead to overcomplication for no reason. Still, singletons are also very common so I do suggest you also look into those. In this case it is very common you just keep your utility method static, maybe even as an extension if it's suited as a common solution under that type.

glossy crystal
#

If I have a prefab, with a script attached to it that makes it move randomly every update frame, and I instantiate that prefab 5 times, why do they move in the same direction? I feel like I'm misunderstanding what prefabs are & what they are used for

twin pivot
#

random =/= true random

#

the randomness is based on something and if you make 5 of the same things it's all probably gonna land on the same value

glossy crystal
verbal dome
#

UnityEngine.Random is shared so you wont get the same values unless you set the same seed

#

So i dont think thats the issue

glossy crystal
willow pelican
#

Hello! I'm making a 2D game and was wondering how can I use different sprites for left and right directions (it's a soldier with an arm band on one side)

teal viper
willow pelican
#

But it's an animation

#

Running and idle animations

#

And stuff like that

teal viper
polar acorn
cyan pike
#

Hi, I'm having trouble with Raycast. I'm trying to change a Pacman tutorial project to connect nodes that make movement decisions of ghosts (I need the neighbor nodes to implement an A* pathfinding). But Raycast isn't colliding with another node. Perhaps nodes are generated with tilemap (they aren't in hierarchy if I don't start the game). I checked the prefab and runtime layers, and they are identical. Any ideas? I can show my code if you want.

wintry quarry
#

Also is this a 2d grid based project?

cyan pike
#

` private void CheckAndAddNeighbor(Vector2 direction)
{
float maxDistance = 50f;

    RaycastHit2D obstacleHit = Physics2D.BoxCast(
        transform.position, Vector2.one * 0.5f, 0f, direction, maxDistance, obstacleLayer
    );

    float distanceToCheck = obstacleHit.collider != null ? obstacleHit.distance : maxDistance;

    RaycastHit2D nodeHit = Physics2D.BoxCast(
        transform.position, Vector2.one * 0.5f, 0f, direction, distanceToCheck, nodeLayer
    );

    if (nodeHit.collider != null)
    {
        Debug.Log($"[Node] Hit node in direction {direction} at {nodeHit.point}");
    }
    else
    {
        Debug.Log($"[Node] No node hit in direction {direction}");
    }

    if (nodeHit.collider != null && nodeHit.collider.gameObject != gameObject)
    {
        Node neighborNode = nodeHit.collider.GetComponent<Node>();
        if (neighborNode != null && !neighbors.Contains(neighborNode))
        {
            neighbors.Add(neighborNode);
        }
    }
}`
cyan pike
wintry quarry
#

just check your grid to see if something is in the neighboring coordinate\

cyan pike
#

I didn't explain why I chose this technique, sorry. There are many nodes in the map, and setting neighbors one by one is harder than this approach

wintry quarry
#

There is no need to set neighbors one by one

#

we know from the grid structure who our neighbors are

#

thjey are the nodes at coordinates:
(0, 1) + our coordinate,
(1, 0) + our coordinate,
(0, -1) + our coordinate,
(-1, 0) + our coordinate,

cyan pike
#

Yes, but the ghosts calculate pathfinding only if they arrive in a intersection. Oh, I understand now... lol

#

I just need to call A* when they arrive in a node

#

I was trying to avoid setting a map as a matrix, that's why I chose nodes (and because in the original project the ghosts use the nodes to determine how direction chosen)

wintry quarry
zealous geode
#

Hello, addressing an issue I had yesterday, I have been trying with a possible solution that an user gave me, but i'm still having waypoint overshooting issues. The force applied doesn't seem to be enough no matter what value of deceleration I set, and the "orbiting" effect around the next waypoint is still there.

    protected override void UpdateVelocity()
    {
        float distanceToPoint = Vector3.Distance(travelPoint, transform.position);
        float currentVelocity = rb.velocity.magnitude;
        float stoppingDistance = (currentVelocity * currentVelocity) / (2f * Ship.Stats.Deceleration);

        if (distanceToPoint <= stoppingDistance + 2f)
        {
            rb.AddForce(-travelDirection * Ship.Stats.Deceleration * Time.deltaTime, ForceMode.Force);
        }
        else
        {
            rb.AddForce(travelDirection * Ship.Stats.Acceleration * Time.deltaTime, ForceMode.Force);
        }

        Debug.Log($"Stopping Distance: {stoppingDistance + 2f}, CurVel: {currentVelocity}, Distance to point: {distanceToPoint}");
    }

What i'm trying to accomplish is that the npc entity that uses this behaviour decelerates when reaching the detection limit stoppingDistance + 2f
It's a space based game so i'm using rb.drag = 0f and no gravity.

wintry quarry
wintry quarry
zealous geode
#

Yes, this is happening in FixedUpdate.

cyan pike
# wintry quarry but a grid-based graph (which is what A* operates on) can be represented in memo...

This is the original project, maybe it can be useful
https://github.com/zigurous/unity-pacman-tutorial

Yes, in this case, I would use a list, but the nodes are generated when I start the game, so I made the raycasts to detect their neighbors

GitHub

πŸŸ‘πŸ’ Learn to make Pacman in Unity. Contribute to zigurous/unity-pacman-tutorial development by creating an account on GitHub.

zealous geode
open apex
#

Any reason why the website doesn't work? I am clicking on "Get Started" but the page doesn't load

#

Can please someone else also give it a try?

#

and let me know if this is happening only to me

naive pawn
#

yeah seems to be giving 204s

open apex
#

thanks

naive pawn
#

unity learn's been having some problems lately, apparently

#

this might be one of said issues

open apex
#

Thanks for the help Chris!

wintry quarry
open apex
#

Any reason why I cannot see this 3d plane object?

polar acorn
#

Double-press F while hovering over the game view to focus on it

wintry quarry
open apex
#

I think I am close enough :d

polar acorn
open apex
polar acorn
#

Try looking at it from the other side

wintry quarry
#

Try looking at it from the bottom

#

though given it's rotation this should be correct IIRC

open apex
#

Checked other side

#

still the same

#

I am just trying to learn something 😭

#

Why is Unity giving me headeache everytime

wintry quarry
#

Actually I think your problem is this menu

#

I notice it's blue for you

#

which means you may have hidden some layers

#

make sure the eyeball next to the Default layer is not crossed through for you

open apex
rocky canyon
#

different menu

wintry quarry
#

the layers one

#

the one I showed the small picture of

open apex
wintry quarry
wintry quarry
rocky canyon
#

two sheets of paper w/ a star in the corner

wintry quarry
#

Lol he probably just got banned

rocky canyon
#

two layer cake being assaulted with a ninja star

rocky canyon
#

that was just plane silly..

analog timber
#

guys, I have a question, in terms of which is easier to program, what is the better option? a 2D game or a 3D game? i did some research on this, and I saw that a lot of people said 2d games are more difficult, and i wanted to know why

polar acorn
#

There's not a lot different when it comes to code

rocky canyon
#

the art style has little to do with the programming difficulting

#

imo

naive pawn
analog timber
#

alr thanks everyone

rocky canyon
#

πŸ™‹β€β™‚οΈ im in the group that believes 2D is harder than 3D, but has nothing to do with code, and more to do with art

#

i hear mostly the other way round tho

naive pawn
#

i can't comprehend 3d modelling πŸ™ƒ

polar acorn
#

2D is easier, but significantly less scaleable. 3D is more work up front but pays dividends for future assets

rocky canyon
#

fr tho, taking 3 2D images.. and making a 3D image basically just that lol thought this was unity-talk

open apex
#

❀️

hollow crater
#

Ok guys I really need help this is PISSING ME OFF SO MUCH.
Ok first question that is pissing me off : Do you use VSCode or VSCommunity ?
Second question : if you use VSCode, do you use extensions like Unity or things like that ?
if you use VSCommunity do I have to select Unity alone or Unity AND .NET ?
Third question : I use VSCode but when I follow EXACTLY the tutoriel it does this : (see images)
When I install unity extension on VSCode I have some errors and there are problems and it doesn't work.
Now I uninstalled the extensions but I have a new problem with the compiller (I don't know what that is) (see image).

naive pawn
#
  • VS Community is 2 separate words, the ide is VS and the free license for VS is the community license; this is incontrast to VS Code/VSC, which is the full name of the ide
  • unless the ide has stuff built-in, you'll generally always want extensions for the specific thing you're using. built-in stuff tends to be language support
#

you have not exactly followed the tutorial

#

configure your !ide

eternal falconBOT
ivory bobcat
north kiln
naive pawn
#

When I install unity extension on VSCode I have some errors and there are problems and it doesn't work.
those are issues with your code. you have to fix the issues.
Now I uninstalled the extensions but I have a new problem with the compiller
so you've now removed the notifications from your ide, so the compiler is telling you that you still have issues

polar acorn
polar acorn
#

You can't fix errors by removing the thing that tells you where they are

#

the errors are still there

hollow crater
north kiln
#

Increment the counter

polar acorn
naive pawn
hollow crater
rocky canyon
ivory bobcat
naive pawn
#

your code has issues

polar acorn
naive pawn
#

the extension just tells you where the issues are

#

so by removing the extension, you just blind yourself to what the issues are

hollow crater
polar acorn
#

Reinstall the addon, fix the code

naive pawn
#

@hollow crater buddy please stop being stubborn.
reinstall the extension. you should see errors.
hover over the red line and see what it says.

hollow crater
#

Rooh I ll do it and take another screen

ivory bobcat
hollow crater
naive pawn
#

uh, ok, we don't need to see those

rocky canyon
#

now do this

#

idk bout the Nuget stuff tho swry

naive pawn
#

make sure to fully configure your ide according to the instructions linked above

polar acorn
#

!ide

eternal falconBOT
polar acorn
#

If you did get errors before, you had it configured

#

then for some reason uninstalled the addon instead of fixing your errors

rocky canyon
hollow crater
#

Ok thanks for your answers everyone, I will uninstall it AGAIN and reinstall it with the guide maybe it'll change soomething (I don't think so)

naive pawn
#

why would you uninstall it again

#

installing it is like the first step of the guide

#

what it'll change is that you'll be able to see the issues you have

#

it won't magically fix the issues. that's your job

#

but to fix issues, you have to first know what and where they are

#

that's what the extensions do

hollow crater
#

I know but I'll begin from zero to be sure I didn't miss anything or whatever

digital haven
#

I need help. I am trying to get my model from mixamo to move when I press wasd but it’s not working. I need help, I’ve been working on this for like a whole afternoon and it still only keeps them in motion

rocky canyon
#

Hoxo #πŸ’»β”ƒcode-beginner message
Keep doing the IDE config stuff, but just wanted to point out the original issue is visible in this message..
Like one of those "One of these is not like the other" minigames..

wintry quarry
#

It's super blurry

#

but you need to have your console window open when you're using Unity

#

so you can see errors like this

#

This one is telling you that you're trying to use the old input system in your code but your project is configured to use the new system only

#

Do not ignore errors in your console.\

digital haven
#

Yeah I’ve been using tutorials online for this.

hollow crater
#

Wait I just saw the ; was missing. Is that what you'all were trying to say ?

wintry quarry
rocky canyon
#

config ur ide and ur ide will tell u

rocky canyon
#

if ur gonna be following alot of tutorials (most will probably be using the older system)
i like to set mine to Both but all up to u

#

good to start inching ur way into the new system tho πŸ’ͺ

digital haven
hexed terrace
trail wigeon
#

okie

balmy basin
#

Hi, I wanna do vector multiplications in unity, but I noticed im limited to 4 dimensions, is there a solution to this?

naive pawn
#

make your own vector structs?

balmy basin
#

thats a pain to do no?

#

Also im worried about efficiency over for example dot products

naive pawn
#

efficiency wouldn't be any different

balmy basin
#

Do you mean with a struct an array btw?

naive pawn
naive pawn
balmy basin
#

bigger then 4

frigid sequoia
#

How would it work to make a event for an instance of an object? ie: notify a character that he, and only him has apply an OnHit effect

balmy basin
#

I only need dot products of 2 vectors (im implementing a feedforward later of an neural network)

naive pawn
#

then sure...? i mean if it's all the same type regardless of dimensionality you wouldn't have any static guarantees about multiplying the same dimension vectors

#

i feel like this is overkill though

#

may as well just pass around your vectors as arrays and then have static methods to operator on those arrays, would be way simpler

naive pawn
frigid sequoia
#

Like, how do I subscribe a listener to an specific instance of a script?

naive pawn
#

by.. doing that?

frigid sequoia
#

But HOW do I declare that? This way is pretty much subscribing to all instances???

#

I am not sure I fully understand how this works

balmy basin
#

And if so, how do i make it working for my unity

naive pawn
# frigid sequoia But HOW do I declare that? This way is pretty much subscribing to all instances?...

ok so first off you have terminology backwards; here you get the effect of all instances subscribing to the event
but this action doesn't make all instances subscribe to the event at the same time
this just makes each individual instance subscribe to the event
so if you want only 1 instance to subscribe, then.. just have that single instance subscribe, just gotta have a way to know which single instance you're targetting

wintry quarry
#

The way you wrote EntitySelectSystem.OnEntitySelect implies that the OnEntitySelect event is static

frigid sequoia
#

It's static, that's what I was asking. I didn't know you could make non-static events

#

I want the BasicAttackManager of each entity to notify the rest of scripts on the entity that it has triggered an OnHit event, but just for that entity, not the rest

wintry quarry
frigid sequoia
#

Mmm, ok, I think I got it

#

Can I document the parameters of an event tho?

wintry quarry
#

not sure what you mean by "document", but yes, you can use any delegate type you want for your event

frigid sequoia
#

I mean like this but actually showing on the ide

rich adder
wintry quarry
wintry quarry
#

This requires you use a custom delegate type instead of Action<...>

#

(which is something I prefer anyway)

frigid sequoia
#

I barely understand actions to begin with, so I don't wanna add another layer lol

wintry quarry
#

Actions are just a shortcut to making delegate types

#
Action<GeneralBehaviourManager, int>``` is identical to defining a delegate type:
```cs
public delegate void BehaviourChangedHandler(GeneralBehaviourManager manager, int amount);```
and then using `BehaviourChangedHandler` wherever you would have put `Action<GeneralBehaviourManager, int>`
#
public delegate void BehaviourChangedHandler(GeneralBehaviourManager manager, int amount);```
is just:

**public **-> is the access modifier, (it's public so everyone can use it)
**delegate **-> the delegate keyword signifies we are defining a delegate type
**void **-> this is the return type (we don't return anything, just like Action does)
**BehaviourChangedHandler **-> this is the name of our delegate type. You can name it whatever you want
**(GeneralBehaviourManager manager, int amount)** -> this is the list of parameter types and names for the delegate type, just like a regular function
#

In fact since this way lets us name the parameters, that's the only way it would make sense for us to be able to document them.

#

Anyway using Action and Func are just shortcuts to defining your own custom delegate types, but they're not as expressive and you can't exactly document them well.

frigid sequoia
#

Mmmm, I think I get it, but I would rather stick to actions cause makes it easier for me to read it later

wintry quarry
#

I disagree on that point, but to each their own

#
public event CommandQueueChangedHandler OnQueueChanged;``` is much more clear and descriptive to me than:
```cs
public event Action<CommandQueue, int, CommandType> OnQueueChanged;```
frigid sequoia
#

Ye, I just ignore the event thing and read, oh, this is an action, sure

gloomy bison
#

hi, small error. i wanted my character to rotate the direction he's facing. he does it when moving but when stationary, he does this (photo 1)

the code:

Quaternion targetRot = Quaternion.LookRotation(moveDir);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, Time.deltaTime * rotSpeed);

the setup: (photos 2, 3, and 4)

Model was imported from blender if that helps

rich adder
gloomy bison
#
 if (charController.isGrounded)
        {
            moveDir = new Vector3(Input.GetAxis("Horizontal"),0, Input.GetAxis("Vertical")) * speed;
        }
rich adder
gloomy bison
#

thats the model's body

#

before play

#

it messes up more if i change it from that to 0

rich adder
# gloomy bison

the resting rotation here is -90 on x? that don't look correct as default

gloomy bison
rich adder
gloomy bison
#

the parent object gets changed to 90 though

#

idk if that's helpful at all

rich adder
#

no inputs = moveDir to 0,0,0

#

your 0,0,0 is not correct in the first place

#

the code is doing exactly what it should be doing, the wrong to fix is the model

gloomy bison
#

oh

#

right

#

so what do i need to do to fix it?

rich adder
#

either fix it in blender, or nest it inside another parent called "Graphics" where its 0,0,0 but child is -90 on x and rotate the "Graphics" object

gloomy bison
#

its rotating the parent -90

#

like the CharRig one

rich adder
#

wdym ? first put the CharRig at 0,0,0

gloomy bison
#

it is

rich adder
#

ok.. so show the hierarchy now

gloomy bison
rich adder
#

graphics should be at 0,0,0 and Cube at. -90, 0,0

#

rotate Graphics

gloomy bison
rich adder
# gloomy bison

yeah so now should be okay rotate the parent actually, CharRig ?

#

in code

gloomy bison
#

does the fact i used mixamo for rigging have anything to do w this? in blender the character is upright

rich adder
#

idk works fine when I use mixamo

gloomy bison
#

ahh the character's visuals were on the mixamo thingy and not "cube"

rich adder
#

blender usually has different axis system than unity tho

gloomy bison
#

ah

#

that could be it

rich adder
#

Z is up in blender

#

Unity Z is forward

gloomy bison
#

so does that mean that it's rotated in unity and not blender then?

#

so i should rotate it in blender and re-do everything?

#

would that be a quick fix?

rich adder
#

if you want you could , I mean usually the parenting thing does quick fix anyway

gloomy bison
#

alr well i'll try that then. thanks for your help!

rich adder
gloomy bison
#

parenting didn't, no. i think i might just be doing something wrong as it's 11:30pm

#

i'll probably fix it in the morning. thanks!

frigid sequoia
#

Does making a class abstract imply anything else other than allowing for abstract methods?

#

It just states it as some kind of interface does it?

polar acorn
frigid sequoia
#

So they are, like that, interfaces, right?

polar acorn
#

Abstract classes can contain code and private members, interfaces cannot

frigid sequoia
#

So they are just worse lol

grand snow
#

A class can implement MANY interfaces, but a class can only inherit from 1 class so they are not the same

#

abstract classes are so you can define some protected/public functions for something to inherit but prevent use of the base as its incomplete.

#

public abstract void DoThing() This MUST be overwritten by sub classes
public virtual void DoThing(){} This can be optionally overwritten

cyan pike
#

how to center a object in center of grid cell? I changed Unity 5 to Unity 6, now my object is centering on corner of cells when I press ctrl

grand snow
#

I presume you do not actually mean unity 5 because thats like 10+ years old

cyan pike
#

yeah, its just another old version, like 2021.3...

violet timber
#

anyone know how to solve these errors? Im new to unity

flint tendon
#

hey i was wondering how i go about importing mixamo animations and characters into my project and making them work with my fps controller

teal viper
sour fulcrum
#

oh wait wtf some of my stuff is in that screenshot 😭

#

@violet timber gotta ask in lc modding discord if your doing that kinda stuff

sour fulcrum
#

suprised that script is even included in a repo context πŸ€”

#

but yeah gotta go to repo server

teal viper
# violet timber Yes I am modding REPO

We don't really provide modding support here. You'll need to ask in the game modding community. The only thing I can guess is that you're missing some dependencies required for modding, maybe il2cpp build module. Make sure you follow some modding guide properly.

sour fulcrum
#

btw dlich if nomnom's unity patcher is in the error its 100% modding related

teal viper
#

Yes, that's why I asked it. The issue itself seems a bit more low level though.

sour fulcrum
#

ye, only reason i mention it is ive seen some studios use harmony for non modding reasons πŸ˜„

#

think they might have installed the wrong thing tbh, repo server will know

violet timber
#

alr thanks guys. πŸ‘

high summit
#
    public void Interactdoor()
    {

        if (!isOpen)
        {
            drawer.transform.DOLocalMoveZ(openvalue, 1f, false);
            (isOpen) = true;
            drawaudiocontroller.clip = drawopen;
            drawaudiocontroller.Play();
        }
        else if (isOpen)
        {
            drawer.transform.DOLocalMoveZ(closedvalue, 1f, false);
            (isOpen) = false;
            drawaudiocontroller.clip = drawclose;
            drawaudiocontroller.Play();
        }
    }
#

Hey folks! Trying to figure out why the first time I interact with the door nothing seems to happen, but the second time its fine

#

Actually, It does play the sound on the first click but doesn't move

#

Seems I had the bools backwards

frosty hound
#

Wrapping (isOpen) in brackets is unnecessary, by the way.

high summit
#

Oh really? Thanks for that

unique quartz
#

hello, I am getting this error when trying to make a game in unity and I don't know what it means, this is it: "UnassignedReferenceException: The variable groundCheck of PlayerMovement has not been assigned. You probably need to assign the groundCheck variable of the PlayerMovement script in the inspector. UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <fde3c13fb32a45329a891b3df03f7908>:0) UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at UnityEngine.Transform.get_position () (at <fde3c13fb32a45329a891b3df03f7908>:0) PlayerMovement.Update () (at Assets/scripts/PlayerMovement.cs:23)"

#

i have tried using all the methods my teacher has recommended and they don't work

#

i have been following a tutorial, and i have gone over it multiple times and done everything exactly, in the inspector the tutorial doesn't assign anything to the groundcheck variable with no issue, however when i do this, i have errors

#

the tutorial is from 2022 and i am using the latest unity model, is this perhaps the root of the issue?

frigid sequoia
#

If I reference a List like this (ignore the errors), I get a reference to the original list that will remain updated to anything that happens to the original list rather than getting a "snapshot" of the list right?

north kiln
north kiln
unique quartz
#

screenshot of the tutorial

north kiln
#

I don't have access to this tutorial, they probably assign the value later

#

The error isn't complicated

unique quartz
#

it doesnt

#

is there an issue with the tutorial?

north kiln
#

I don't have access to this tutorial

unique quartz
#

i can't give access to it

#

its a private school video

north kiln
#

It's impossible to say whether there's an issue with the tutorial. The error says the value hasn't been assigned, and you're showing that it isn't. So assign it the appropriate transform and move on

unique quartz
#

the tutorial doesn't do this