#💻┃code-beginner

1 messages · Page 487 of 1

wintry quarry
#

You can't find anything on Raycasting?

#

It's very common

sullen perch
#

sample terrain on raycast

worldly mural
#

If I want to have two game objects use the same script but react to different tags how can I do that? I'm guessing I could replace "Asteroid" with a variable but I don't know how to make that variable adjustable in the inspector

charred mist
#

quick question

#

once i get really big numbers it looks like this

#

not good for a text box cuz nobody knows what that is

indigo wave
#

I'm trying to complete my assignment for lesson 2 (throwing food at stampede. I've followed the lesson as best as I can, but for some reason, the animals keep spawning too swift and too close to one another . Here is the code for the spawn manager for better understanding.

eternal needle
charred mist
eternal needle
eternal falconBOT
charred mist
#

is there like a setting to disable scientific notation

eternal needle
eternal needle
charred mist
#

i could just switch to them in that case right

eternal needle
charred mist
#

ok thank you

night valve
# charred mist ok thank you

Btw it comes handy the other way, if you need to type a large number in your code, you can do this for example var largeFloat = 1000e8f; instead of counting zeroes

inner quartz
#

@teal viper Hello again, let's continue about my problem? I'm not English person and I only learn it now. So, look at this code. What I need to make with PlayerData class? What I need to change in Values class? And also, do I need change my SaveSystem class?
Values class: https://hastebin.com/share/motinuzoka.csharp, PlayerData class: https://hastebin.com/share/ifisafizew.csharp, SaveSystem class: https://hastebin.com/share/edogurapih.java

inner quartz
languid saffron
#

NVM, fixed it!

My cursor doesn't show when I open the menu in my 3D Game. This has been happening to other games of mine too, I cannot seem to fix it! Any little help would be greatly appreciated.

solemn fractal
#

At the end I fixed it in 20 minutes today after work with fresh mind.. Basically I created a method in my PlayerHealth Script and inside that method I was changing the variable to false, but I was activating that method in my SpawnManager, for some reason that was not working. Now I just instead of doing that creted the method inside the SpawnManager and worked. Must have been some kind of process order that was happening .

turbid pelican
#
using Unity.Collections;
using Unity.VisualScripting;    
using UnityEngine;
using UnityEngine.UIElements;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField]float jumpForce;
    [SerializeField] private float speed;
    [SerializeField] private LayerMask groundLayer;
    [SerializeField] private LayerMask wallLayer;
    private Rigidbody2D body;
    private Animator anim;
    private BoxCollider2D box;
    private bool isGrounded()
    {
        RaycastHit2D hit = Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, Vector2.down, 0.1f, groundLayer);
        return hit.collider != null;
    }
    private bool onWall()
    {
        RaycastHit2D hit = Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, new Vector2(transform.localScale.x, 0), 0.1f, wallLayer);
        return hit.collider != null;
    }
    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        box = GetComponent<BoxCollider2D>();
    }

    private void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        body.velocity = new Vector2(horizontal*speed, body.velocity.y);
        if (horizontal > 0)
        {
            transform.localScale = new Vector3(-40,40,1);
        }
        else if (horizontal < 0)
        {
            transform.localScale = new Vector3(40,40,1);
        }
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded())
        {
            Jump();
        }
        anim.SetBool("Run", body.velocity.x != 0);
        anim.SetBool("isGrounded", isGrounded());
        print(onWall());
    }
    private void Jump()
    {
        body.velocity = new Vector2(body.velocity.x, jumpForce);
        anim.SetTrigger("Jump");
    }
    private void OnCollisionEnter2D (Collision2D collision)
    {
    }
}

for my player whenever it touches a wall it only returns true for a few seconds and then returns false is there something wrong with the code?

timber tide
#

There's a big hint on the documentation of BoxCast if you go read it

#

Actually, maybe that only applies to 3D physics of shape casts, but usually those will not detect colliders inside of the cast.

#

Let me give you a better way to do this though and that is by invoking a collider directly instead of doing a casting query.

turbid pelican
timber tide
#

Trying to figure out what overload you'reusing here. What's those 2 parameters before the last signifying

timber tide
#

Ah, ok you're swapping the sprite scale for direction I see

#

Looks fine, the only thing I can think of is that the boxcast isn't detecting the collider inside of the cast

turbid pelican
#

whenever i give the wall a rigidbody it will work but idk why it wont work normally ;p

timber tide
#

