#💻┃code-beginner

1 messages · Page 266 of 1

summer stump
#

To hit the ground, but in front of you

rocky gale
#

its rigidbody right

carmine turret
#

Ahh okay, so slightly angled away from the ground. Check?

carmine turret
#
    void Movement(){
        if(currentState == movementState.Grounded && !_jump){//platform moving
            if (Input.GetAxisRaw("Horizontal") == 0){
            }
            rb.velocityX = Input.GetAxisRaw("Horizontal") * speed;
        }
#

That's pretty much all of the movement code at the moment

#

and theres a groundcheck in a seperate variable

rocky gale
#

this 3d?

carmine turret
#

2d

rocky gale
#

oh ok

carmine turret
#

Sorry, should have made that clear aha

rocky gale
#

lol all good

#

gimme a sec

carmine turret
#

Is there an easy way to calculate a direction?

#

for the raycast that is

rocky gale
#

i think there is a function for slopes

carmine turret
#

Obviously I can do Vector2.up or right for x and y, but calculating one in between?

carmine turret
rocky gale
#

let me see

carmine turret
#

Alrighty

rocky gale
#

mayb this tutoiral sry i cant help much i dont rly do much 2d 😅 https://www.youtube.com/watch?v=1E8AI5UgmAw

In this tutorial I will show you how to make sure that your dynamic rigidbody driven character can handle slopes in Unity 2D.

Do you want to improve the way you write code for your games on the example of a 2d platformer? Check my video course:
https://courses.sunnyvalleystudio.com/

Is your character using kinematic rigidbody for movement? May...

▶ Play video
carmine turret
#

no worries, will take a look

#

Hmm this seems like a really ehhh, hack way to do it because it switches between kinematic and dynamic haha

#

I think I do need to do the slope check that aeth suggested and somehow make it adjust the velocity

rocky gale
#

oh

#

ye idk 🤣 im bad with 2d

carmine turret
#

npnp!

#

I appreciate your attempt anyways

#

As it stands, once ive fixed this Im pretty much done with programming my character controller

rocky gale
#

oh nice

carmine turret
#

then its just menus maps and fluff

rocky gale
#

im sure a lot of ppl have the same issue

carmine turret
#

Im aiming for 9 maps that if played perfectly will be completable in 5 mins each, but difficutly will make the average around 20 mins per map I think

#

its the type of game where if you fall, you potentially lose a lot of progress ^^

rocky gale
#

sounds like a cool game

carmine turret
#

Good for streamers and viralization ;3

rocky gale
#

yea

carmine turret
#

the gimmick is that you use a grappling hook to swing, an airdash to move in air and a hookshot to latch onto walls to combo movement

rocky gale
#

can get streamrs speedrunning

exotic hazel
#

im trying to make a terrain bigger using scale tool but it isnt just working

carmine turret
#

if everything was flat, then it reuns VERY smoothly and feels good

carmine turret
#

this is for programming 🙂

carmine turret
#

I beleive you dontw ant to use scale for terrain as it messes up the terrain, and instead want to add more terrain segments? been awhile since i did 3d stuff

exotic hazel
exotic hazel
rocky gale
#

search up on google

timber tide
#

size options should be right onthe terrain itself

#

Public or Property usually

#

I do dislike making private properties pascal case

#

you cant force me visual studios

neat beacon
timber tide
#

Destroy(collider.gameObject);

neat beacon
timber tide
#

You want to destroy the component (the particle system), but instead you're destroying the whole gameobject that contains the particle effect

#

or, you dont want to destroy the effect (half asleep here)

#

that means you need to deattach the system then if it's on the gameobject (that you want to destroy)

cunning rapids
#

Guys, when I disable/enable a game object while it is playing an animation, it gets stuck on that state of the animation

#

This is all the relevant info

timber tide
#

you can open the blend tree and look at it during runtime

cunning rapids
#

I'm not using a blend tree

#

The animations seem to be playing fine, too, it's just it practically resets the default state of the revolver and rotation

timber tide
#

usually disabling just removes update (and any rendering) from happening, but you can probably still check the duration if you want to make sure

cunning rapids
cunning rapids
timber tide
#

probably ways about it, but a crude idea is to just stop the current animation, make sure all states are reset

cunning rapids
#

How would I achieve that?

timber tide
#

make sure all states are false (or w/e you need to have toggled to be certain that you return to idle)

cunning rapids
timber tide
#

also you've warnings there about animation so that's probably relevant to your problem

burnt crow
#

hello, I have a cube and text like this and somehow the text never renders when I spawn in the cubeparent, anyone have any advice why?

timber tide
cunning rapids
# timber tide nothing you've not done before

I've tried making it play the idle anim in the OnDisable() method. but it didn't work and gave me the "game object with animator is inactive" or something along the lines of that

#

A cheap fix seems to just reset the default transform of the gun ondisable, no?

cunning rapids
burnt crow
#

ah my bad, what other info can I include?

cunning rapids
#

This is code beginner, maybe some code?

carmine turret
#

Lets be a little nicer about that 😉

#

But yes, posting your code in a code block would be useful

burnt crow
#

this is what i got @cunning rapids @carmine turret

GameObject canvas = gameObject.transform.GetChild(1).gameObject;
canvas.SetActive(true);
GameObject canvasChild = canvas.transform.GetChild(0).gameObject;
 canvasChild.SetActive(true);
_biasText = canvasChild.GetComponent<TMP_Text>();
_biasText.text = "cooltext";
cunning rapids
#

But I apologize if I did

burnt crow
#

nah youre good

cunning rapids
#

Thanks man, just give me a second

carmine turret
cunning rapids
#

The inspector

#

Also, this block of code belongs to the "cubeparent" gameobject, just in case it isn't attached there

#

The code looks correct at first glance, even if it looks a bit messy

burnt crow
#

I'm gonna try to serializefield the text

#

now I'm doing something like this with the TMP_Pro _biasText SerializedField and it still isnt working

_biasText.gameObject.SetActive(true);
_biasText.transform.parent.gameObject.SetActive(true);
_biasText.text = "cooltext";
astral saddle
#

Is the text supposed to be screen space or world space?

burnt crow
#

I'm not quite sure what that terminology means, gonna consult chatgpt and get back to you rq

burnt crow
astral saddle
#

is the canvas set to be world space then?

burnt crow
#

where would i set that

astral saddle
#

so screen space = 2d UI
world space = 3d UI (so it gets treated like any other 3d object)

burnt crow
#

right yeah it's world space bc its above the 3d cube

#

how can i double-check its world space

astral saddle
#

in your canvas component

burnt crow
#

I can't find where to do that

#

in the inspector

astral saddle
#

can you take a screeenshot of the inspector that you have on the "Canvas" gameobject, the parent of your text gameobject?

burnt crow
#

wait i see i found it that makes a lot of things make sense now actually let me try that

#

it works now! thanks so much :)

astral saddle
#

No worries! Code looked fine so I figured it must've been something in the scene setup

burnt crow
#

a couple things just clicked for me about canvases and textmeshpro bc of what you were saying here, very helpful

carmine turret
#

Whats the easiest way to calculate the position of where I want something to be, for example if I want a raycast to start infront of my players location

#

Like this for example

cunning rapids
#

Get the current player position, get it's current orientation, calculate desired position

#
public float distance = 1.0f;
```example distance of the raycast

```cs
Vector2 playerPosition = transform.position;
Vector2 facingDirection = transform.right;
```Get the player position and rotation

```cs
Vector2 position = playerPosition + facingDirection * distance;
RaycastHit2D hit = Physics2D.Raycast(position, facingDirection);```Start the raycast at the new position
opal zealot
#

I'm able to incorporate the jump code into my movecment control through the Unity Input system, but I am unable to make him jump.

cunning rapids
#

!code

eternal falconBOT
cunning rapids
#

In the minute mark ~4:30 in the video he adds a debug log when you press the jump key.

#

Does it do the same to yours?

#

Also, specify what you mean by "it doesn't work"

#

Have you tried doing some tests on why it doesn't work? if so, what were the results?

opal zealot
cunning rapids
#

Is the ground detection working?

#

Most jump systems have a system to check if you're grounded

opal zealot
#

I'll check on that too.

cunning rapids
#

In this case (I must admit it's a bit weird), it checks the current player y velocity. If it's equal to 0, then you can jump

#

I prefer using raycasts but it doesn't matter

#

Log that part

#

Like the dude did in the video

opal zealot
#

I added those for sure.

cunning rapids
#

Post your code on any of those websites

opal zealot
#

An earlier friend said I should just use one characterController so I didnt add in _characterController.

opal zealot
opal zealot
# cunning rapids What? What do you mean?

When I first added the jump code to my main movement code, I had both characterController and _characterController. They told me both are the same so I just added the former for streamlining purposes.

cunning rapids
#

Ah alright

opal zealot
#

Should I remove the _ on the rest as well, or would it break the script entirely?

cunning rapids
#

Log "isGrounded"

#

Check if it returns True or False

opal zealot
#

Never done that before.

cunning rapids
#

In update, type cs Debug.Log(_groundedPlayer);

opal zealot
cunning rapids
#

There you have it

opal zealot
cunning rapids
#

You can't jump if you're not grounded

#

Also thiss code feels a but messy

opal zealot
#
    {
        isGrounded = Physics.CheckSphere(transform.TransformPoint(groundCheckOffset), groundCheckRadius, groundLayer);
    }```