Like I was saying, instead of querying a specific shape, I like to create multiple colliders and just invoke those. (It's easier to visually see and debug)

#

Collider for the bottom, collider on the side for wall

turbid pelican
timber tide
#

Can you debug that the scale x isn't changing

#

could be some other issues, but debug why it failed in the first place

maiden swift
#

So, I want to have an obstacle, it's a rectangle, on top of it I want to have ground layer, and sides would have wallLayer, how do I do that?

fringe plover
#

Is there any way to change GameObject layer at runtime?

timber tide
#

gameobject.layer, no?

willow scroll
willow scroll
fringe plover
lapis frigate
#

I have a class named unit and for some reason every time I try to accsess or change something about it I get the NullRefrence error but the thing is I Debugged it and I know for affact that the unit itself and its variables are not null so I dont know why does it happen

#

The SetHUD method is example for when it gives me the NullRefrence error

#

but when I debugged unit.unitName it gave me the right name

#

so unit.unitName is not null for a fact

fringe plover
lapis frigate
#

where do u see line 14?

fringe plover
#

i mean 17

lapis frigate
#

it is not

#

1 sec

fringe plover
#

line 42 stats manager?

lapis frigate
#

line 17 isn't null

fringe plover
lapis frigate
#

idk why does it happen

#

the thing is

#

every time I use / change any information for the class Unit I get a null refrence error

#

even though its not null for a fact

#

ok nevermind

#

I accutaly GOT IT

#

fnialy

eternal needle
lapis frigate
#

I was on it for hours yesterday

#

The thing is

#

the player was a unit class and not a class that inheriet from unit

#

and unit is an abstract class

eternal needle
#

that makes no sense in relation to this error

maiden swift
willow scroll
willow scroll
fringe plover
#

Okay

eternal needle
willow scroll
#

So, you player was of type Unit

eternal needle
#

Especially considering they said unit is abstract, you cant make an instance of it. Meaning itd be a compile error way before a null reference error

willow scroll
#

I still want to know how they've come to this conclusion

hallow acorn
#

hey is there something like a transform.forward but using rigidbody.velocity ?

maiden swift
#

But will probably become useful later

hallow acorn
stiff fjord
#

my player keeps moving even after i let go of the a or d keys i understand i can use getaxis horizontal and it all works well but i need a and d for the key rebindings i plan to do later

willow scroll
willow scroll
stiff fjord
willow scroll
hallow acorn
stiff fjord
willow scroll
#

Use Vector3.Scale instead

eternal needle
hallow acorn
willow scroll
#

It affects the performance

#

But there is no quaternion used in the code

#

The thing is that Quaternion has a multiplication operator on a Vector3, but it doesn't work othwerise, therefore, the Quaternion has to come first

public static Vector3 operator *(Quaternion rotation, Vector3 point);
willow scroll
eternal needle
stiff fjord
willow scroll
stiff fjord
willow scroll
stiff fjord
willow scroll
#

Also it seems that you have to use Time.fixedDeltaTime (or Time.deltaTime) with MovePosition anyway. My bad, sorry for that

#

Just make sure it's put in FixedUpdate

willow scroll
hallow acorn
#
``` what can i do so my rotation doesnt reset to 0 without input and goes farther the longer i hold the input
languid spire
hallow acorn
languid spire
hallow acorn
#

i dont understand i mean it rotates as it should basicly it just doesnt stay on the rotation it should

languid spire
#

there is no way that code comes even close to working

languid spire
#

A video tells me nothing. But if you dont believe me, go and do some research on the difference between values held as a Quaternion and those held as Euler angles

hallow acorn
#

wdym like for something that doesnt work it looks like it works just fine

modest dust
#

The only reason it "works" is because of playerControls.flying.ReadValue<float>() * RotationSpeed. Quaternion values are in range -1 to 1, whatever rotation you're getting is basically ~0 + value_you_read

#

Once there is no input the only value that's left if the quaternion value from your rotation, again in range -1 to 1

vestal adder
#

!code

eternal falconBOT
hallow acorn
modest dust
#

Everything will work as long as you use it correctly

hallow acorn
#

transform.Rotate(0, playerControls.flying.Yaw.ReadValue<float>() * RotationSpeed, 0); did i use it Correctly?

vestal adder
#

this is my "typewriter effect" script which i use to display text, i have it set up to send an event action when the text is complete, but im not sure how to go about using those events to interact with other scripts and tell them when to swap to the next line of text

hallow acorn
modest dust
hallow acorn
#

ok i think it works pretty correct

stiff fjord
#

is this maxfilecount now a constant?

slender nymph
#

no

stiff fjord
slender nymph
#

what did google say?

stiff fjord
slender nymph
#

#854851968446365696

⚠️ Before Posting
🔍Search the internet for your question! 🔍
⠀+ Use the API Scripting Reference and User Manual.
⠀+ This troubleshooting site for commonly posted issues.

#

and your question is easily answered by a 10 second google search

stiff fjord
#

this?

slender nymph
#

do you have any errors?

stiff fjord
slender nymph
#

if you do not have errors after writing that code using the const keyword which google would have told you is used to create a constant, then clearly you did it correctly.
as for whatever this other screenshot is for, i don't know what you are asking there

languid spire
round obsidian
#

Is it a good idea to start from Unity starter controllers and customize it for our needs ? (like the third person controller)

slender nymph
#

if that is how you want to start, then sure

slender nymph
eternal falconBOT
vestal adder
inner quartz
#

How to change text of the child

wintry quarry
inner quartz
#

I have gameObject, it's not specific component...

wintry quarry
#

GameObject doesn't have a "text" property

#

Look at the line of code right above yours

#

Everything important is on Components

inner quartz
wintry quarry
#

You should try to understand what the code actually does

#

.transform gets the Transform component of whatever you call it on

#

I don't really understand the question to be honest

inner quartz
wintry quarry
#

Look at the red underline

inner quartz
night valve
#

Logic based on gameobject names feels so wrong

slender nymph
#

it is typically a bad idea

wintry quarry
# inner quartz

Two problems with this:

  • the text object is likely a child of this object, not the same object
  • it's very unlikely you're using Text which is the legacy component. Most likely it's TMP_Text
night valve
# inner quartz How to change text of the child

I'd recommend using enums in this case, or making a base class Toggle and child classes like MusicToggle, SFXToggle, or making an IToggle interface with Toggle function. Maybe for a single-person project it is somehow manageable to operate on strings, but still error prone. Doing this while working in a team is a no no. Still, even for solo proj it's best to learn correct practices instead of getting bad habits

burnt vapor
#

Abstracting everything into a Toggle just limits your code in the future, and generally it solves nothing

#

And instead of an enum you're better off using an constant if you are trying to avoid magic strings. Regardless I would wrap this in a method that takes a boolean instead, and call the change from there. It would be a decent place to call for the component, and the boolean can indicate if something is on/off

night valve
#

whether to abstract this out or not is a matter of project design, but it is always better than checking gameObjects name

burnt vapor
#

Name? Are you referring to the Find method being used?

#

The correct solution there is to just not use that at all

night valve
#

no, the parent if check

#

if(gameObject.name == "MusicToggle"

burnt vapor
#

Oh, we're looking at two completely different things

night valve
#

there's thousands of solutions for this, he picked the worst ;p

cosmic dagger
burnt vapor
#

My Discord didn't scroll all the way up, I thought it was about setting the text

#

Right, I see what you mean. I assume this is a toggle visual and I agree you might as well create a prefab/reusable component for this

#

I feel like that code is wrong, though. I get the idea this person is trying to define multiple toggles, only varying by their gameobject name. That's not a good idea

night valve
#

yeah, a toggle should have only one method and one boolean field, nothing more. So inheritance is the proper approach here

#

optionally some notification mechanism, but SFXToggle should not even consider "am i being a MusicToggle?"

crimson ibex
#

I am facing a very frustating problem since 2+ months. It has slowed down my development and made my experience a misery. Please help with few details I can give.

  1. Problem is simple - whenever I make any changes in my Codebase, the Visual Studio (and VS Code) intellisense stop recognizing Unity SDK and may be dotNET SDK.
  2. It happens after Unity rebuilds on any Code changes.
  3. If I reopen Visual Studio, I get autocomplete and other intellisense functionalities. But as as Unity build happens for any change, it even does not recognize "List" and starts throwing error in IDE.
    I know it is not exactly Unity. But I am stumped for months. 😦
brittle kelp
#

how do i use this.activate ?

#

like this?

deft grail
#

there is .SetActive / .enabled? if you mean that

brittle kelp
#

oh .SetActive?

deft grail
#

yeah

stuck field
strong pewter
#

yall know why my presets in starter assests show 9 instead of 12?

brittle kelp
shell oriole
#

hi! im really new to unity and i'm trying to make some velocity based movement, but it really doesn't work. no errors. just jitters all over the place.

deft grail
shell oriole
stuck field
# brittle kelp i dont know i didnt save yet

Hm, well some issues I see is using "activate" - thats not real, use .SetActive (As was said), or .enabled for components, but that isn't what you are doing.

Second issue, GameObject.allthestuffneededforhardmode won't really exist either

#

Banana would you like me to provide some sample code to show you how it would be done?

shell oriole
strong pewter
#

im having trouble with this:

it shows 9 instead of 12.. i keep restarting and the same thing happens to me. Yall know why?

strong pewter
#

cross post?

stuck field
languid spire
#

post the same question in multiple channels

strong pewter
#

huh

#

i didnt

#

i've just talked

#

here

languid spire
strong pewter
#

wait

#

oh my bad

#

now its gonecatto

languid spire
strong pewter
#

it wont let me say uh

stuck field
brittle kelp
stuck field
#

It basically means provide you with some code to learn off of

strong pewter
brittle kelp
stuck field
stuck field
stuck field
strong pewter
#

it no work😭

stuck field
#

Or update the package if it's not updated

#

But I assume it is

strong pewter
#

i did that like more than 10 times

#

ive been working on it since aug 4😭

stuck field
#

Also @brittle kelp

// These are just setup as normal bools would be inside a class, i'm just lazy to make a class right now
public bool IsAllowedToDoIt = true;
public bool IsAllowedToDoItConfirmed = true; // Just made 2 because you had 2 to show you how that would work

public List<GameObject> ObjectsToEnable = new List<GameObject>(); // You can put your gameobjects into this list in inspector

public void EnableObjectWithConditions()
{
    if (IsAllowedToDoIt && IsAllowedToDoItConfirmed)
    {
        foreach (GameObject obj in ObjectsToEnable)
        {
            obj.SetActive(true);
        }
    }
}
stuck field
#

This is how the code should be formatted ^

#

Np, don't just copy it and stuff, learn off of it as well so you know what to do next time

strong pewter
stuck field
#

What version of the samples are you on?

strong pewter
#

these versions (also delted sum cause they took storage)

#

oh wait

stuck field
strong pewter
vestal adder
#

dark did you have some particular learning method for becoming proficient at 10 languages

stuck field
strong pewter
stuck field
# strong pewter how?

No idea, you'll have to figure that out on your own, you could search up how to downgrade unity packages

vestal adder
#

i prefer to learn like that since its more fun

#

takes a while though, no?

stuck field
#

If it takes a while for you, you just need to be patient in your learning

vestal adder
#

if only i was a faster learner

stuck field
fluid oxide
#

guys i made a game and every time u swipe it should appear 2 platforms so u can jump on it but everytime i swipe it dosent work and it dosent add any platform why?

stuck field
fluid oxide
#

ightt

#

using UnityEngine;

public class SwipePlatformSpawner : MonoBehaviour
{
public GameObject platformPrefab;
public float spawnDistance = 10f;
private Vector2 startTouchPosition;
private bool isSwiping;

void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            startTouchPosition = touch.position;
            isSwiping = true;
        }
        else if (touch.phase == TouchPhase.Ended)
        {
            Vector2 endTouchPosition = touch.position;

            if (isSwiping && IsSwipeUp(startTouchPosition, endTouchPosition))
            {
                SpawnPlatform();
            }

            isSwiping = false;
        }
    }
}

private bool IsSwipeUp(Vector2 start, Vector2 end)
{
    float swipeDistanceY = end.y - start.y;
    float swipeDistanceX = Mathf.Abs(end.x - start.x);
    return swipeDistanceY > 100f && swipeDistanceY > swipeDistanceX;
}

private void SpawnPlatform()
{
    Vector3 spawnPosition = transform.position + new Vector3(spawnDistance, 0, 0);
    if (platformPrefab != null)
    {
        Instantiate(platformPrefab, spawnPosition, Quaternion.identity);
    }
    else
    {
        Debug.LogWarning("Platform prefab is not assigned.");
    }
}

}
i told chat gpt i understand some of code i asked him cause idk how to type on yt

stuck field
# fluid oxide using UnityEngine; public class SwipePlatformSpawner : MonoBehaviour { publ...

Well some issues I see (Just before I go to bed, this is my last message, you'd have to ask another if what I say doesn't work): Possibly because you are checking the value for 100 distance, which is a lot I believe, so maybe try put that down and test again, put it at like 1, see if it works, if it does, keep going up until you get a good value.
Also add some debugs in your code at points to see where your code ends, then say where it ends (What doesn't execute) so other people can help you fix it easier.

vestal adder
#

debug to check if the input is working

strong pewter
rich adder
eternal falconBOT
stuck field
gilded stag
#
        {
            if (distance.magnitude < maxDistance)
            {
                //checks if distance magnitude is less than max distance then it finds a fraction and multiplies the normalized version of force by this fraction and negates it
                force = -force.normalized * 10 * distance.magnitude / maxDistance;
                //adds force to the rigidbody velocity
                rb.velocity = force;
            }
            else
            {
                //as distance is greater than max distance, the force is equal to max force and this is added to rigidbody velocity instead
                force = -force.normalized * 10;
                rb.velocity = force;
            }
        }```
#

for some reason the raycast in the if statement doesnt work and im not sure why

vestal adder
gilded stag
#

the debug.log isnt returning in the console

#

and when i press on the mouse button and the ball is on the ground, it doesnt do anything

steep rose
gilded stag
#

i did it earlier

steep rose
#

show us where you put it

gilded stag
#

in a different if statement with only the raycast statement

#
        {
            if (distance.magnitude < maxDistance)
            {
                //checks if distance magnitude is less than max distance then it finds a fraction and multiplies the normalized version of force by this fraction and negates it
                force = -force.normalized * 10 * distance.magnitude / maxDistance;
                //adds force to the rigidbody velocity
                rb.velocity = force;
            }
            else
            {
                //as distance is greater than max distance, the force is equal to max force and this is added to rigidbody velocity instead
                force = -force.normalized * 10;
                rb.velocity = force;
            }
        }
        if (Physics.Raycast(transform.position, Vector2.down, 10f))
        {
            Debug.Log("True");
        }```
teal viper
#

Never remove debug logs when you're asking for help. We need to know wheat you tried and how.

gilded stag
#

why is it indented weirdly

#

the debug.log is outside the first if statement

steep rose
#

have you tried making the raycast longer?

#

have you tried putting in a layermask?

gilded stag
#

yes and yes

#

the radius of my ball is 0.5

#

and i have it set to 10

#

the raycast set to 10 distance

#

and it does the thing i want it to do without the raycast

vestal adder
#

i think you should visualise the raycast with debug.DrawRay

gilded stag
#

wait

#

its raycast2d?

rich adder
#

You dont even need DrawRay anymore, the Physics Debugger now shows all casts

gilded stag
#

is there a raycast2d?

steep rose
rich adder
steep rose
#

then yes use raycast2D

gilded stag
#

i had this issue before as well

#

i forgot 2d physics is a thing too

#

thank you for your help

vestal adder
#

easy mistake

rotund garnet
#

i need to generate my tile based world infinitely as my player walks outward, so would it be best to have a world generation script on the player, or have the script on each tile, so they replicate themselves?

#

basicly: more scripts = bad?

slender nymph
#

neither. world generation should not be the responsibility of the player, nor should it be the responsibility of individual tiles. you should have a separate object that handles world generation

rotund garnet
#

so just place it on an empty game object in my scene?

rotund garnet
#

okay

#

thx

shy tiger
#

Another little bit help if ya don't mind, how to do like close the game?
The object is its force close if we touch that yellow
(Also, is my code are wrong?

#

(This should be last help

slender nymph
#

i said do the beginner courses, not repost your question here. and get your !IDE configured too

eternal falconBOT
shy tiger
#

Alright, thanks.

neon ivy
#

I need a piece of ground to follow the player around on the xz plane (so it's always underneath the player) so I don't have to have an insanely huge collider in this huge flat open space I'm making, but setting the position every frame is bound to mess up collision between the player and the ground. I'm not sure how to approach this...

wintry quarry
#

second - I think actually setting the position of the collider every physics frame won't cause many issues either.

#

e.g.

Transform target;
Rigidbody myRB;

void FixedUpdate() {
  Vector3 oldPos = myRB.position;
  Vector3 newPos = target.position;
  newPos.y = oldPos.y;
  myRB.position = newPos;
}```
This will be fine tbh
steep rose
#

1 big collider wont cause performance issues if thats what you are worried about

#

now if the mesh has a ton of tri's and vert's then thats a whole different issue

#

but if it is just a box you will be okay

neon ivy
#

even if it's like 10k by 10k?

steep rose
#

yes

#

its only 4 vert's well should be if you are in 2d, 8 if you are in 3d

#

and if its static, its even less on performance

neon ivy
#

I guess, I'll just make a big ol floor collider then xD

terse plume
#

This ain't code but I am not sure where to ask:
Does this setting thingy work? How should I use it? I changed it to 256 and built again and my textures ain't 256 😛
(I did a clean build, still no 256 😛 )

slender nymph
#

use id:browse to find relevant channels for your questions instead of posting in an unrelated channel.
but what are you expecting to happen with that setting

terse plume
#

all images bigger than 256 to be resized to 256 🤔

slender nymph
#

and how have you confirmed that the textures have not been imported with a max size of 256x256

#

it also appears you have not even applied the overrides

terse plume
#

oh 🤦‍♀️

#

I feel very dumb 🤦‍♀️

#

thanks ❤️

obsidian parcel
#

so i have made the game in unity but for some reason the device is heating up for no reason art is very minimal and also code is also not that much i am getting the 120 fps on phone and 800 fps on pc but im not sure why my android device is heating up any idea?

wintry quarry
obsidian parcel
#

any advice or something that can help me to make that heating issues less

wintry quarry
#

profile your game and optimize any hotspots so that your device has to do less stuff to make the game happen

#

Or limit your framerate

obsidian parcel
#

will try these stuff

keen dew
#

This is why phones usually limit the framerate to 30 or 60 fps

solemn cedar
#

i've dragged a rigidbody2d into here, and whenever i click play the rigidbody gets unnasigned and it gives me this error

deft grail
rocky canyon
#

u arent draggin in a prefab reference are you?

solemn cedar
deft grail
solemn cedar
rocky canyon
#

the rigidbody must be in the scene

solemn cedar
rocky canyon
#

what is Bird ? can u show the hierachy of this script and the bird rigidbody?

#

soo everythings on Bird im guessing

solemn cedar
#

the rigid body and script yes

deft grail
solemn cedar
#

the camera is normal

#

what

#

its working now

#

all of a sudden

#

i literally just dragged it in like before

rocky canyon
#

i dont know why the slot would become empty when u start..
but since its on the same gameobject

you could do:

private Rigidbody2D myRB;


myRB = GetComponent<Rigidbody2D>();

}```
#

to assign it via the script

deft grail
solemn cedar
deft grail
#

you can make your screen a different colour when in playmode to avoid this

solemn cedar
#

it'll save me from future headaches

deft grail
solemn cedar
#

somewhere here?

deft grail
#

1st one under general

solemn cedar
#

thank you

rich adder
#

surpised this isn't default tinted..

rocky canyon
#

i actually prefer the lightly grey tint

#

was really helpful at first tho to have a color (purple ftw)

#

ysssir

faint osprey
#
    {
        Debug.Log("working");
        yield return new WaitForSeconds(2);
        Debug.Log("working1");
        while (inMainSequence)
        {
            var carbonPush = Instantiate(Carbon, UICan.transform);
            carbonPush.transform.SetAsFirstSibling();
            carbonPush.GetComponent<Rigidbody2D>().AddForce(Random.insideUnitCircle.normalized * carbonSpeed, ForceMode2D.Impulse);
            yield return new WaitForSeconds(carbonSpawnRate);
        }
    }``` for some reason working is being called but working 1 isn't and i dont know why
polar acorn
faint osprey
polar acorn
faint osprey
#

an object that gets destroyed just after calling start coroutine

polar acorn
#

So then the coroutine is stopped when that object is destroyed

#

Call StartCoroutine on an object that will actually stick around

faint osprey
#

hmm so coroutines arent dependant on the gameobject their attached to

#

thats odd

polar acorn
#

that behaviour is running the coroutine

#

It doesn't matter where the function that return IEnumerator is, since that's not the object running it

willow scroll
#

Try starting a Coroutine using another MonoBehaviour, and you won't be able to stop it from your current script

waxen adder
#

I've seen in some components that you have to click a flag/boolean to get access to some settings. How can something like that be done to my own scripts?

slender nymph
#

write a custom inspector for it or use something like Naughty Attributes or Odin Inspector which both have attributes that can add that functionality

waxen adder
#

Ah ok, so it's not something I can do by default (without writing a custom inspector)?

waxen adder
#

Gotcha, ty

wintry quarry
waxen adder
#

Oh, this begs the question actually. What do you guys prefer? Naughty Attributes or Odin Inspector?

wintry quarry
#

Odin is very heavy, but more feature rich

#

Naughty is more lightweight

#

most of my projects don't get far enough to ever actually need Odin features

#

Odin's serializer is also famously slow