My Groundcheck code.
cunning rapids
#

I haven't worked with CC ever before, but I feel like there are too many ground checks

opal zealot
#

So I'm trying to see how to make it work.

#

Not to mention the movement code being from a different tutorial: https://www.youtube.com/watch?v=DXw9QhsjlME

Checkout the full Third Person Parkour System Course here - https://fantaco.de/unity-parkour-system

Hey everyone, in this video we'll create a Third Person Controller in Unity. We won't be using any assets to build it, we'll build it completely from scratch because it's a good way to learn the fundamentals of 3D game programming,
and it will ...

▶ Play video
cunning rapids
#

You only need one groundcheck

#

For jumping

opal zealot
#

Ah

#

Not sure which Groundcheck do I keep

cunning rapids
#
private bool isGrounded;
```Grounded bool
```cs
void Update()
{
  isGrounded = Physics.CheckSphere(groundCheckTransform.position, groundCheckRadius, groundLayer);

  if (isGrounded && velocity.y < 0)
  {
      velocity.y = -2f;
  }

  if (isGrounded && Input.GetKeyDown(KeyCode.Space))
  {
      Jump();
  }

  velocity.y += gravity * Time.deltaTime;
  characterController.Move(velocity * Time.deltaTime);
}
```Movement logic, first line to check if you're grounded, the rest is basic CC stuff (such as gravity and input)
```cs
void Jump()
{
    velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}```Jump method

I'd do something like this. Simple and concise
#

But don't take jy word completely as I've never used CC before except a few times

opal zealot
#

No worries, thanks for the help.

burnt crow
#

Hey folks, I'm having trouble with an update function on a script I attach to an object that spawns in partly-in. I have a Debug.Log at the beginning of the Update() function, and the Update() function is never called according to that even though other functions in that script work

#

any idea what I'm missing here?

#

any help is appreciated :)

opal zealot
# cunning rapids But don't take jy word completely as I've never used CC before except a few time...
        _groundedPlayer = characterController.isGrounded;

        //If on the ground stop vertical movement
        if(_groundedPlayer) {
            _playerVelocity.y = 0.0f;
        }

        //If Jump pressed and on ground jump the player
        if(_jumpPressed && _groundedPlayer) 
        {
            _playerVelocity.y += Mathf.Sqrt(_jumpHeight * -1.0f * _gravityValue);
            _jumpPressed = false;
        }

        _playerVelocity.y += _gravityValue * Time.deltaTime;
        characterController.Move(_playerVelocity * Time.deltaTime);

    }``` Presume I don't need this one then?
keen dew
burnt crow
#

the component works for other stuff so I would assume the component isn't disabled

keen dew
#

well check it then

burnt crow
#

what's the difference between disabled and inactive

#

from my research I believe it's not disabled

keen dew
#

Show a screenshot of the editor window with the console and the inspector visible while the game is running

burnt crow
#

I'm making a very basic VR app on Meta Quest 3 on Mac so I can't run the game through quest link

opal zealot
#

I'll need to come back after gym to try and fix.

keen dew
burnt crow
#

no I'm using unity but I can't control the game with the run button

keen dew
#

Then where does it print the logs?

burnt crow
#

Android LogCat, I'm sure it works I've been using it for hours

cunning rapids
spiral narwhal
#

Why is SetInt, SetBool etc of animators not available from the editor like it is in scripting?

keen dew
#

Because they require 2 parameters and the inspector can only pass one

spiral narwhal
#

The editor can only pass one? Lol how did I never notice

#

An unfortunate restriction, thanks for the heads up : )

verbal dome
#

You can get around it by making your own function in a script and call that

fringe pike
#

how to make the animation only play when highlighted?

#

and how to do it reverse when not highligheted anymore

spiral narwhal
spiral narwhal
fringe pike
#

what abt this

spiral narwhal
#

What does this mean in reverse

#

The animation in reverse?

fringe pike
#

yeah so it get smaller when not highlighted

#

btw

#

shit still aint working

spiral narwhal
#

Create a new animation with the old one in reverse#

neon ivy
#

hi, I'm making a jump but I need to transform the directional vector of this jump from the character's local space to global space.
for instance if my character's jump is straight up (0,1,0) but my character is walking on a wall that makes the character's transform.up to be to the right I need to transform the jump vector to (1,0,0). how do I do this? I'm not very familiar with vector transformations so please dumb it down a bit xD

modest dust
#

Isn't transform.up already in world/global space?

static bay
modest dust
buoyant horizon
#

Hello! I've mentioned this error a few days ago and someone recommended that I look into a specific forum in hopes of resolving my problem ( I have tried ). I've looked everywhere I could possibly think of in the game files searching for the solution ( all the scripts, assets / inspector tabs ) but no luck. The problem I encounter is a *** " NullReferenceException : Object reference not set to an instance of an object " ***. I've been told that perhaps I've failed to reference an object but I cannot find my mistake. This console error occurs when I interact with an object I've set as an "Interactable item" which after interacting with should go into a inventory ( I can show the code if necessary )

modest dust
#

I might have not expressed myself clearly, but I think that's what Alice was talking about

timber tide
#

translating with vector.up would be the idea though in world coordinates

timber tide
modest dust
#

But If Alice wanted the global representation of the local up, then tranform.up should be used

buoyant horizon
buoyant horizon
timber tide
#

!code

eternal falconBOT
buoyant horizon
#

I copy - paste the code in here between the *** " ***, right?

timber tide
#

just throw it into a paste site

buoyant horizon
#

Aaa ok

buoyant horizon
slender nymph
#

Inventory.instance is null

buoyant horizon
slender nymph
#

it currently is and should not be. you cannot call a method on a null object

buoyant horizon
#

So I need to find my method containing the "Inventory.instance" and assign it a value?

slender nymph
#

you need to assign to the static instance field on your Inventory class

exotic hazel
#

How do i spawn random animals on a Terrain?I do know how to do it on a flat land its p easy but terrain is very uneven in shape so

buoyant horizon
#

One second, let me find the code for the inventory.

neon ivy
exotic hazel
buoyant horizon
slender nymph
#

configure your !IDE and spell your methods correctly

eternal falconBOT
eternal falconBOT
burnt vapor
#

Dang, too slow

buoyant horizon
exotic hazel
charred spoke
exotic hazel
charred spoke
#

I am very confused right now

exotic hazel
#

there was another thing i wanted to do and i was told to do it throught sampleheight as well

charred spoke
#

Ok…and ?

exotic hazel
#

and sampleheight gives us the highest point on the terrain of a given coordinate?

charred spoke
#

There is no lower or higher point at a given coord there is just a height

modest dust
neon ivy
#

yes, because my player rotates a lot since I change the direction of gravity a lot, mario galaxy style walking on spheres n stuff

#

if it helps, this is how I transform my movement direction

Vector3 crossProd = Vector3.Cross(Physics.gravity.normalized, GetGravityDirection().normalized);
float angle = Vector3.Angle(Physics.gravity.normalized,  GetGravityDirection().normalized);
Quaternion rot = Quaternion.AngleAxis(angle, crossProd);

Vector3 transMove = rot * absMove;

InputVector =  transMove.normalized * magnitude;
#

I do not know what a cross product is though UnityChanOops

#

but it works

modest dust
#

Just use:

  • transform.up in place of (0,1,0) (up)
  • transform.forward in place of (0,0,1) (W forward)
  • transform.right in place of (1,0,0) (D right)
  • -transform.right in place of (-1,0,0) (A left)
#

Add them up and normalize

#

Unless you're not rotating the object at all, just applying different forces / transformations

#

Then rotate the vectors I guess

neon ivy
#

I am rotating the object, I guess that is just the easiest way of doing it

modest dust
#

Yup

neon ivy
#

UnityChanOops was making it way more complicated than it had to be, typical

modest dust
#

The best solution is the simplest solution

neon ivy
#

thanks UnityChanThumbsUp

cunning rapids
#

Guys, my animation issue still persists, even when tweaking the OnEnable() method

#