waxen adder
#

Hmmm. Sounds like I might start with Naughty then

bold saffron
rich adder
#

besides that, you should put some logs and see what is happening inside if statements

#

Quternions do not go above 1, so -90 for example is nonsense angle

bold saffron
#

oooh

rich adder
#

work euler angles instead

bold saffron
#

alright, thank you!

bold saffron
rich adder
#

Quaternion.Euler(xyz)

bold saffron
#

Thank you!!!

stuck palm
#

is there an event for when the editor saves?

rich adder
stuck palm
rich adder
stuck palm
wintry quarry
#

Sorry - had some discord lag

#

didn't see the newer messages

bold saffron
bold saffron
#

I gettin double the help, this is sick 🙏

covert owl
#

I FINNALLY DID IT

#

WOOOO

covert owl
#

NEVERMIND ssunCri

vagrant harness
#

I need to use a TryCatch to move files, but I also need to move the files asynchronously- anyone know what I can do? I'm at a loss.

teal viper
vagrant harness
teal viper
# vagrant harness Yeah- TryCatch cannot be used in coroutines
  1. You should clarify that you're using a coroutine I. The initial question. I expected you using async await.
  2. Share the actual error.
  3. You could try extracting the file loading part(including the try catch) into a separate method that is called from the coroutoutine.
  4. Putting file loading in a coroutine is not gonna help, unless the file loading is async as well. Maybe share your code as well.
covert owl
#

im having Sprite Issues out of all things

#

when i place the sprite down the actual visual and the info box are just off set

covert owl
#

where the game thinks its at

#

i dont know the proper term sorry

vagrant harness
covert owl
#

it offset by 2

#

these are the settings

deft grail
covert owl
#

you see that is what i thought, but that dosent chang a thing

polar acorn
#

Did you change the positions after changing the anchors

covert owl
#

yes

teal viper
#

Was there an actual question?

#

I only see 2 screenshots and some sentences that don't really explain much without context.

covert owl
#

kinda made it better, but that because i took the 2x2 version and just made it bigger

#

questing is how does one shift it up & over by .5

steep rose
#

can you not just drag the UI element where you want?

teal viper
#

Shift what? The grid? The icon? Is it even an icon? Is it part of the canvas ui?

#

Too many variables that we don't know...

covert owl
teal viper
#

What asset??

covert owl
#

i dont get how that was difficult

#

wdym??

#

the black box with a crappy pickaxe on it

#

yhea its hard to see with all the words

teal viper
#

You need to start talking in full sentences. Explain what you're trying to do. Explain your setup. Explain the issue. Read #854851968446365696 on how to ask questions correctly. We don't need to be playing the guessing game here.

covert owl
#

you are the only one want to play a guesing game

teal viper
covert owl
#

im done with you

teal viper
covert owl
#

it would be easier then getting YOUR "help"

steep rose
# covert owl i dont have a UI

wdym no UI? also dilch was asking for more information, you were instead giving loose information of which we have to guess

#

if you have a canvas you should have some UI elements

covert owl
#

i dont have a canvas

#

one last thing

#

i did it WOOO

deft grail
steep rose
#

or some UI element

mortal spade
#

I want to find all AudioSources in a scene, then store them in an array. Anyone have any good pointers? I'm looking this up but I don't see anything on it.

teal viper
mortal spade
covert owl
steep rose
#

i dont think UI works without it

lilac moth
#

Can anybody assist in making my character's jumping more smooth?

I have a rigid body character and Im using this to jump:
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);

The jump works, but it's too immediate/not smooth. I want it to behave more floaty and smooth like when jumping with a character controller component

steep rose
deft grail
covert owl
steep rose
lilac moth
teal viper
lilac moth
deft grail
#

to make it not so fast?

steep rose
#

but yes do what dilch said, im curious

lilac moth
steep rose
#

that looks normal, nvm just read your text

lilac moth
#

red is using character controller and is what I want blue to jump like (blue is using rigid body). Perhaps you all are right about gravity, but I play with it and it doesnt work like red

deft grail
#

and what is your jump force

lilac moth
#

jump force right now is 500

deft grail
#

the default is 1 if im not wrong

steep rose
#

are you perhaps calling your function in Update()?

deft grail
#

that doesnt really matter much anyway since its an Impulse, shouldnt give results like this

teal viper
#

Ah,it has mass of 10. Didn't notice

#

In this case it's something like 50 m/s

#

Enough to to move 50 meters/units in one second if ignoring gravity.

lilac moth
#

I changed jump force to 100, player mass to 1, and kept gravity at 15. It still jumps too fast. Am I missing something you are saying?

lilac moth
deft grail
#

jump force should not be that high

teal viper
teal viper
steep rose
#

is anything in your code messing with velocity or are you ever slowing your character down in some way?

deft grail
#

!code

eternal falconBOT
deft grail
#

can show the full code

lilac moth
deft grail
rich adder
#

You should not have KeyDown in FixedUpdate btw

lilac moth
#

but that wouldnt affect the jump behavior, just when it is triggered?

rich adder
#

Button/KeyDown is a one frame event it would be hard to always get it on the physics loop, does it sometimes miss the jump ? the GetButton is probably not making you feel the jank as much, still it should be in update

lilac moth
#

but right now I just cant figure out the actual jump. It just happens so fast. I dont know if my gravity is too low, force is too high, etc

rich adder
#