Even when I MANUALLY type in the rotation through the inspector during runtime, it just reverts it back to whatever number it stopped at

#

Only the rotation is messed up, too

#

Position and scale works fine

buoyant horizon
#

Ok! I have setup my IDE ( succesfully I hope so )

#

Now what do I do? Do I just open up the code I have trouble with?

burnt vapor
#

Then if you correctly specify the Awake method (including correct casing), the editor should now point out it's a Unity method if everything is correct

buoyant horizon
#

Okk, let me see

noble forum
#

hi

buoyant horizon
#

Oh my god...

#

I feel so stupid right now. Apparently my dumb ass wrote "awake" instead of "Awake"

noble forum
burnt vapor
#

This is why a correctly configured editor helps

buoyant horizon
#

Thank you for the help Fused & boxfriend & Mao ❤️

buoyant horizon
noble forum
#

any idea about it?

buoyant horizon
#

I saw the spelling because I saw you writing "Awake Method" and I thought "Why do I have awake instead of Awake"

#

Thank you anyways 😅

burnt vapor
#

VSCode is ass with C# in general and if you can use Visual Studio or are willing to pay for Jetbrains you should switch.

buoyant horizon
#

I'll give VS a try. Thanks for the tip

noble forum
queen adder
#

okay I have silly question, let's imagine two coroutine and you are starting the first one in Start method. And second coroutine is connected to this first one BUT! let's imagine first coroutine is in infinite loop. Would I get crash thanks to this logic?

fossil tree
#

hi i have a problem i try to instanciate my gameObject at a distance of my mousse but when i zoom that instanciate it under the map how can i calculate the distance i have zoom or something like that

the scrolling script

float scroll = Input.GetAxis("Mouse ScrollWheel");
            
            Vector3 pos = transform.position;
    
            pos.y -= scroll * 1000 * scrollSpeed * Time.deltaTime;
            pos.y = Mathf.Clamp(pos.y, zoom, dezoom);
            
            transform.position = pos;

the script for instanciate my object

Vector3  mouseInScreen = Input.mousePosition;
        mouseInScreen.z = 695 ;
        Vector3  mouseInWorld = Camera.main.ScreenToWorldPoint(mouseInScreen);
        transform.position = mouseInWorld;
        if (Input.GetButtonDown("Fire1"))
        {
            Destroy(gameObject);
            
            putTurret1 = true;
        }
        if (putTurret1 && canBePlaced)
        {
            Instantiate(tourelle1placable,mouseInWorld,Quaternion.identity);
        }
rich bluff
fossil tree
#

how can i use raycast for instanciate a object i never use raycast

rich bluff
#

is the map flat?

fossil tree
#

its a flat map with basement

#

so not really

#

its for make a td

rich bluff
#

it has some collision surface right? floor?

fossil tree
#

yes

whole idol
#

I tried creating a 3D (URP) and got this? wth is this?

rich bluff
#

use Camera.main.ScreenPointToRay(mousePos) to get the ray
use Physics.Raycast() to cast that ray into the scene
RaycastHit will contain the world point to place your object at

#

or use Plane, its simpler to use but it wont take into account collision meshes

fossil tree
#

ok i see i gonna try that ty guy

narrow girder
#

im not sure if this is a animation thing or code but is it possible to create a code that would throw the hammer in a parabolic trajectory? or do i need to animate it to have a trajectory?

cosmic dagger
narrow girder
sour yew
#

hey guys. can smb help me out? i have this piece of code:

public class PlayerInteract : MonoBehaviour
{
    // Start is called before the first frame update
    void Start(){ 
        
    }
    
    // Update is called once per frame
    void Update()
    {
        float interactRange = 2f;
        Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
        if (Input.GetKeyDown(KeyCode.E)) 
        {
            List<GameObject> gameObjects = new List<GameObject>();
            foreach (Collider collider in colliderArray)
             {
                var npc = collider.GetComponent<NPCInteractable>();
                if (npc!=null)
                {
                    float distance = Vector3.Distance(npc.transform.position, transform.position);
                    Debug.Log("NPC position: " + npc.transform.position);
                    Debug.Log("player position: " + transform.position);

                    if (distance > interactRange)
                    {
                        npc.EndConversation();
                    }
                    else
                    { 
                    npc.Interact();
                    }
                }
            }
        }
    }
}

and when i press E, i get 4 NPC instances logged. How can it happen? Can smb help me out? Thx

cosmic dagger
exotic hazel
burnt vapor
hidden sleet
#

Does an enumator coroutine have to be called in an update function?

burnt vapor
#

A coroutine has to be called once with StartCoroutine()

cosmic dagger
hidden sleet
# burnt vapor You could, but that's not the point

It's just that this only seems to change the alpha of the image when I first click, and doesn't do the smooth change that I'd like

private void Start()
    {
        playerControls = new PlayerControls();
        playerControls.BasicMovement.Aim.started += SwitchToAimCam;
        playerControls.BasicMovement.Aim.canceled += SwitchToBodyCam;
        playerControls.Enable();
    }

    private void SwitchToBodyCam(InputAction.CallbackContext obj)
    {
        mainCamera.SetActive(true);
        aimCamera.SetActive(false);
        currentReticleFade = 0f;
        StartCoroutine(FadeCrosshairOut());

    }

    private void SwitchToAimCam(InputAction.CallbackContext obj)
    {
        mainCamera.SetActive(false);
        aimCamera.SetActive(true);
        /* Fade time to control duration of fade
         */
        currentReticleFade = 0f;
        StartCoroutine(FadeCrosshairIn());

        
    }

    private IEnumerator FadeCrosshairIn()
    {

        if (currentReticleFade <= reticleFadeTime)
        {
            currentReticleFade += Time.deltaTime;
            reticleAlpha = currentReticleFade / reticleFadeTime;
            Color newColor = new Color(aimReticle.color.r, aimReticle.color.g, aimReticle.color.b, reticleAlpha);
            aimReticle.color = newColor;
            yield return null;
        }
    }

    private IEnumerator FadeCrosshairOut()
    {
        if (currentReticleFade <= reticleFadeTime)
        {
            currentReticleFade += Time.deltaTime;
            reticleAlpha = 1 - (currentReticleFade / reticleFadeTime);
            Color newColor = new Color(aimReticle.color.r, aimReticle.color.g, aimReticle.color.b, reticleAlpha);
            aimReticle.color = newColor;
            yield return null;
        }
    }
exotic hazel
burnt vapor
sour yew
burnt vapor
hidden sleet
#

The section down here Color newColor = new Color(aimReticle.color.r, aimReticle.color.g, aimReticle.color.b, reticleAlpha); aimReticle.color = newColor;
It does correctly change the image, but it's just on or off, with no smooth transition

burnt vapor
#

Your Coroutines all have a single yield return null; in an if-statement. This means the method starts, checks the if-statement, changes the alpha, waits 1 frame, and then ends

#

Perhaps you want this if-statement to be a while loop?

#

Right now yield return null; does nothing but wait a frame and then nothing at all

hidden sleet
#

Was a bit confused by what that return actually does, I was under the impression that would start the routine again

burnt vapor
#

So my guess is you need to change the if-statement to a while loop

hidden sleet
#

guess I was wrong

burnt vapor
#

No, a yield statement defined the delay basically

cosmic dagger
burnt vapor
#

Unity will wait this period before resuming the method

cosmic dagger
hidden sleet
#

Ah, so it doesn't start it again, just continues it

burnt vapor
#

You still need to define the flow of resetting yourself

hidden sleet
#

let's see if this works

cosmic dagger
hidden sleet
#

ay! It works!
Alrighty then, that makes sense. Can use that in other places now then

#

thanks for the help

#

So if yield return acts as a delay, can I use that to control how many seconds elapses between each run of the routine?

burnt vapor
#

See Coroutine time delay

#

Okay nevermind, looks like it barely explains the different yield statements. There are a lot of different yield instructions you cna use, like waiting for seconds, until the end of a frame, but also with predicates to wait until something becomes true

sour yew
exotic hazel
#

I wanted to find the no. of rabbits in the world through this line.I saw it in some learn.unity tutorial and remember it was written somethign like this but cant remember How."RabbitSpawner" is the name of the script

burnt vapor
languid spire
exotic hazel
burnt vapor
#

Why would it make no sense? That line is perfectly valid apart from the fact a Find type method is used

#

You just used the singular variant rather than the plural

exotic hazel
#

oh it was jsut Length and not length

languid spire
#

even so. it a singular find so how can it have a length of anything other than 0 or 1

exotic hazel
burnt vapor
#

Not why Length can't be used for a single result

exotic hazel
burnt vapor
#

Have a general manager keep track of what spawner is allowed to spawn a rabbit and have it keep count of the total spawned