1 or 2 mass is ok. Jump force too high

deft grail
#

wait

#

your gravity is at 15?

#

or -15

teal viper
#

The velocity applying is also weird to be honest.

#

But the main issue is probably the force and gravity combo.

#

Applying 0 velocity on y would basically negate the jumping velocity on the next fixed update.

rich adder
#

yup that should be rigidbody.velocity.y inside the Vector3

teal viper
#

Which could explain why it's stopping abruptly despite moving so fast.

lilac moth
#

Thank you all so much!

#

I was so focused on the jump and not my other movement code

ember tangle
#
{
    return Directions.DefaultIfEmpty(None).FirstOrDefault(direction => direction == vector2Int);
}```

So if I understand this correctly, FirstOrDefault() is a lambda expression where each direction in Directions is returned if it matches the function argument? What is DefaultIfEmpty(None) mean here?
valid finch
#

I can't seem to get the visioncone to reveal stuff in the fog of war.. i have been messing with this for hours.. The 1st photo is sceneview.. the 2nd is sceneview in playmode.

wintry quarry
#

DefaultIfEmpty(None) means return whatever None is if Directions is an empty collection

#

None is presumably some variable defined elsewhere in the file

eternal needle
#

do you even need that DefaultIfEmpty, when you have FirstOrDefault?

ember tangle
#

Yeah 'None' in this case is basically Vector2Int.zero. I want to remove the DefaultIfEmpty because its impossible for the Directions list to be empty

#

but I wanted to understand it before I did that

#

thanks

wintry quarry
#

Yeah you can remove the DefaultIfEmpty

wintry quarry
rotund hull
#

I am trying to make a pixleated look for my game using a render texture, but any movement is like drawing on the camera and it stays

slender nymph
rotund hull
teal viper
#

What is the actual question?

#

Is it something along the lines of "how do I implement a dialogue system"?

#

That is not a question

#

It's a statement

glass totem
#

like back and forth

#

constintly

teal viper
#

Read my messages.

#

It is not a question

wintry quarry
# glass totem constintly

you're getting way ahead of yourself. Just start with something simple like detecting when the player walks near the NPC and presses a button. You have to work up from the basics before you get to the whole system

#

If you're looking for how to do the whole system, find a tutorial

teal viper
#

Question implies asking something and has a question mark at the end.

#

None of your messages actually ask something.

polar acorn
#

What about dialogue trees

teal viper
#

The answer is 42

#

Please learn to convey your thoughts correctly. Ask "How do I implement xyz?", instead of "I want xyz." Make it easier for people to understand you and you'll get proper answers.

slender nymph
#

That is the answer to the ultimate question of life, the universe, and everything, which of course is not known in this universe. You did not ask a question, so we can only assume you wanted to ask a question that nobody knew

vagrant harness
#

This feels wrong.

teal viper
low wasp
#

Hey yo! I am trying to implement spawning 10 game objects at random times. I was able to get it working but they all spawned at the same random time. Can I add the random code to each car spawn, add it in a way to get each to spawn differently, or have 10 different scripts that spawns each car differently?

It was to large.
https://hastebin.com/share/olodapopev.csharp

vagrant harness
eternal falconBOT
low wasp
teal viper
#

Though maybe pay attention to naming conventions.

vagrant harness
#

Are single words not Sentence case?

teal viper
#

You mean Pascal case?

teal viper
#

It doesn't matter if it's a single word or not. In this case it should be came case, since it's a field.

#

Pascal case is only used for methods and properties within a class.

vagrant harness
#

Anyone know why my ternary operator isn't working? (Yes, I will replace the magic numbers with actual variables soon.)

#

Nvm

#

Forgot the f lol

vale karma
#

Hello, I am building a 3d L-System, I have the rules implemented and it all seems to work. The only problem is the right side, of the fractal seems to reset its Z position ONLY on the right side, even if I flip the code right/left it does the same. Heres a vid, heres what im aiming for, and heres the code ( one sec to get it all sent)

umbral belfry
#

nice fractal

vale karma
#

its not completeddddddddd

#

thankyou tho

#

im dumbfounded, whats funny is i can accidentally do the same thing to the other side, because i set z to zero unintentionally, so im trying to find where i did that on the other side but havent yet

languid spire
vale karma
#

yessirr

#

actually all it is is a skinnedmesh collider with a blendshape key

languid spire
vale karma
#

trying this now

#

no change on the result

#

i feel like its a coincidence that the left side lines up the way it does. the first branch moves correctly, but not the Z value after for techincally both branches. the left branch just so happens to get the right calculation to match up, while the other side is offset by the same distance, which im guessin equals 0 for the right side.

languid spire
vale karma
#

i took out the 1.01

#

but yes, i think its a culprit, the bounds.max only gives a constant size for the y among all sticks ig, and the reason i have it like that is when i change the stick scale it will reach into the individual updated size and not the constant

languid spire
#

change yur Debug.log to include the local position as well as the position

vale karma
#

or so i would hope, its been a terrible work around

#

local on the right

#

it would be helpful to say that each stick is parented under another, organized in a way to pick of parts

#

i wish there was a clearcut way to track the top of a blenshape object. probably RecalculatingBounds() but it doesnt work on the mesh fsr.

languid spire
vagrant harness
#

This sentence is to convey a sense of confusion and the sender's inability to solve this themself, as they have already tried and failed to. This sentence is overly verbose to comply with this Discord server's message posting rules, which prohibit single word messages, which would've likely been sufficient in this context.

languid spire
vagrant harness
#

Thx

languid spire
#

next time read the docs

vagrant harness
#

I did.

languid spire
#

And does that not show you need a Collider parameter?

vagrant harness
#

Oh turns out I accidentally had it in the OnTriggerEnter method- I really should post full code lol

languid spire
#

I know you don't but the docs show that you should

vagrant harness
languid spire
#

yes it does

vagrant harness
#

Output variables aren't always required though

languid spire
#

that is not an output variable

vagrant harness
#

You get what I mean

languid spire
#

well, if there was an override that took no parameters the docs would reflect that

modest quarry
modest quarry
hexed terrace
#

Your buildingManager is null. Most likely the BuildingManager.Instance isn't ready when Awake() is called

modest quarry
#

i did the samefor a UI element and it works inthat?

#

is it different for that?

teal viper
modest quarry
#

okay

burnt vapor
#

private BuildingManager BuildingManager => BuildingManager.Instance;

#

Assuming you call this property after all Awake methods were fired (which you should), it will not be null.

#

Alternatively assign it in the Start method

modest quarry
#

yes assigning in start works

red helm
#

Can someone help me out on an error

#

There is a button, and when it is clicked it will change scenes, I tried rewriting the script, making another button, but there is always this error

deft grail
# red helm

might just be an editor warning not sure, try restarting unity / ignoring the error completely

red helm
burnt vapor
#

The warning means you have a Monobehaviour script attached somewhere of which the reference can no longer be found

#

Can for example happen when you change scenes and unload the scene that had it

languid spire
# red helm

This kind of warning generally appears when you modify a script when in play mode, ignore it

red helm
#

Thanks for the help

keen cargo
#

hey yall, quick question - so i'm developing a tracking state for a state machine enemy ai, however i'd like it so the ai goes as close to the player's original destination as it can before it goes to the alert state

currently this has a stopping distance, if i change it to something like (distance < 0.1f), the ai completely breaks in which i assume is a floating point error as it gets stuck in the tracking state

here is the code:

void Track()
{
    enemy.indicator.material.color = Color.magenta;
    enemy.navMeshAgent.destination = enemy.lastKnownPosition;

     if (Vector3.Distance(enemy.transform.position,enemy.lastKnownPosition) <= enemy.navMeshAgent.stoppingDistance)
        {
            ToAlertState();
        }
}

#

ah that didn't paste well, let me fix it

red helm
#

But I think I should just ignore it since it doesnt affect the gameplay

burnt vapor
#

You can press the warning to see what exactly is missing

languid spire
keen cargo
keen cargo
languid spire
keen cargo
#

yeah the lastKnownPosition is where the player was last seen

languid spire
#

you only need to set that once

keen cargo
#

the code WORKS with the stopping distance just fine, but the ai stops a bit too early for my liking

languid spire
#

well adjust your stopping distance. Stopping distance may not be what you think it means

keen cargo
#

adjusting the stopping distance will break the other part of my script, where the ai stops before hitting the player

languid spire
#

Stopping distance does not mean WILL stop, it means CAN stop,

keen cargo
#

alrighty let me see

#

ah i found the problem

#

it was taking the stoppingdistance from the chase state

#

all i needed to do was to change the stoppingdistance when it entered the tracking state

#

all good now thanks catpray

languid spire
#

lol, rubber ducking is a wonderful thing

keen cargo
sullen perch
#

This code is ment to spawn a lot of destinations for my ai to walk to, it is ment to attatch to the terrain but dosent, any ideas?

slender nymph
#

wdym by "meant to attach to the terrain"? because there's nothing in that code that indicates what you mean by that

#

also !code

eternal falconBOT
sullen perch
#

sorry

#

i got the code online and aparently its ment to spawn the destinations on the terrain

slender nymph
#

spawn the destinations on the terrain
are you for some reason assuming that this is supposed to make those instantiated objects children of the terrain object? because this code does not do that

sullen perch
#

no, just spawn them on the trrain

#

is there a easier way to place a lot of destinations?

slender nymph
# sullen perch no, just spawn them on the trrain

have you actually put your scene camera near the objects and focus on them by double clicking to see if they actually are on the terrain? because the code should be doing that, but you may be too far from the objects to actually see it correctly (for example, you are so far from the selected object that the terrain appears to not be rendering at that location, though your screenshot is not very informative here)

sullen perch
#

no, all the location that have spawned have spawned in the sky( if that is what you ment)

pearl flower
#

How can I hide public method from inspector, for example, make not possible to specify it in UnityEvent?
At the same time, I need keep method public, because I wanna access it from other class.

slender nymph
slender nymph
slender nymph
pearl flower
#

Well, for the safety, make not possible to call it from other part of project, only from code.

#

No side effects.

#

And good control.

sullen perch
slender nymph
#

does the terrain object have a parent?

sullen perch
#

yeah

slender nymph
#

yeah so that's why. i bet the parent isn't at 0,0,0 either

sullen perch
#

oh

#

so the terrain has to be at 0,0?

slender nymph
#

ideally the terrain object should be at 0,0,0 in world space yes

sullen perch
#

oh ok

#

thx

slender nymph
#

otherwise you need to convert the position from local space relative to the terrain to world space

sullen perch
#

it is still floating in the same location

#

nvm

slender nymph
#

is the terrain still at a location other than 0,0,0 in world space

sullen perch
#

i might have fixed it

low wasp
deft grail
rocky canyon
#

thas what u code does.

#

if timer runs out.

spawn this
spawn that
spawn that
spawn that
etc

#

probably need to utilize a for loop

deft grail
#

definitely need a loop

low wasp
#

I see. I was trying to get each set of cars to spawn at a different random times. I will see if I can craft this into a for loop. Do I need a different script for each car group or just on to rule them all?

deft grail
#

is your idea spawn 1 wait 2 seconds spawn 1 wait 3 seconds spawn 1 wait 1.5 seconds?

rocky canyon
#

a random time between each is what i understood

deft grail
#

so just add the cars to an array/list loop through it then make random time

low wasp
#

Yes a random time between each.

rocky canyon
#

coroutines! cs IEnumerator SpawnCarsWithDelay() { foreach (GameObject car in cars) { SpawnCar(car); // Spawn car float delay = Random.Range(minSpawnTime, maxSpawnTime); //wait random time yield return new WaitForSeconds(delay); } }

low wasp
#

Right now, they all spawn at the same random times.

#

Thanks for all the help. I will work on this with the suggestions.

void fable
#

Hello! I had a question regarding Unity/VScode. I installed VScode and chose it as my editing tool. Though when I try to open the project in VScode it shows me this

#

What have I missed? I tried following a tutorial

deft grail
slender nymph
#

well you've clearly not installed the unity extension

#

!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

void fable
void fable
languid spire
deft grail
#

if nothing then you shouldnt be opening vs code

void fable
void fable
slender nymph
#

that is not telling you to install the unity editor. it is about the unity extension for vs code

void fable
#

oh.. My bad

languid spire
void fable
#

Ill install it

slender nymph
languid spire
void fable
languid spire
void fable
low wasp
#

Thanks again for everyone's help. I was able to get it running as intended.

slender nymph
wet bobcat
#

ohh sorry didnt know that

slender nymph
#

it also helps to share code correctly. the bot linked how to share code correctly just a few messages before yours

wet bobcat
#

just though my questions got lost in the flow

#

so should I edit or post again?

verbal dome
#

You can post again or link to it

wet bobcat
#

thnx

#

Can I get some help with making the two cursors in this script GamepadVirtualCursors to be able to drag objects in a 3d world. Just like in this script DragObject (updated with cleaner code) but with the New Input system and not the mouse. Please?

...how do I make OnMouseDown(), GetMouseAsWorldPoint(), and OnMouseDrag() accept the virtual cursors instead of the system mouse?

...problem is that I made followed a tutorial to make the gamepad cursors and it is a bit too good for me to understand.

wet bobcat
slender nymph
#

did you follow the instructions from the bot? if yes, then yes.

wet bobcat
#

it does not show up in the message, just links

slender nymph
#

yes because that is how linking code works

wet bobcat
#

ok cool

#

sorry about the pinging, maybe thats why I get no help lately :/

slender nymph
#

it also doesn't help that you are barely providing any information, just dropping two scripts and saying "help me make it work"

wet bobcat
#

Alright, I was thinking that I was too wordy and using the wrong terms and thats why nobody wants to bother

void fable
#

does anyone know how to fully restart vscode? Everytime i delete it and redownload it, it opens where i left off. But i want to restart all over

slender nymph
#

but why

void fable
#

because I open and closed things on accidant

#

I dont know what I did

strong wren
wet bobcat
#

how do I reach private Mouse virtualMouse;from another script?

frosty hound
#

You can't, it's private.

cosmic dagger
frosty hound
#

Either make it a public field, create a public property, or a function that returns it.

wet bobcat
frosty hound
#

You can

cosmic dagger
wet bobcat
#

public Mouse virtualMouse; in script "GamepadCursor" - I try to reach it in another script with GamepadCursor.virtualMouse or ?GamepadCursor.Mouse.virtualMouse

cosmic dagger
wet bobcat
#

Ah, is there no way to avoid having to reference it on the game object? So I do not have to change anything in the editor?

cosmic dagger
#

in order to access any script on a GameObject, you have to reference it. that's kinda how everything works . . .

wet bobcat
#

So public Gamepad gamepad would do?

frosty hound
#

The onyl way to avoid having to reference the object is if you make the variable a static member

#

Which, if this is a single player game, then having global access to the input would be a good usecase, or making the GamepadCursor a static class.

rich adder
#

static is a noob trap

wet bobcat
#

it is a single player game but the player will control two cursors

#

with the gamepads two joystics

rich adder
#

are you not using the new input system ?

#

it handles it all for you

wet bobcat
#

I am but I do not get it

#

I want to drag rigid bodies with the two cursors

rich adder
#

its a little confusing at first that just because they have multiple ways to use it

lilac moth
#

Does anybody know if it is possible to have a gameobject with a script that can detect collisions of that gameobject's child gameobject's collider?

I have already coded the gameobject to create the childgameobject and reference the collider of the childgameobject, but I do not see a way to use Oncollisionenter method with the child gameobject's collider.

I dont want to create a script for the child if I dont have to

rich adder
lilac moth
cosmic dagger
lilac moth
#

yeah I know there is the ontriggerenter method, but Im just not finding a way to make reference the child's boxcollider trigger in the parent gameobject script

#

am I making any sense?

rich adder
lilac moth
#

gotcha, thanks for the info

zenith cypress
#

The rigidbody parent that gets the trigger event, will have the child trigger collider as a parameter. It collects events for itself and all children on itself. If you want to check if it got the child, you will have to reference the child and compare.

rich adder
#

Ahh ^ this . Did not know that

lilac moth
rich adder
#

I usually use overlaps now awkwardsweat

lilac moth
#

I have the reference to the child game object's collider. Just need to use it within a trigger method

zenith cypress
#

Rigidbodies are the collectors of physics events basically.

rigidbody (OnCollision, OnTrigger, etc happen here for anything under it)
- collider
  - collider
- trigger

So just like check if it is the child

void OnTriggerEnter(Collider col) {
  if (col == _childCollider) DoAThing();
}
rich adder
# lilac moth

why not just use a Prefab that has components you already need like collider and script that just Invokes an event you can sub to when spawned?

zenith cypress
#

That too

cosmic dagger
#

the trigger and collision messages have a parameter. the collider (of the collided GameObject is passed as the parameter for the method. you just need to do a comparison . . .

lilac moth
rich adder
lilac moth
#

im not sure if im trying to do something too advanced for my current knowledge

polar acorn
rich adder
polar acorn
#

that already has the collider on it?

cosmic dagger
lilac moth
#

I can make my game object a prefab and instantiate/copy the prefab. That is fine. I just dont know how to have a gameobject with multiple colliders and then reference any which collider all in one script

I have the parent gameobject that has a child gameobject. I want to reference the childgameobjects collider

Im trying to understand what you guys mean in that the parent gameobject should have access to child gameobject colliders

polar acorn
#

You shouldn't have multiple colliders on the same object unless you want them to act as one big aggregate collider that are all treated the same

rich adder
#

also you can have it just spawn as a component w prefab with the things you want already referenced

lilac moth
#

Gotcha, yeah im either trying to do something impossible and/or the wrong way. I appreciate yalls guidance. I will look more into this

rich adder
polar acorn
#

If the alternate colliders are on different objects, you can tell them apart by getting different properties of the object, like tags or scripts and whatnot

cosmic dagger
lilac moth
rich adder
#

btw if you ever look into events

SomeComponent spawnedComponent = Instantiate(prefabOfSomeComponent , etc.);
spawnedComponent.OnChildEvent += DoSomethingAfterChildDidSomething;```
or if you want specific colliders referenced in prefab for some reason.
```cs
spawnedComponent.ColliderReferencedA.isTrigger = true;
spawnedComponent.ColliderReferencedB.isTrigger = false;``` @lilac moth
wraith grotto
#