exotic hazel
#

then use if statement to stop spawning if it reaches 100?

burnt vapor
#

For example

#

If you want to keep a shared context between multiple spawners you would at least need a general manager that can keep track of this.

burnt vapor
#

Then either have it spawn the actual rabbits on defined spots rather than having individual spawners, or have the spawners communicate with the manager by having a singleton pattern in some way.
I'd pick the former

languid spire
# exotic hazel how do i do so that only a specific numberof rabbits spawn like a 100 and once 1...

here is an example

    IEnumerator Spawn()
    {
        while (loop) {
            yield return new WaitUntil(() => Count < maxEnemies);
            yield return new WaitForSeconds(Random.Range(3, 10));

            float angle = Random.Range(0f, 359.99f);
            point.x = Mathf.Cos(angle) * (radius+15f);
            point.z = Mathf.Sin(angle) * (radius+15f);

            GameObject go = Instantiate(prefab, point, Quaternion.identity);
            Count++;
            enemies.Add(go);
        }
    }

Count is decremented when an enemy dies

gritty wagon
#

Is it possible with a Collider2d, to have it detect collisions between like the ground, but not collide with the player, but still send triggers/collision when the play and it "collides", without them actually colliding and not being able to move into each other

hidden sleet
#

Just going over in my head how i'd implement a damage system. Is there much of a difference between having a health component that controls the current health value, which the player class can then reference, to having an interface with methods to adjust player and enemy health in their respective scripts?

exotic hazel
#

bruh my jump function suddenly stopped working

#

Theres no problem then why is the character not jumping upon pressing Jump

spiral narwhal
#

Is OnEnable called when the parent is enabled after having been disabled?

exotic hazel
cosmic dagger
spiral narwhal
cunning rapids
#

Hello guys. I got a question regarding weapon switching. I have a script that switches weapons for me when I press the alpha 1 and 2 keys (etc.). I made sure that when the weapon is disabled, it resets the animation controller and disables the "isReloading" state of the scriptable game object it is referencing. However, while the "stop reloading" aspect works fine, the animation still gets stuck in that weird state in the reload animation. it seems to be LITERALLY changing the default transform of the revolver

spiral narwhal
#

This function is called when the object becomes enabled and active.
Technically it was never disabled, only its parent was

#

But then again it is now

cosmic dagger
cunning rapids
#

Funnily enough, it seems like I'm facing a quite similar issue

exotic hazel
cunning rapids
#

That's usually the most common cause

exotic hazel
cunning rapids
#
Debug.Log();
exotic hazel
#

oh

cunning rapids
#

Well...?

#
Debug.Log(GroundCheck);
``` and see what it returns
exotic hazel
exotic hazel
cunning rapids
cunning rapids
#

Not a string, debug the boolean GroundCheck

exotic hazel
#

i did that

cunning rapids
#

If it returns False, you have your answer

exotic hazel
#

it was working too suddenly jump stops working

cunning rapids
#

My guy. Your boolean for ground check is called "isGrounded"

exotic hazel
#

oh wait

exotic hazel
#

its false

cunning rapids
#

There you have it

#

Your code doesn't allow you to jump if it's false

#

Show me the scene

exotic hazel
#

one sec

cunning rapids
#

Specifically, the position of your "Ground Check" game object

#

It should be slightly below or at the player's feet

exotic hazel
#

those arrow is the groundcheck

cunning rapids
#

What

#

Dude, do you know what your script does?

exotic hazel
#

yea

cunning rapids
#

"isGrounded" acts like your feet

exotic hazel
#

i wrote it bruh

cunning rapids
#

Alright, what is your ground layer supposed to be?

cunning rapids
#

This your ground check? Is it attached to the player game object? Is the floor the correct ground layer?

exotic hazel
#

the groundcheck is the arrow in 2nd picture

cunning rapids
#

Show me the inspector for the movement code

exotic hazel
#

wait

#

i changed the terrain today

cunning rapids
#

Make sure your terrain has the correct layer for "Ground"

exotic hazel
#

dint apply ground layer to it :/

cunning rapids
#

or whatever you called it idk

cunning rapids
exotic hazel
cunning rapids
cunning rapids
exotic hazel
#

yep its working

#

finnaly spent the whole day on just the animal spawner and this jump

#

will setup the spawner tomorrow

#

thx

swift crag
#

Wrong Layer is a very easy mistake to make

cunning rapids
#

Yo fen

#

Your thing with my weapon problem worked yesterday

#

Thanks

#

Using Scriptable Objects helped

errant canopy
#

Hi, yesterday I got recommended to switch to Unity Event system for making my multiple triggers work. I've set it up and I'm getting notifications when touching each of them, but my problem wasn't that, more of how to know which one was touched.
https://paste.mod.gg/biegbuvflnfu/3

swift crag
cosmic dagger
errant canopy
swift crag
#

What do these triggers represent?

#

Are they mostly going to be "right" and "wrong" triggers?

errant canopy
#

Colored it to make it easier to see, but the idea is for me to know which trigger the player touched out of these

errant canopy
errant canopy
#

I'm still quite new to Unity

swift crag
wintry quarry
swift crag
#

But it looks like you're trying to explicitly avoid direct references here

#

since you're running everything through this GameEvent system

errant canopy
swift crag
#

I have to wonder if you actually need any of this

wintry quarry
#

Anyway you should make these things pass themselves in as a parameter to this event

wintry quarry
swift crag
errant canopy
swift crag
#

UnityEvent is used for things like the "on click" events on a button

errant canopy
swift crag
#

in this case, you just register different listeners for different triggers

#

(this code does not match your current code -- you're directly registering with a TriggerManager)

swift crag
#

like "do something any time an entity's health reaches 0"

spiral narwhal
swift crag
#

But this is not appropriate for setting up very specific one-off interactions.

errant canopy
swift crag
#

I wouldn't create a global event bus to handle a button that opens a door

#

The button will only ever do one very specific thing: open a door

#

The button should just directly reference the door and tell it to open

errant canopy
#

It's a core mechanic like the health example

swift crag
#

(or the door should directly subscribe to the button)

errant canopy
#

Have you seen the game "Exit 8", I'm making a small project to learn game development a bit, and trying to make a copy of that

swift crag
#

are you creating something like Antichamber's infinite hallways?

errant canopy
#

Not sure what that is

swift crag
#

It's a game based heavily around impossible geometry

#

which it accomplishes through a mixture of teleporting the player and Weird Shaders

errant canopy
#

Most simple way to describe what I'm doing is:
Playroom you look if there is a diferrence or not compared to the first room you spawned in. If there isn't, you walk forward, if there is, you walk backwards.
Between each level there is an area for a sign to show which level you're on.
If you were right about differences (or none) it goes up, if you were wrong, it goes down.

#

And I thought about player teleporting, but in the long term I believed that spawning and despawning would be easier.

swift crag
#

Okay, so all of these events are going to be either "success" or "failure"

#

in that case, just pass a bool

#

which will mean either:

  • right or wrong
  • change or no change
errant canopy
#

I have 2 type of maps

swift crag
#

the latter may be easier to deal with, since you won't have to tell the trigger managers about the correct answer

errant canopy
#

The normal map has the "correct trigger" in front, reverse is opposite ofc

swift crag
#

they'll just indicate which answer you chose

cunning rapids
#

And interact with

#

You can make one by creating a ScriptableObject script instead of MonoBehaviour

errant canopy
#

So I have 2 triggers for that on each, and then a 3rd that I would be at the "start" of the current level to handle despawning of previous map and changing the level sign area behind to the correct one.

errant canopy
swift crag
# errant canopy When you say scriptable objects, could you elaborate

You've already probably used lots of MonoBehaviour-derived classes. These are a kind of component (which is, itself, a kind of unity object). Components can be attached to game objects.

A ScriptableObject is another kind of unity object. It's not a component, so it can't be attached to a game object. Instead, you can store scriptable objects as assets -- much like a prefab, a texture, a material, etc.

short gust
#

hey guys, don't know where to ask about IDE/code editor problems with unity, so sorry if this an off-topic

I'm trying to move from Visual Studio 2022 to VS Code, but after proper setup by guide with packages, settings, extensions, etc. - VS Code is not compiling on save until I alt+tabbed back to unity, but intellisence, code completion, etc. is working fine still
am I doing something wrong? asset refresh in settings is checked both in Unity and VS Code, but it's not triggering at all
I found extension for VS Code that forces refresh, but I hope I messed up something during setup and just haven't done something, because Unity extension supposed to do that by itself

swift crag
#

since a ScriptableObject is a unity object, you can serialize references to them in the inspector

errant canopy
#

Right, ok, I wasn't sure about the terminology

swift crag
#

Unity is just looking for file changes.

errant canopy
short gust
errant canopy
#

But even if I pass a bool, how am I supposed to know if I should set it to true or not?
I still don't know which trigger is actually being touched?!

swift crag
#

"change" or "no change"

errant canopy
#

Yes. So for example how do I pass a bool with the true value to represent "changed"?

#

All I know now is that a trigger is being touched

#

How do I know if it's the "CorrectTrigger" or "WrongTrigger" that the player is touching

swift crag
#

You're going to need to modify GameEvent

#

it currently can't receive any arguments

#

Raise needs to take a bool parameter

errant canopy
#

Yeah done that

swift crag
#

also, I see you have UnityEvent in GameEventListener after all

#

so switch that from UnityEvent to UnityEvent<bool>

#

(i'd missed the other files)

#

er, actually, you'll need to do this:

#
[System.Serializable]
public class LevelChoiceEvent : UnityEvent<bool> { }

then

public LevelChoiceEvent Response;
#

Unity can't serialize fields with generic types in them (except for a few things, like lists)

#

public UnityEvent<bool> Response; wouldn't serialize

#

so you wouldn't be able to see Response in the inspector

swift crag
errant canopy
#

If I'm using UnityEvent<bool>, what would I use for the invoke method as an arguement?

swift crag
#

OnEventRaised will need to take a bool

#

since OnEventRaised now needs a bool, Raise will also need a bool parameter

errant canopy
#

Yeah, but what do I put in raise when I call it

swift crag
#

and since Raise now needs a bool parameter, TriggerManager needs to pass it one in its OnTriggerEnter method

swift crag
#

and that's where the chain ends!

errant canopy
#

Since we're now using UnityEvent<bool>

swift crag
errant canopy
#

Ah, right

swift crag
#

so:

  • TriggerManager has a bool field that it passes to GameEvent.Raise
  • GameEvent.Raise passes that parameter to GameEventListener.OnEventRaised
  • GameEventListener.OnEventRaised passes that parameter to LevelChoiceEvent.Invoke
#

and thewn LevelChoiceEvent.Invoke winds up running all of its listeners, passing them that bool parameter

errant canopy
#

Yeah, that all works nice and dandy

#

I'm still unsure how we can decide if the bool should be true or not depending on which trigger is touched

swift crag
#

TriggerManager needs a bool field.

#

If you know which one is which, just set it up in the inspector

#

check the box for the "Changed" trigger

#

That bool will not be "right" or "wrong"

#

I mean, it can be, if you pre-author each level and know the answer already

errant canopy
swift crag
#

I was imagining something where you randomly generate a "changed" or "not changed" level

swift crag
#

and then you just wait to see which trigger the player chooses

#

and, in response, you decide they were right or wrong

#

This way, you don't have to mess with the triggers for every single level

#

Their meaning is constant: "Change" or "No Change"

#

Keep the game logic out of the triggers.

errant canopy
# errant canopy

I'm gonna be completely honest and idk if I'm just extremely slow or something. But I still don't see how this setup allows for me to know which trigger is touched. You say "set it up in the inspector" but from the picture here, how would I do that?

swift crag
#

"Change" and "No Change"

errant canopy
#

Well 3, but yeah mainly 2. Don't worry about the last one.

swift crag
#

If there are more than two options, you need to handle that.

errant canopy
#

There are only correct or wrong

#

Last one is just for spawning things, I'll figure that out.

swift crag
#

Okay, so the third kind of trigger is completely unrelated to these two

#

The "Change" and "No Change" triggers.

errant canopy
#

Yes

swift crag
# errant canopy

Rename that field to "Changed". It will be true for the "Change" trigger and false for the "No Change" trigger

swift crag
#

Suppose I subscribed this method to my GameEventListener.

#
public void ChoiceMade(bool changed) {
  if (changed == correctAnswer) {
    Win();
  } else {
    Lose();
  }
}
#

if correctAnswer is false and changed is true, that means:

  • The level had no change
  • The player touched the "Changed" trigger

So, you lose

errant canopy
#

Yes, but the bool value is never changed?

#

When is the value of Change set to false or true on each corresponding trigger?

swift crag
#
[SerializeField] bool changed;

void OnTriggerEnter(Collider other) {
  onTriggerTouched.Raise(changed);
}
acoustic crow
#

Why is the Wheels Collider so far down

errant canopy
swift crag
#

give this a read if you're not familiar with these terms

errant canopy
#

Ok, yeah perfect. I'm really still new to Unity and only know slight few things. Thanks for the help 👍 😁

visual hedge
#
    private void Moving()
    {
        Vector3 dest = _grid.GetPositionCell(_index_grid);
        if (Vector3.Distance(dest, transform.position) > 0.1f)
        {
            Vector3 lerp = Vector3.Lerp(dest, transform.position, _speed_move);
            _rb.MovePosition(lerp);
        }
        else
        {
            _rb.MovePosition(dest);
            _is_moving = false;
        }
    }

Does this method needs to be run in update to work properly?

#

I mean... when I run it just as method from non-update... it only gets that RB around 30% of the distance...

#

So I guess the answer is it has to be run in update or ienumerator

wintry quarry
#

not Update

#

also that's definitely an improper usage of Lerp

visual hedge
hexed terrace
#

surely the guide told you were to put it 🤔

visual hedge
#

I think I will simply get rid of lerp since I don't plan using it anyways and I plan to use MoveTowards + Animate the character running

#

so this part is irrelevant, altho for self-education I willread the docs

visual hedge
shell sorrel
#

if there is physics involved and you are moving it use FixedUpdate

wintry quarry
#

MovePosition is actually a thing that moves the Rigidbody and its effect gets queued up to happen in the physics update, that's why it needs to go in FixedUpdate.

#

These "rules of thumb" are actually all just stand-ins for actually understanding how these functions and methods work and applying your knowledge to get the effect you want.

In reality there are no rules, but these things like "only use MovePosition in FixedUpdate" are designed to keep things working properly without thinking too hard.

burnt vapor
#

@sour yew This is a coding channel, which is for coding questions. Not for materials.

visual hedge
#

or it's actually there by default?

wintry quarry
#

for a Rigidbody though you'd probably want to use MoveRotation or set the RB's rotation with Quaternion.LookRotation

visual hedge
#

nah, I switched from RB to transform.position. My rb has different purpose

wintry quarry
#

those two may not be in sync

#

if you're doing physics it's usually best to deal with the Rigidbody

visual hedge
#
    private IEnumerator MoveThePlayer(Vector3 dest)
    {
        dest = dest + new Vector3(0, 0.5f, 0);
        if (is_moving)
        {
            yield break;
        }

        is_moving = true;

        while (MoveToPosition(dest))
        {
            yield return null;
        }

        PlayerState = PlayerStates.IDLE;
        is_moving = false;
    }
    private bool MoveToPosition(Vector3 target)
    {
        return target != (transform.position = Vector3.MoveTowards(transform.position, target, animSpeed * Time.deltaTime));
    }

done it like this

visual hedge
#

thank you

shut spade
frosty lantern
#

Hey I'm using mouse deltas to control the rotation of my camera, but you can visibly see the ticks between the angles when you move the mouse slowly. I tried slerping but it doesn't keep up with the natural movement of the mouse, and when you move quickly the rotation tends to bounce back

#

how would I smooth out the rotation for slower turning?

visual hedge
#

Not 0... physics, but... I mean I am not going to use physics at all

#

it's turn based game without any physics. I won't be needing to jump or something. And I will definitely get away with MoveTowards and so on.

frosty lantern
#

attempt one bounces in the other direction at high speed, attempt 2 just doesn't work

rocky canyon
#

ur first attempt looks the closest

#

just needs a slerp

#

and i know u said u tried it.. but it was most likely implemented incorrectly

frosty lantern
#

yeah i just don't know the variable to slerp over

rocky canyon
#

ull slerp the right side of this

frosty lantern
#

yeah so i slerp the current rotation to the new one, but I don't know what to put for the float to smooth it out but not cause bugs

rocky canyon
#

since ur rotating it in update u'd probably want to use some modifier multiplied with time.deltaTIme;

#

and then adjust that modifier in the inspector until it rotates like u want

frosty lantern
#

yeah, delta time felt nice at slow speeds, but at higher speeds it bounces. so I need my modifier to increase at larger mouse speeds

#

so I tried multiplying by the magnitude of mouse delta

#

but that didn't work

#

because mouse delta's in pixels

#

so then I divide mouse delta by the magnitude of the width and height of the screen

#

and my camera doesn't rotate

rocky canyon
#
void Update()
{
    // Calculate the target rotation based on mouse input
    float targetYRot = yRot - mouse.delta.y.ReadValue() * Time.fixedDeltaTime * panSpeed;
    float targetXRot = xRot + mouse.delta.x.ReadValue() * Time.fixedDeltaTime * panSpeed;
    targetYRot = Mathf.Clamp(targetYRot, yMin, yMax);

    // Smoothly interpolate the rotation using Quaternion.Slerp
    Quaternion currentRotation = transform.rotation;
    Quaternion targetRotation = Quaternion.Euler(targetYRot, targetXRot, 0);
    float slerpSpeed = 0.1f; // Adjust this value for the desired rotation speed
    transform.rotation = Quaternion.Slerp(currentRotation, targetRotation, slerpSpeed);

    // Update strafe and accel variables
    strafe = Input.GetAxis("Horizontal");
    accel = Input.GetAxis("Vertical");
}```
#