What is considered good practice when your character dies and the whole level needs to be reset to it's starting layout?

rich adder
#

79% of good practices are specific to the project at hand and the answer usually boils to itdepends (aside from general good practices like not writing horrific code etc.)

wraith grotto
#

Well i'm completely lost. I'm making a top down shooter similar to hotline miami. I guess i need to launch something once the player is considered dead, any recommendations on how to handle this?

hexed terrace
#

!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)

rich adder
#

since its specific to player and it can even be static

#

public static event Action OnPlayerDeath
PlayerHandler.OnPlayerDeath += DoSomethingAfterDeathOfPlayer

wraith grotto
#

understood, thank you for the recommendation. I'll look into all of the above mentioned options. When testing stuff reseting the scene definitely works so i might go with Steves approach

rich adder
#

yeah game like hotline miami resets whole scene? (maybe), doesnt hurt to learn about events though

#

you can use it for other cases

wraith grotto
#

thank you for the recommendations, i will do some research then

rich adder
#

Reset scene is good too, just need some DDOLs if you want to not reset specific things (like score trackers etc)

wraith grotto
#

i think a reset will do cause literally everything needs to reset.

#

it's a school project so im not going to make something overly complicated

sour widget
rich adder
uneven quarry
#

So I'm working on a platform fighter party game similar to that of knight club and duck game, and I was wondering how the best way to go about doing player collision with the ground and walls and such. is using raycasts for platforming collision a good idea?