it'd look similar to this, where ur building ur rotations before hand.. and then slerping

frosty lantern
#

for slerpspeed I don't want to limit the speed of rotation. I want it to line up tith the normal rotation, the slerping is just to smooth out the sudden ticks at lower speed. that's what I'm not sure about

#

but I should work on comments and organising anyways

rocky canyon
#

not sure i understand.. ur normal rotation (w/o smoothing) is just gonna be what it is.. its smoothing that prevents the jerky and snappiness

#

w/o it.. it would still be jerky.. u would need smoothing but very little of it

#

this is the new input system? i always had issues w/ mouse delta's

frosty lantern
#

yeah, i'm using the slerp function to prevent the jerky rotation

#

yes it's the new input system

rocky canyon
#

theres tutorials i found not too long ago that showd ways to use mouse delta w/ different settings in the input system that kinda helped w/o doing any smoothing in code.

#

let me see if i can't find one of em for reference

#

the actual problem/fix starts @ 1:00

visual hedge
#

Thank you all for the help, got it done, so far movement and so on works like intended

rocky canyon
#

eziest speed run ever 🙂

#

did that help?

frosty lantern
#

Hm. I think the issue might not be the input system but rate just the update rate or the precision. my setting was already on dynamic.

rocky canyon
#

oh, well they probably started using that as the default setting since ive used it

frosty lantern
#

yeah, probably

rocky canyon
#

idk mate, but the update runs super fast..

#

cant be that

frosty lantern
#

the stutter isn't it not receiving or overcompensating for a movement, but it's like a 10fps rotation as opposed to sixty or smth

rocky canyon
#

I poll for my player input the old system so i have no examples i can look at of my own to help out w/ ur setup

frosty lantern
#

well I guess i'll live for now, it's a mild QoP issue

rocky canyon
#

i simply use a basic slerp for rotation

#

and i multiply my inputs by a sensitivity modifier (for the speed)

rocky canyon
#

player movement / feel is 1 of the more important things

queen adder
#

Hi I have a question, if two gameobjects collide and i want them to be a trigger and not to actually collide, is it fine to have a rigidbody and a collider with no trigger on one gameobject and just a collider with on the other gameobject with the trigger on? sorry if i explained it bad im new to unity

rocky canyon
#

yes

#

but another route (if u dont want any interaction to happen) and u just want it to pass thru.. u can set Include / Exclude option in the inspector to ignore each other..

frosty lantern
# rocky canyon

I think my issue her is that if I move my mouse at a moderate speed, it covers more than 180 degree rotation, so the slerp bounces back to chase the shortest path to the new rotation

shut spade
rocky canyon
#

or can set up layers and use the layer matrix in the physics settings of the project settings to have two layers ignore each other

rocky canyon
#

could very well be whats happening

frosty lantern
#

so how do i maintain a "path" to slerp through?

rocky canyon
#

and thats what will happen.. if 1 direction is closer to the other.. its gonna take the shortest path

frosty lantern
#

would I need to set up an enum to track the iterations of rotation and ensure each rotation is met?

rocky canyon
#

simple fix would be to clamp ur mouse delta... so it only lets u rotate in certain increments

rocky canyon
#
  // Smooth mouse input
    Vector2 mouseDelta = new Vector2(mouse.delta.x.ReadValue(), mouse.delta.y.ReadValue());
    smoothedDelta = Vector2.Lerp(smoothedDelta, mouseDelta, smoothingFactor);```
#

could also smooth ur delta before u use it

frosty lantern
#

oh wow

rocky canyon
#

just brainstorming for ya

frosty lantern
#

let me see how that works ill be a sec

rocky canyon
#

to me i work in iterations / trial and error.. when people post issues with movement code its always a challenge to know what will work and whats best..

#

b/c w/o the context and the lead - up to what u have.. its harder to troubleshoot little issues

queen adder
# rocky canyon yes

I want it to display "hit" to the console when they collide but right now they just go through each other

rocky canyon
#

isKinematic rigidbodies dont respect collisions

#

it'll have to be a regular rb to trigger isTrigger colliders

frosty lantern
#

amazing

#

perfecto

#
   void Update()
   {
       yRot -= mouse.delta.y.ReadValue() * Time.fixedDeltaTime * panSpeed;
       xRot += mouse.delta.x.ReadValue() * Time.fixedDeltaTime * panSpeed;
       deltaRot = new Vector2(xRot, yRot);
       slerpRot = Vector2.Lerp(slerpRot, deltaRot, Time.deltaTime);
       yRot = Mathf.Clamp(yRot, yMin, yMax);

       strafe = Input.GetAxis("Horizontal");
       accel = Input.GetAxis("Vertical");
       transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, slerpRot.x, 0) * Quaternion.Euler(slerpRot.y, 0, 0), smoothSpeed);
   }
    ```
#

it's perfect

#

messy but perfect

rocky canyon
#

👍 glad it works

wintry quarry
swift crag
#

it's kind of less wrong than just Time.deltaTime, since at least it's a constant

rocky canyon
#

yea ur delta is gonna be frame-independent anyway

wintry quarry
#

it's doing nothing except dividing panSpeed by 50

swift crag
#

mouse input is a distance

wintry quarry
#

but yeah

swift crag
#

it is not a rate of change

rocky canyon
#

just a simple constant should be enuff

swift crag
#

People usually use Time.deltaTime by mistake there

#

which winds up giving you very weird mouse input

#

the longer the frame, the larger deltaTime is -- and the more the mouse has moved in that frame

#

so as your game gets slower, your mouse gets more sensitive

queen adder
rocky canyon
#

soo i edited unity's URP template to make this readme.. it works and all but I get this error when opening the project

AmbiguousMatchException: Ambiguous match found.
System.RuntimeType.GetMethodImplCommon (System.String name, System.Int32 genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) (at <eef08f56e2e042f1b3027eca477293d9>:0)
System.RuntimeType.GetMethodImpl (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) (at <eef08f56e2e042f1b3027eca477293d9>:0)
System.Type.GetMethod (System.String name, System.Reflection.BindingFlags bindingAttr) (at <eef08f56e2e042f1b3027eca477293d9>:0)
ReadmeEditor.LoadLayout () (at Assets/Spawn_Readme/Scripts/Editor/ReadmeEditor.cs:73)
ReadmeEditor.SelectReadmeAutomatically () (at Assets/Spawn_Readme/Scripts/Editor/ReadmeEditor.cs:63)
UnityEditor.EditorApplication.Internal_CallDelayFunctions () (at <bf6080dbf0564cf1b405dfd6e0dac725>:0)
frosty lantern
#

removed the fixeddeltatime and lowered panspeed

#

still amazing

rocky canyon
#
static void SelectReadmeAutomatically()
    {
        if (!SessionState.GetBool(s_ShowedReadmeSessionStateName, false))
        {
            var readme = SelectReadme();
            SessionState.SetBool(s_ShowedReadmeSessionStateName, true);

            if (readme && !readme.loadedLayout)
            {
                LoadLayout();
                readme.loadedLayout = true;
            }
        }
    }

    static void LoadLayout()
    {
        var assembly = typeof(EditorApplication).Assembly;
        var windowLayoutType = assembly.GetType("UnityEditor.WindowLayout", true);
        var method = windowLayoutType.GetMethod("LoadWindowLayout", BindingFlags.Public | BindingFlags.Static);
        method.Invoke(null, new object[] { Path.Combine(Application.dataPath, "SpawnReadme/Layout.wlt"), false }); // the error is here..
    }```
#

it worked before I changed the name / directory

#

but all i have done is renamed the folder from TutorialInfo to Spawn_Readme

#

and changed the matching strings in the Readme.cs script

languid spire
#

SpawnReadme not Spawn_Readme

rocky canyon
#

ohhh! really?

swift crag
#

changing strings shouldn't be causing an error when trying to resolve the method group, though...

languid spire
#

method.Invoke(null, new object[] { Path.Combine(Application.dataPath, "SpawnReadme/Layout.wlt"), false });

rocky canyon
#

yea, ive had this issue before and i couldnt figure it out

#

so i gave up on it until now

#

let me try w/o the underscore

#

if i mark the readme.asset as isLoaded = true it doesn't error.. but that was just bypassing it lol

rocky canyon
frosty lantern
#

oh I see path string in the code is different from the folder name

swift crag
#

I don't see any method that matches what you're doing, though -- there are only two methods named LoadWindowLayout and neither takes one string and one bool argument

languid spire
#

yep

rocky canyon
#

dynamic rigidbodies. are kinda the important part to detect collisions

swift crag
#

There is TryLoadWindowLayout

#

but not LoadWindowLayout with those args.

rocky canyon
#

ya its just unity's readme..

#

i hadn't changed anything but the filename string

frosty lantern
#

yeah theres an underscore in the folder name but not in the code

swift crag
rocky canyon
#

ya, it still shows the readme if i select it.. but it doesn't load up on first start

#

like unity's did.. but yea i didnt catch that typo

#

i got it right up here 😄

woven crater
#

do i need to learn how to save the grid and load it or do i just need to make a scene asset for each level

rocky canyon
languid spire
rocky canyon
#

pre-me-fukin it up 😄

rocky canyon
languid spire
#

rofl

woven crater
#

neeed direction

rocky canyon
#

i copied the setup after i modified it and pasted it into other projects w/ their meta files..

#

question being.. the instanceID isn't a problem b/c of the meta files being transfered along side it?

#

it worked fine after recompiling.. so i guessing its a non-issue

swift crag
rocky canyon
#

mmhmm its not hard to do 😄

#

i was worried about that layout.wlt file..

#

b/c i have no idea how those work

#

but seems u keep the directory intact its pretty easy to copy over/ move to other projects locations

swift crag
#

oh, actually..

#

no, it's not just when the path is messed up

#

The code just doesn't work at all.

cunning rapids
#

Hello guys, I found this extremely satisfying and relatively simple recoil system on youtube, however, with its implementation I was wondering how would you set different recoil values for different weaponss, if they all follow the values of a single parented object?

https://www.youtube.com/watch?v=geieixA4Mqc&t=0s

Newest video! (The Craziest Dev Challenge I've Ever Done) - https://www.youtube.com/watch?v=x7js1DhgEi8&ab_channel=Gilbert

Welcome to my first tutorial for Unity!
In this tutorial I show you how to use recoil to make your guns a lot more punchy! Unfortunately this tutorial doesn't show you how to animate your weapons for the full recoil effect....

▶ Play video
rocky canyon
#

can't say after that tho..

swift crag
#

Does it actually run, though?

rocky canyon
#

well something has to make it focused to the readme when the project opens

swift crag
#

That's not what the method does

#

The method loads a layout

#

There's a separate method to select the readme asset

rocky canyon
#

ohhh ya, i cant say if that parts working or not..

#

my layout always looks like my last version i used

#

but it does set the bool to true

#

lol..

rocky canyon
swift crag
#

yep, bingo

rocky canyon
#

or extract it and put it on the weapon.. and have it read the value from there instead

swift crag
#

cracked open the template

#

loadedLayout: 1

#

loadedLayout is set to true in the template and the code never runs

cunning rapids
rocky canyon
#

mmhmm

swift crag
#

I'm guessing that Unity removed the matching LoadWindowLayout method and replaced it with a TryLoadWindowLayout

#

But since they were using reflection to access the internal methods, this refactoring wasn't noticed

rocky canyon
#

ahh, i think imma just remove that part.. i dont need it to force a layout.. it was meant to show dependencies.. so if u click the readme asset..

swift crag
#

and they just wound up giving up on loading a layout entirely

rocky canyon
#

the readme will still be drawn in the inspector..

swift crag
#

yeah, there's no point in trying to load a custom layout anyway

#

the entire thing should just be removed

rocky canyon
#

nice.. thanks for looking mate 🙂

rocky canyon
minor glen
#

Hello, I'm currently on a school project. In this school project I have a Cylinder Gameobject ("electrode") and another Cylinder GameObject ("electrode holder"). "electrode holder" is a parent from "electrode". "electrode" 's scale following the Y-Axis is being modified. I want to be sure the "electrode" 's face facing "electrode holder" stays at the same position. How can I do ?

Thanks

rocky canyon
#

how does scaling it change the rotation?

#

either way.. if ur modifying the transform of a child object. best to make sure that the parent is scaled to 1:1:1

#

Electrode_Holder and Electrode are both 1:1:1 across the board..

#

i scale the _Graphics obj's instead..

#

then u can do all ur other stuff (movement/rotations/etc) to the Root obj's

#

and since they're 1:1:1 they should be fine

#

scale the graphics (rotate the parent) -> this will keep dimensions and stuff the same

#

if u scale the graphics and (rotate the child) -> this will break ur scales and cause weird stuff

minor glen
#

I'll try on my side (my electrode holder is not 1:1:1).
In case I need to use colliders, on what Object do I apply it ? The project is to simulate some electrode soldering (so the electrode is consumed when in contact with the table)

cunning rapids
#

@rocky canyon Yo so like, how do I change the values of the recoil script through the revolver script:

bleak pasture
#

Im a bit confused about coordinates, if I move an object from one end of my terrain to another supposed on the same axis I get: FROM: World space: Vector3(-8852.64, 76.46, -1066.66) 884.997,-6.044,3 (local space)
to: World space: Vector3(-8852.64, 99.11, 0.04) -181.701,16.606,3 (local space). World space is obtained from using the .transform property. I dont understand why I didnt move it on the Z axis in the local space ? the object has a rotation of 0,90,0

#

is the code showing world coords not correct ?

polar acorn
bleak pasture
#

the local space was obtained from the transform x,y,z in the inspector while the object is a child of the terrain gameobject

#

are the axis inverted in world space or something ?!

polar acorn
bleak pasture
#

cuz it seems my translation along the X axis in local space was done on the Z axis in world space...

languid spire
polar acorn
bleak pasture
polar acorn
languid spire
#

so you are using the object forward

bleak pasture
#

and I adjusted height with the green arrow

#

huh no idea how to know if it is local or world. I guess that would be somewhere in unity learning

polar acorn
#

So, was this gizmo in local or global?

bleak pasture
#

so local

polar acorn
#

There is no way to know how this might affect the global position on any particular axis

bleak pasture
#

I should set the gizmo to work in world space then ?

polar acorn
#

I don't know what you're trying to do, so I don't know what you "should" be doing

cunning rapids
#

The more I code my game, the more it starts looking like just a bunch of spaghetti code

#

Anyways, thanks @polar acorn

bleak pasture
#

well Ill try to put into words what Im doing cuz I have no idea myself and come back

rocky canyon
#

the removed comment, i think it was b/c you hadn't declared a variable named hit

#

in the doc's for raycast u can see here they delcare a RaycastHit called hit.. and then the function uses that variable

rocky canyon
#

so u go back learn about it more. and start refactoring ur code.. *this time using more coding practices that allow for optimization/ expandability

primal shadow
#

Can anyone help me with making a world in vrchat im a 3D designer not a coding exspert so wjag should i lear what code (U# ,udon ,)

eternal falconBOT
primal shadow
#

Yes im in that but what code shoild i
Use

rich adder
summer stump
rich adder
#

ask the community which knows about this specific plugin workflow..

polar acorn
#

The VRChat discord is the place to ask this

rocky lava
#

My camera isnt attached to my cameraholder for some reason, my cameraposition (first pic) is in the player, but the actual camera position when i press play, it's all the way back here (2nd pic)

polar acorn
#

Set it to pivot and see where the camera actually is

rocky lava
#

for the camholder

#

for the camera

#

this is the code btw 1 for the mouseinput and 2 for the following of locking of the camera to a position

rich adder
rocky lava
#

NVM I GOT IT

summer stump
# rocky lava

Is your gizmo set to center or pivot?
Also, don't crop images so much

rocky lava
#

ty guys!

rich adder
#

also do not multiply mouse by Time.deltaTime

polar acorn
rocky lava
summer stump
#

Still cropped too much. Why are you cutting the image off so much?

rocky lava
#

oh because i thought it was the only thing that was needed, but i fixed it!

rocky canyon
#

the entire screen is always best

rich adder
# rocky lava

btw notice how you have to crank the sensitivity to 400 to work? remove Time.deltaTime on mouse, if you havent

rocky canyon
#

sensitivity? yes.

rancid tinsel
#

im trying to check if between the script holder and the player, there is a wall object with the tag "Wall" - but it never returns true even if there is a wall. Any ideas what I did wrong? https://gdl.space/doquxoruze.cs

summer stump
#

To see if it is going the direction you expect

#

It SHOULD be, but just in case

#

Also, debug the hits

final kestrel
#
myForcedLookTarget = transform.Find("DemoForceLookAt").gameObject.GetComponent<DemoForcePlayerLookAt>();
        revealCurtain = transform.Find("DemoCutsceneStage/CurtainReveal").gameObject;
        mySpeaker = transform.Find("DemoCutsceneStage").gameObject.GetComponent<AudioSource>();

I learned that finding objects this way is expensive. What other way is more efficient and lighter?

rocky canyon
#

using components

summer stump
rocky canyon
#

or tags or ^

rancid tinsel
rocky canyon
#

nothing wrong with using Find once.. in a start / awake function to grab references

#

but using them in update (all the time) is really bad

final kestrel
#

Ah so okay. Thanks a lot for the answers

polar acorn
final kestrel
#

oh

rocky canyon
#

ya, strings suck

#

if u ever change a string w/o thinking about all ur code they're all gonna miss over the objects ur hunting

final kestrel
#

All right. Got it.

polar acorn
#

But drag in references whenever it is possible to do so. Faster, easier, less error-prone

rancid tinsel
polar acorn
rancid tinsel
#

how do i check if between two points, there is a gameobject with the tag "Wall"?

wintry quarry
#

a raycast is a good way

summer stump
wintry quarry
#

LineCast actually would be better

rocky canyon
#

u do

rancid tinsel
#

got rid of the isWallBetween(); bit

rocky canyon
#

(); x 2

rancid tinsel
rocky canyon
#

if u want u can use layers.. and a layermask

summer stump
rocky canyon
#

so 1 raycast only detects walls

solid bough
#

whenever me or my friends make a pull from our github (or checkout to a new branch, anything) we get the 'object reference not set to an instance of an object' error and need to assign the references over and over every single time

how can we make it so that they already come assigned?

polar acorn
solid bough
polar acorn
solid bough
polar acorn
#

And both the object you are referencing and whatever has AttackingRange on it are both in the scene to start, right? Neither one is spawned at runtime?

solid bough
polar acorn
visual hedge
#

I have dungeons like this in my game. Basically such a map is a dungeon. Game = turn based.
There are tiles in dungeons where player meets enemy and battle scene is loaded. Game manager (singleton, as is also persistent in battles) returns player afterwards to the dungeon (if player weren't killed in turn- based battle). But...
Any suggestions on how do I keep track of which enemies were destroyed already and which chests were opened? Basically best approach to store the progress?
I intend to use json at this point if that's the way. Do I store all the tile information and then when player re-enters the dungeon instantiate the information from the tiles that weren't cleared yet?

wintry quarry
visual hedge
wintry quarry
visual hedge
rocky lava
#

is there a better way to make these stairs walkable, i keep having to press A and D to get it to work and i get stuck at the top

wintry quarry
#

A simple component like this might do the trick @visual hedge


public class GridItem : MonoBehaviour {
  [SerializeField, HideInInspector]
  private string _uuid = "";

  public string Uuid => _uuid;
 
  private void EnsureUuid() => if (_uuid == null || _uuid == "") _uuid = Guid.NewGuid().ToString();

  void OnValidate() {
    EnsureUuid();
  }
 
  void Reset() {
    EnsureUuid();
  }
}```
wintry quarry
visual hedge
wintry quarry
#