rich adder
sour widget
rich adder
#

mind you this is for windows specific

uneven quarry
rich adder
uneven quarry
#

my game will have some amount of momentum mechanics which would require a tight understanding on everything that is causing the player to move, hence my inclination towards custom physics. on the point of something being wrong in the rigidbody component, as far as I am aware the clipping into a solid is a very normal thing that results from discrete movement steps and the fact that the "collision" will only trigger once the players collider is overlapping the ground which then retroactively snaps the player to the ground, hence the clipping

uneven quarry
rich adder
#

I never noticed my character dipping into the ground , I don't work too much in 2d though

uneven quarry
# rich adder Oh ok, You tried the continuous detection modes too ?

so I tried continuous before and it didnt help but now it does, so the issue of the ground seems to be solved, however there are still things like wanting the character to not slide down slopes and other things that come with the black box built in physics (also the physics being non-deterministic which would mean adding online would be nightmarish)

#

but thank you for helping with the continuous thing

hallow acorn
#

hey is there a way to rotate an object without it affecting the local rotation?

#

like just the mesh itself or sth

rich adder
deft grail
hallow acorn
uneven quarry
rich adder
#

hmm there has to be some open source project somewhere to look at maybe or use

toxic cloak
#

helo is it really neccecary to unsubscribe an event on a game object that m gonna destroy anyhow?

polar acorn
toxic cloak
polar acorn
#

It doesn't "just know" the thing that it's trying to call is gone

#

that's why you have to unsubscribe

toxic cloak
languid spire
# vale karma Haha no

up to you. what I was thinking is you are setting the movingPoint positions at the wrong time in your code, also your Draw method would be better as a coroutine, but I'll let you figure it out

polar acorn
# toxic cloak i see why now thank you

The way you could think of it is: Have you ever had someone get a new phone number and forget to tell you? If you try to call them, you would call the number you have, even though it's disconnected. Unless they tell you that number isn't active, you won't know not to call it

toxic cloak
topaz mortar
#

Anyone here smart enough to quickly fix this? It's supposed to not have the same colors touch.

{
    for (int y = 0; y < _height; y++)
    {
        for (int x = 0; x < _width; x++)
        {
            if ((x + y) % 2 == 0)
            {
                SpawnHex(_hex1, x, y);
            }
            else if ((x + y) % 3 == 0)
            {
                SpawnHex(_hex2, x, y);
            }
            else
            {
                SpawnHex(_hex3 , x, y);
            }
        }
    }
}```
deft grail
magic panther
#

Quick stylistic question: Should I keep the var here or replace it with something? Is it acceptable, is what I mean. (idleParticles is a ParticleSystem)

    protected override void Awake() {
        base.Awake();

        spriteRenderer = GetComponent<SpriteRenderer>();
        itemSprite = spriteRenderer.sprite;

        if (!instantLoad) {
            spriteRenderer.sprite = null;
            itemActive = false;
        }

        var mainModule = idleParticles.main;
        mainModule.startColor = effectsColor;
    }
deft grail
magic panther
#

Thanks

topaz mortar
#

Anyone here smart enough to quickly fix

hallow acorn
#

So my Mesh is childed to my drone with the controller and idk why but the mesh doesnt rotate on the Y axis this is the code thats supposed to rotate it: ``` void Rotate()
{
transform.Rotate(0, playerControls.flying.Yaw.ReadValue<float>(), 0);
Mesh.transform.Rotate(0, playerControls.flying.Yaw.ReadValue<float>(), 0);
Mesh.transform.rotation = Quaternion.Euler(new Vector3(playerControls.flying.Pitch.ReadValue<float>() * RotationSpeed, Mesh.transform.rotation.y, playerControls.flying.Roll.ReadValue<float>() * -RotationSpeed));

}```
toxic cloak
#

my head is rotating now

toxic yoke
#

What is the best way to trigger a function once after an animation has started playing? I think I just have a mental blockade right now cause it seems like such a simple problem but I can only come up with really complex solutions...

toxic yoke
#

wouldnt that need an entire script for the animator?

toxic cloak
hallow acorn
toxic yoke
#

Hm but that's not the case for me. I am working on a level director with basically a sequence of scripts that I put into the director game object one after the other. The different scripts of the director access all kinds of objects to spawn enemies and trigger animations. I basically want to be able to tell if the animation has ended and potentially wait for the end or just skip the wait and then go to the next script.

toxic cloak
sage peak
#

Hello! Can someone tell me why this isnt working?

hallow acorn
sage peak
#

Bro how do I write the codes in boxes

languid spire
#

!code

eternal falconBOT
rich adder
#

lol

sage peak
#

MATE

rich adder
#

did you actually read the bot msg

willow scroll
#

You got this

wet bobcat
#

I finally got my gamepad virtual cursor to drag objects. However it drags all objects that have the script as soon as I click.

OnMouseDown() anf OnMouseDrag() works on the clicked collider only so I need to simulate this. Hint plz? Do I need to use raycasts?

Gamepad Virtual Cursor

VirtualDragObjects

sage peak
#

😂

#

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

public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
void Start()
{
offset = transform.position - target.position;
}

// Update is called once per frame
void Update()
{
    Vector3 newPosition = new Vector3(transform.position.x,transform.position.y,offset.z + target.position.z);
    transform.position = newPosition;
}

}`