you don't need to use any lambdas - I just wrote it quickly in Discord

visual hedge
#

yeah, I will look into it, thank you 🙂 LEt me compute the thing you wrote 🙂

rocky canyon
#

use ramps as colliders 😉

wintry quarry
#

They seem to be using box colliders

#

unless there's another collider they're not showing

rocky lava
#

yeah i am

#

just box

#

the stairs arent colliders

deep lotus
#

Hey, I'm making a platformer, and I wanna make a custom script for collisions because I don't think the default one can do what I want.

Basically, I want the player to not collide with a platform if it is hidden behind another object, if the platform is partially hidden, I still want the player to collide with the part that is visible but not with the hidden part

rocky canyon
#

thers no code handling walkin up and down stairs.. rigidbody's dont do those too well unless suplemented w/ code to traverse them

ionic zephyr
#

Anyone knows if its a good idea to implement a character roaster with scriptable objects?

swift crag
#

it's been pretty nice

#

It does feel slightly weird for EntityInfo to reference the Entity and for the Entity to refer back to its own EntityInfo

#

I store things like "name" and "description" in the EntityInfo

#

so the Entity has to know about its EntityInfo so that it can tell you what its name is

polar acorn
swift crag
#

🔥

ionic zephyr
swift crag
#

get one of those costco chicken ovens

ionic zephyr
#

oh shit, it is spelled without the "a"

#

sorry, spaniard here

polar acorn
#

Yeah just joking about the typo, ignore me

quiet scaffold
#

whats a good way to do enemy spawning restrictions in 2d? i dont want the enemies to spawn too close/on the player, but also i dont want them too far away

timber tide
#

depends how many you are spawning

#

but usually you can get away with some sphere casting or distance checks

rich bluff
visual hedge
swift crag
visual hedge
wintry quarry
#

you just need some kind of unique identifier

#

you might want to think about things like "what happens if I update the game and move the chest?"

#

A UUID could solve that problem, the V3I solution doesn't. But that might not matter to you

visual hedge
#

yeap. I was thinking about using scriptable object to hold the information about the tile, but I am not so sure about that now... I mean there's very elegant ways to do so and not so elegant... and I gues I will have to take the simpliest one for now 🙂

timber tide
#

you'dhave a serializable container with the grid id and item id

rich bluff
#

yeah its much simpler to use unique id for serialization than to try to bind tile position to object that could have moved, or tile can have many, or object could not even be there anymore and so on

visual hedge
austere hedge
#

My goal is to select the text in the DisplayDifficultyLabel object, and modify the text. I believe what I have to do is get all the components in the children, that are specifically the text type, and store them in an array. If I can do this part, then I can probably figure out the rest.

I have tried the following:

var foo = GameObject.Find("GameOverMenu").GetComponentsInChildren<Text>();
var foo = GameObject.Find("GameOverMenu").GetComponentsInChildren<TextMesh>();

Both of these gives me an empty array.

swift crag
#

Just reference the thing you need directly.

#

Or are you generating these difficulty labels things at runtime?

ionic zephyr
#

if I want to perform a dodge should I use a bool or disable the collider??

austere hedge
#

So maybe var foo = GameObject.Find("DisplayDifficultyLabel").GetComponentInChildren<Text>(); ?

swift crag
#

no, just add a List<Text> field and drag the things you need into it

#

also, if you're using TextMeshPro, you have the wrong type

#

Text is the legacy Unity UI text

austere hedge
#

I am, so is that TextMesh?

swift crag
#

The correct type is TMP_Text

#

which covers both TextMeshPro (non-UI) and TextMeshProUGUI (UI) text components

rich bluff
#

or the legacy text thing yup

ionic zephyr
austere hedge
rocky canyon
#

soo dpi cant be read by unity software?

eternal needle
# ionic zephyr or should I change the layer of the object?

Different solutions work on different things. For example if you disable the collider and are using rigidbody movement, you are falling through the floor. If you rely on the layer for other things, which you want to still function during this time, then changing the layer wont work either.

ionic zephyr
#

oh okay, so the best day would be a boolean right?

eternal needle
# ionic zephyr oh okay, so the best day would be a boolean right?

🤷‍♂️ maybe. I wouldnt say it's the best because something suddenly has to check this bool. If you have a rigidbody projectile, your bool will have 0 effect on the object and it will still collide with your player even if it doesnt damage them. I think layers could work fine because you can do layer based collision

#

It all depends on your system

ionic zephyr
#

hmm I see, so maybe changing the Layer of the object should be more precise?

eternal needle
paper star
#

Can someone help me with a plugin quick

#

Assets\Scripts\PlayerMovement.cs(17,5): error CS0246: The type or namespace name 'RigidBody' could not be found (are you missing a using directive or an assembly reference?)

#

RigidBody rb;

icy junco
#

hello i have like kind of a problem with my movement when i am moving everything is fine but when i try to sprint its like stuttering could this be because of the sprint function being in the fixedupdate?

paper star
#

is what i typed

icy junco
#

okay thx

paper star
icy junco
#

wdym

paper star
#

in visual Studio 2022

#

for some reason

summer stump
#

!ide

eternal falconBOT
paper star
#

thanks

summer stump
#

Your IDE is not configured if it didn't suggest the correction for you btw

eternal needle
icy junco
#

what is the link to put code snipet in here

eternal needle
eternal falconBOT
icy junco
#

this is movement code

icy junco
ionic zephyr
#

how can I make a layer not to collide with specific layers?