#

LETS GO

hallow acorn
#

you gotta use 3 of the back ticks its shift + the key next to "?" before and after your code

sage peak
#

This "'"?

rich adder
#

no thats single quote

sage peak
#

Oh god you cant see it

languid spire
rich adder
#

just copy the ones from the bot

#

literally copy and paste

hallow acorn
short hazel
#

You can copy the formatter from the one shown in the bot message

slender nymph
# hallow acorn this one

and that location is specific to whatever layout you are using. for US QWERTY layout the ` key is to the left of the 1 key

short hazel
#

On English keyboards it'll be above Tab, if I remember correctly. So it's not always in the same place

rich adder
sage peak
#

OHHHHHHHHHH

languid spire
sage peak
#

FINALLY

#

I GOT IT

toxic cloak
#

damn

slender nymph
#

it's still three of them

sage peak
#

Oh

short hazel
#

Nope still not, you need 3 backticks

sage peak
#
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    public Transform target;
    private Vector3 offset;
    void Start()
    {
        offset = transform.position - target.position;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 newPosition = new Vector3(transform.position.x,transform.position.y,offset.z + target.position.z);
        transform.position = newPosition;
    }
}```
hallow acorn
sage peak
#

Thereee

languid spire
slender nymph
short hazel
sage peak
#

bro wait a damn minute

hallow acorn
#

ok my bad i take back everything i said about the " ` " topic

sage peak
#

While I was finding a way to paste the damn code I think I fixed the problem

#

hold on

#

yeah.. im sorry guys 😭

willow scroll
#

I think you're not concentrated well enough on pasting the code

hallow acorn
rich adder
sage peak
hallow acorn
rich adder
hallow acorn
#

no way theres a wikipedia article about this

rich adder
#

almost every coding server

slender nymph
hallow acorn
silver basin
#

How do I get the x and z rotation of what was hit by my raycast?

rich adder
slender nymph
silver basin
slender nymph
#

do you perhaps want the normal?

silver basin
#

Yeah

slender nymph
#

the raycasthit provides the normal

silver basin
slender nymph
#

what are you actually trying to do with this

hallow acorn
#

can someone tell me what can cause my childed object rotate exactly like the parent rotation*-1 on the y axis and ignores every rotation on the y axis i give it in the code?

silver basin
slender nymph
#

just assign its transform.up to the normal

toxic cloak
hallow acorn
tiny bloom
#

UIManager & Player both inherit from MonoBehavior
the UIManager has a reference to the player
and the player communicates to UIManager through events
so this way Player has no dependencies
and u can simply drag the Player prefab to other scenes\projects and it should work fine.

I understand this and it's cool
but what about the UIManager? it has a reference to the player, and it won't work if you move it to another project for example. 🙃

also regarding the Player, what if it has references to other classes that encapsulate logic
meaning non MonoBehavior classes that hold some data\logic unrelated to unity
this way if i move the player into another project
ill need all of those classes too
so am i missing the concept of clean architecture in unity?
since tutorials i watch all raise this issue of decoupling components from each other so u can simply drag components into other projects and them working fine

#

also i come from a full stack web development background
and there's nothing like this
in order for a components\services to work you need the injected services that you use in those components\services for it to function

eternal needle
# tiny bloom UIManager & Player both inherit from MonoBehavior the UIManager has a reference...

Honestly any attempt at decoupling stuff like this is just gonna be secretly coupled in a more complicated way. If you use some other way of hooking up these references like DI or just another script, that's still gonna be quite specific to your project. I dont think it's worth it to worry about making a UIManager that can be drag/dropped to any project. Even premade UI assets require you to set up stuff with your own scripts

#

Especially with the player, and how different itll be between games, I dont really think this will end well

gaunt solstice
#

I have a question. So I'm using this code to make my simple enemy ai walk around at random points within a circle;

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

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

        result = Vector3.zero;
        return false;
    }

    void Patrol()
    {
        if (agent.remainingDistance <= agent.stoppingDistance)
        {
            Vector3 point;

            if (RandomPoint(transform.position, moveRange, out point))
            {
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(point), turnSpeed * Time.deltaTime);

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

But I don't want it to move at random points within a circle, cause oftentimes it'll just keep going back and forth. Does anyone have any tips for how I could make the movement feel much more natural, like having the random point be within it's cone of vison rather than a circle around it?
tiny bloom
slender nymph
eternal needle
# tiny bloom Well then what's the way to go? i do follow coding principles in my code but w...

In this case I dont think theres a clean way that isnt extremely overcomplicated or detrimental to the progress of your current project. Stuff like player movement would make sense to completely decouple, and these components/projects already exist like the character controller, rigidbody, or KCC asset. Your player and UI will be too specific to your game, that it's already coupled to your game

low wasp
#

Hey yo! When my player gets hit by an object. I have it respawn at the start. The issue is that I cannot control the new spawn. I have commented out the things I have been trying to get this working. I am sure it has to do with enabling controls on the new spawn. I just cannot seem to find the magic words that would make it work. Any help would be greatly appreciated.

https://hastebin.com/share/lalevedunu.csharp

gaunt solstice
# slender nymph if you want to get a point within it's cone of vision, you'll need to decide on ...

I have this script to create a cone of vision where the enemy can see the player;

    {
        Collider[] rangeChecks = Physics.OverlapSphere(transform.position, viewRadius, targetMask);

        if (rangeChecks.Length != 0)
        {
            target = rangeChecks[0].transform;

            Vector3 targetDirection = (target.position - transform.position).normalized;

            if (Vector3.Angle(transform.forward, targetDirection) < viewAngle / 2)
            {
                float targetDistance = Vector3.Distance(transform.position, target.position);

                if ((Physics.Raycast(transform.position, targetDirection, targetDistance, wallMask)) == false)
                {
                    canSee = true;
                    StartRotate();
                }
                else
                {                
                    canSee = false;
                }
            }
            else
            {
                canSee = false;
            }
        }
        else if (canSee == true)
        {          
            canSee = false;
        }
    }```
So how would I add a random point within this fov
slender nymph
#

ah so you're just going to ignore the advice that was provided and do your own thing then. that's fine too i guess

gaunt solstice
slender nymph
#

have you looked at what Vector3.Dot does?

gaunt solstice
#

yes I have used it before

slender nymph
#

so then surely you know that none of that code you just posted is necessary for just getting a point within a cone in front of the object. and you just need to use Vector3.Dot to determine if the random point you selected is within that cone

toxic cloak
low wasp
toxic cloak
#

yes depending on your player design

low wasp
gaunt solstice
slender nymph
slender nymph