#💻┃code-beginner

1 messages · Page 326 of 1

hexed terrace
#

by base, do you mean built-in RP

lost anvil
#

yep forgot the name

ripe spire
#

hi can someone help me with this script and tell me what am I doing wrong

hexed terrace
languid spire
hexed terrace
#

gotta fix those top two compile errors

summer stump
#

The important bits of the errors are cut off

languid spire
#

so why would expect a Unity Editor API to be available in a build?

#

you are referening an Editor only namespace, that does not exist in a build

summer shard
#

where do i post questions about lightning

polar acorn
#

You cannot use anything from any UnityEditor namespace in a build

swift crag
#

You probably added a using directive by accident.

swift crag
#

Your IDE can auto-insert them based on the types you're trying to use

ripe spire
swift crag
#

Yes, because System.Random is probably not the Random you actually wanted.

polar acorn
hexed terrace
#

You've been given the info to fix it

polar acorn
hot shore
#

Hello, im new in unity and was just wondering how games like sims 4 handle pause when in build mode? I see that it doesnt entirely pause the game since it still lets me move and place objects/furniturr on screen

polar acorn
swift crag
#

"Pausing" is a pretty vague concept

#

You aren't completely freezing the game

#

(that would be useless; you couldn't unpause!)

#

If everything respects the current timescale correctly (so, nothing cares about the exact frame count or framerate), setting the timescale to zero will pause your game world

#

But you can still make parts of your game not respect the timescale

#

My menus all use Time.unscaledDeltaTime

#

as does the spectator mode, which means you can fly around even when the game is paused

hot shore
#

Oh i see so i just have to set timescale to 0 and manually specify the parts that should not respect the timescale and use unscaleddeltatime. Thank you guys!

full wave
#

how do i return all GOs with a set tag ("mass"), except the GO thats running the script?

tawdry rock
#

how can i reach the SkinnedMeshRenderer material's emissive property?

exotic plank
swift crag
#

true

swift crag
polar acorn
tawdry rock
polar acorn
tawdry rock
polar acorn
tawdry rock
#

this thing?

polar acorn
#

So that'd be the string you'd use to set that float

chrome tide
#

I'm making a menu animation. First i set it's Y size to 0 so it isnt visible:

rect.localScale = new Vector2(rect.localScale.x, 0f);```
then i call an OpeningAnim() method so it will scale up the Y value, creating a cool animation as if the UI "jumps" out:
```cs
public void OpeningAnim()
{
    rect.DOScale(new Vector2(rect.localScale.x, 1f), duration).SetEase(Ease.OutBack);
}```
The problem i have is that the Title, Play and Exit text objects (those are TextMeshPro objects) dissapear after calling OpeningAnim. It also happens when i set the scale normally (`rect.localScale = new Vector2(rect.localScale.x, 1f);`), not via DOTween's DOScale (`rect.DOScale(new Vector2(rect.localScale.x, 1f), duration).SetEase(Ease.OutBack);`). the only objects that are still visible are images.
Note that I scale the whole Canvas object.
I also provide these screenshots with my hierarchy objects, how the menu is supposed to look and how it should not.
wintry quarry
chrome tide
chrome tide
wintry quarry
#

which object is the canvas

#

"Menu"?

chrome tide
#

yes

#

Menu

wintry quarry
#

SO what's the effect you want?

#

You want everything to stretch?

#

Or what

chrome tide
#

i want it to go from scaleY 0 to scaleY 1

wintry quarry
#

that's a code answer

#

I want to know what effect you're trying to achieve

#

visually

#

Do you want things to stretch or do you want things to... be slowly revealed as if being uncovered by something?>

chrome tide
#

i want it to suddenly stretch

#

the animation is done right, i tested it and the images are animated properly. the only issue is that the Text objects (game title etc) dissapear for some reason.

tawdry rock
polar acorn
charred spoke
carmine elm
#

i never had this problem, but if i try to declare a Vector3 i have to declare it UnityEnginge.Vector3 to work, what can i do?

charred spoke
#

Put using UnityEngine; at the top of your script

carmine elm
#

it is there

wintry quarry
#

Show your code and the errors you're getting. You did something wrong

charred spoke
#

Or is it because you have an ambiguous declaration from another lib ?

wintry quarry
#

probably that

#

you probably have using System.Numerics;

#

But yeah sharing the error message will reveal everything

charred spoke
#

If the other lib is needed you can set an alias using Vector3= UnityEngine.Vector3 at the top

carmine elm
vital hinge
#

could someone help me out troubleshoot/debug/fix a score system im trying to implement in a flappy bird like game?

blissful spindle
#

Hi, I would like to take for example a number 1 and increase it to number 10 in 2seconds how would I be able to achieve that? (yes I do know its a silly question)

I want to do this for a smooth transition between FOV changes

wintry quarry
wintry quarry
#

DOtWeen is a good option too

blissful spindle
wintry quarry
#

those are not mutually exclusive things

chrome tide
wintry quarry
# blissful spindle hmm I see since I dont understand Coroutines will check out the Mathf solution T...

for fov change it would be very simple. Something like:

float zoomFov = 40;
float normalFov = 90;

float targetFov;
float currentFov;
float fovChangeSpeed = 100f;
Camera myCam; // make sure to assign this

void Start() {
  currentFov = normalFov;
}

void Update() {
  currentFov = Mathf.MoveTowards(currentFov, targetFov, fovChangeSpeed * Time.deltaTime);
  myCam.fov = currentFov;
}

void Zoom() {
  targetFov = zoomFov;
}

void UnZoom() {
  targetFov = normalFov;
}```
charred spoke
chrome tide
#

it doesn't, it is as if i didn't add this TextMeshPro mesh update:

chrome tide
#

one way or another, it still should update the text's mesh.

willow scroll
#

The ForceMeshUpdate method should be called just before performing any calculations, which may require the updated info of the text.

#

Calling it every 1 second is blind-guessing

vital hinge
wintry quarry
#

it's the same as any other NullReferenceException

vital hinge
#

what does that mean?

willow scroll
wintry quarry
vital hinge
#

cuz the score isnt updating

wintry quarry
#

Yeah because you haven't referenced something properly

#

you're trying to use a reference that is not assigned

#

look at the filename and line number in your error

#

it tells you exactly where to look

#

Score.cs line 16

vital hinge
wintry quarry
# vital hinge

You don't have a UnityEngine.UI.Text component attached to the same GameObject as this script

#

simple

vital hinge
wintry quarry
willow scroll
# vital hinge perfect lol

Imagine having a red apple in your room and trying to eat it. But you cannot eat it, because it doesn't exist. It is null and gets an error.

wintry quarry
#

No Text there
So the GetComponent returns null.

chrome tide
vital hinge
wintry quarry
#

Do you see a Text component here anywhere?

#

I don't

#

So the code won't find one

#

because it doesn't exist

willow scroll
vital hinge
#

this one

wintry quarry
wintry quarry
willow scroll
vital hinge
vagrant zealot
#

The problem is on GameManagerState but i cant really understand the problem i would be glad if someone can help

wintry quarry
#

m getting an error on GameManager.GetComponent<GameManager>().SetGameManagerState(GameManager.GameManagerState.GameOver); at the first block of code
You should share the error. WE're not mind readers

#

"an error" is too vague

wintry quarry
# vital hinge

You probably just have another copy of this script in the scene where there is no Text component

willow scroll
#

Please, consider sharing the error. You're probably getting a NullReferenceException

vital hinge
wintry quarry
#

¯_(ツ)_/¯

willow scroll
warm geode
#

is it possible to crash in untity because of simply clicking a button

vagrant zealot
#

Error was in my language so its my bad not to share , its CS1061 it says "gameobject" does not contain a "GameManagerState" definition, and no accessible "GameManagerState" extension method was found that accepts a first argument of Type "GameObject". (maybe you are missing a usage directive or assembly reference?)

wintry quarry
vital hinge
warm geode
#

this script is huge

vital hinge
willow scroll
wintry quarry
warm geode
#

atleast for a beginner like me :/

wintry quarry
#

Also that's not a very big script

warm geode
#

the button sets iscrouching to true which then calls the crouchtransition function

wintry quarry
#

this code is pretty explicitly an infinite loop

#

nothing inside the while loop changes heightDiff

#

so if that condition is true at the start, it will be true forever

willow scroll
wintry quarry
#

This also looks like something that is supposed to be in a coroutine @warm geode

#

you would need frames to elapse between each loop for this to make sense

vagrant zealot
#

hey!


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if((collision.tag=="EnemyShipTag")|| (collision.tag == "EnemyBulletTag"))
        {
            PlayExplosion();

            lives--;
            TextLives.text = lives.ToString();

            if(lives == 0)
            {
                GameManager.GetComponent<GameManager>().SetGameManagerState(GameManager.GameManagerState.GameOver);
                gameObject.SetActive(false);
            }
            
        }
    }
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{

    public GameObject playButton;
    public GameObject playerShip;
   public enum GameManagerState
    {
        Opening,
        Gameplay,
        GameOver
    }
    GameManagerState GMState;
    void Start()
    {
        GMStat e= GameManagerState.Opening;
    }

    // Update is called once per frame
    void UpdateGameManagerState()
    {
        switch(GMState)
        {
            case GameManagerState.Opening:
                break;
            case GameManagerState.Gameplay:
                break;
            case GameManagerState.GameOver:
                break;
        }
    }


    public void SetGameManagerState(GameManagerState state)
    {
        GMState = state;
        UpdateGameManagerState ();
    }
}

im getting an error on GameManager.GetComponent<GameManager>().SetGameManagerState(GameManager.GameManagerState.GameOver); at the first block of code. why is that happening ? couldnt solve the problem
CS1061 it says "gameobject" does not contain a "GameManagerState" definition, and no accessible "GameManagerState" extension method was found that accepts a first argument of Type "GameObject". (maybe you are missing a usage directive or assembly reference?)

tidal basin
#

Now, I am trying to make a fps character controller. I am using the new input system and the controls are so jittery. I look on google and changed the update mode to dynamic update and at the beginning (when i have only camera look script) it was fine. But when i add the movement script, it broke and begin jittery again (both movement and camera). Here is my simple movement code:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public InputManager inputManager; // Refence to our InputManager component
public CharacterController controller; // Reference to your CharacterController component

[SerializeField]
private float smoothInputSpeed = .2f;

public float playerSpeed;
private Vector2 currentInputVector;
private Vector2 smoothInputVelocity;
private void Update()
{
    Vector2 input = inputManager.inputMaster.Player.Move.ReadValue<Vector2>();
    currentInputVector = Vector2.SmoothDamp(currentInputVector, input, ref smoothInputVelocity, smoothInputSpeed);
    Quaternion characterRotation = transform.rotation;
    Vector3 move = characterRotation * new Vector3(currentInputVector.x, 0, currentInputVector.y);
    controller.Move(move * Time.deltaTime * playerSpeed);
}

}

wintry quarry
willow scroll
warm geode
vagrant zealot
vagrant zealot
willow scroll
#

Why not edit the original question?

wintry quarry
vagrant zealot
willow scroll
tidal basin
# wintry quarry It's more likely related to the code that moves your camera and or rotates your ...
    {
        float mouseX = inputManager.inputMaster.Player.MouseX.ReadValue<float>() * sensitivity * Time.deltaTime;
        float mouseY = inputManager.inputMaster.Player.MouseY.ReadValue<float>() * sensitivity * Time.deltaTime;

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

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }```
Can you take a look at it?
wintry quarry
#

that's a classic mistake

vagrant zealot
wintry quarry
#

(make sure to adjust your sensitivity down as well to compensate)

willow scroll
tidal basin
tidal basin
#

But now its so, so fast

willow scroll
wintry quarry
wintry quarry
#

no no they were just talking about the code

#

it's not important

tidal basin
wintry quarry
#

revert what???

tidal basin
wintry quarry
#

what did you have before?

#

pass through?

tidal basin
wintry quarry
#

I would have expected that you had it as a Vector2 before 😬

#

well wait

#

I mean

#

I guess it can work either way

wintry quarry
#

you can do this then:

Vector2 mouseInput = inputMaster.Player.Mouse.ReadValue<Vector2>();```
#

and get mouseInput.y and mouseInput.x

tidal basin
tidal basin
willow scroll
#

That's the basics

#

Vector2 is a struct, which has x and y variables

willow scroll
#

This is how you access them

tidal basin
tidal basin
wintry quarry
#

we use the thing that we have

tidal basin
cinder crag
#

How can I get a game object from a different scene? Like I have the player and I have the main menu and have save and load system game object in both scenes which have the Save and load system script which has a public game object player parent which I just drag and drop the player but in the main menu I don't have the player ofc so I'm not sure how can I grab the player from the other scene

willow scroll
cinder crag
tidal basin
willow scroll
cinder crag
rich adder
cinder crag
rich adder
summer stump
#

Are both your scenes loaded at the same time?

cinder crag
cinder crag
lost anvil
#

having an issue with spine IK where im trying to get the torso/spine bone of the character to face towards the target in a somewhat realistic manner, and i cant find any good guides on spine IK anywhere

https://gdl.space/uradaquton.cs - (the first bit is just head ik)

ivory bobcat
summer stump
cinder crag
summer stump
ivory bobcat
summer stump
cinder crag
summer stump
#

Pretty sure we've talked about it before?

summer stump
rich adder
cinder crag
rich adder
#

you just kinda ignored it

ivory bobcat
lost anvil
coarse frost
#

is there a collider type that is best for a player character

ivory bobcat
willow scroll
lost anvil
#

ohh yeah i knew that was whats wrong with my script

#

thanks man

coarse frost
ivory bobcat
willow scroll
#

Even though, as I have previously mentioned, your character already looks amazing and their posture doesn't require any changes.

cinder crag
willow scroll
chrome tide
willow scroll
ivory bobcat
#

The save/load script is likely doing too much. The player from the next scene should instead be responsible for acquiring it's data from your loading script/manager rather than the script/manager trying to configure the player object from the next scene before it's loaded - assuming that's the reason why a reference of the player is needed.

chrome tide
summer stump
cinder crag
acoustic arch
#

how can i make scriptable objects with custom method or ability for each? can i make an interface abstract and edit the code somehow of an object?

summer stump
eternal needle
acoustic arch
tired junco
#

hey! is there a way to play an animation reversed like set the speed to -1 via code?

eternal needle
acoustic arch
#

will it begin to overly fill my create asset menu by doing so?

eternal needle
verbal dome
#

With a "/"

lost anvil
verbal dome
verbal dome
#

@lost anvil Oh you are setting the bone's local rotation, I suppose that's the issue? Since you are calculating the direction in world space, not local

#

Could you just set its world rotation (transform.rotation) instead? I never used OnAnimatorIK, just LateUpdate, so I dont know

cinder crag
# summer stump Well I don't know. You haven't been super clear on what you need. You mentioned ...

https://paste.ofcode.org/35KkmSuca6kgapMBBBZrnzg (SaveAndLoadSystem script) not sure if im doing too much , it might be and i dont realize it, the playerParent is simply so i can drag and drop the player gameobject with has all the components i need like inventory and playerstats , the problem is , i dont have that said player gameobject in the main menu obv so when i want to press the continue button which loads the saved data it well doesnt work cause it cant find the player gameobject in the main menu scene when i press the continue button so ofc it doesnt load so i dont know how i can load the needed player data like current ammo or currentlyEquippedWeapon etc and gives me an error so im not sure how i can do it ngl.

verbal dome
lost anvil
#

like the way i want

verbal dome
#

Yeah you can rotate bones in LateUpdate since it runs after animations

lost anvil
#

👍 ill try that

summer stump
#

Considering you only need to LOAD from the main menu, not save

cinder crag
summer stump
cinder crag
#

i have it but how can i use it now? if i jsut wanna load the data (this is in the main menu manager script)

summer stump
#

You probably want your Load() method to actually RETURN the savedata struct. As it is, you load it and then throw it away without caching it

cinder crag
summer stump
queen adder
#

I am trying to change the hue from 0 to 360, but it doesn't go through the other colors. What I'm doing wrong? I also want it to go cyclically.

private float time = 0.0f;

void Update()
{
  time += Time.deltaTime;
  material.color = Color.Lerp(
    Color.HSVToRGB(0.0f, 1.0f, 1.0f),
    Color.HSVToRGB(1.0f, 1.0f, 1.0f),
    time
  );
}
wintry quarry
#

as for making it cyclical you can just do:

  time += Time.deltaTime;
  time %= 1;
  material.color = Color.Lerp(
    Color.HSVToRGB(0.0f, 1.0f, 1.0f),
    Color.HSVToRGB(1.0f, 1.0f, 1.0f),
    time
  );```
queen adder
#

The color stays being red instead of it going through orange, yellow, green etc.

wintry quarry
#

where did you get material from?

#

Do you have any errors in console?

queen adder
#
void Start()
{
    MeshRenderer renderer = GetComponent<MeshRenderer>();
    material = renderer.materials[0];
}
wintry quarry
#

you could just do material = renderer.material;

#

no need for the array

#

but yeah do you have any errors in your console?

cinder crag
summer stump
#

And return it

queen adder
wintry quarry
#

0 and 1 are the same hue actually

cinder crag
wintry quarry
#

so maybe try this:

time += Time.deltaTime;
time %= 1;
material.color = Color.HSVtoRGB(time, 1, 1);``` @queen adder
#

because if you do the color lerping like that it's going to think it's lerping from Pure Red to Pure Red
In RGB it thinks it's lerping from (255, 0, 0) to (255, 0, 0) which won't do anything of course

hollow dawn
#

how do I add animations to my player? like when I run I want a running animation. I got one from mixamo but dont know how

hollow dawn
cinder crag
cinder crag
#

okay so i got a small problem since im using playerParent to find the components i need like inventory n such and i set the playerParent to private , i tried many times to reference itbut i failed miserably

wintry quarry
polar acorn
cinder crag
timber tide
#

I prefer to GetComponent if I am using requiredcomponent attribute

#

oh but for parent stuff yeah, just assign it imo

cinder crag
# summer stump Yep

did all of that and it still uh doesnt work , gives me the errors in the vid when pressing the continue button

summer stump
#

What errors

polar acorn
summer stump
#

Also, having the savedata in the ddol singleton doesn't help if you don't actually pull that data and update the player with it

cinder crag
cinder crag
#

sorry

summer stump
cinder crag
#

getthe reference like this?

deft grail
#

so why would that work

summer stump
polar acorn
#

since that happens at end of frame

summer stump
#

It's just some struct sitting there

cinder crag
cinder crag
summer stump
cinder crag
acoustic arch
#

with the CreateAssetMenu can i organize all of the assets into a folder/dropdown of some sort

#

so it doesn't fill my create menu with a load of objects

deft grail
acoustic arch
#

can you give me an example

deft grail
#

menuName its called

acoustic arch
#

oh wait wha

deft grail
#

[CreateAssetMenu("New Gun", "Gun/New Gun")] something like that i think?

#

try it and see

acoustic arch
#

does not contain a constructor that takes 2 args

deft grail
acoustic arch
#

nvm

summer stump
#

@cinder crag It's super basic. Say savedata has an ammunition count.
player.AmmoCount = SaveData.AmmoCount

#

It's dot notation and an equals sign

#

I REALLY recommend a basic c# course

acoustic arch
deft grail
#

do you see any red at all

cinder crag
ivory bobcat
# cinder crag how can i pull it and update the player?

That would be a design question of when you should do it but relative to just acquiring the data, you'd have a script on the player in the new scene that would just load the necessary data from the save manager in Start or something. For example, if you're wanting to Update/load the player's position:cs private void Start() { transform.position = SaveData.Instance.playerPosition; }

cinder crag
summer stump
#

First, you need to be doing all that code on a component on the player!

#

Then, you are pulling FROM savedata, not setting its values

cinder crag
#

thats all i needed honestly

cinder crag
summer stump
#

That is fine

cinder crag
summer stump
#

I don't like all the getcomponents, but that is whatever

#

If it works it works

cinder crag
cinder crag
#

sinc ethats where the rest of the components are

summer stump
#

But that is taste

#

It is fine

cinder crag
#

is it better or ?

#

just a pref?

summer stump
cinder crag
summer stump
#

Also, why not transform.position = saveData.playerPos

cinder crag
#

oops im dumb , mb mb

cinder crag
# summer stump Yes, better

for some reason these errors appear when i saved and tried to laod in when pressing the continue button in main menu

summer stump
cinder crag
summer stump
#

Those scripts on that line have some reference you are trying to access, and the reference is not set

cinder crag
summer stump
cinder crag
#

since its in another scene

rocky canyon
#

well that wont work

summer stump
cinder crag
#

can try this

summer stump
#

I thought you said it was in a different scene

cinder crag
summer stump
cinder crag
cinder crag
autumn tusk
#

i'm kinda confused

summer stump
autumn tusk
#

basically i want to change the sprite for an tmp image but im not sure what function i need to use to set the source image

cosmic dagger
autumn tusk
#

tried setsprite

cinder crag
autumn tusk
#

doesnt work with an tmp image

summer stump
cinder crag
cosmic dagger
summer stump
burnt mantle
summer stump
autumn tusk
#

hold up

#

i think im getting mixed up

summer stump
#

But I appreciate it

autumn tusk
#

its a ui image, not a tmp image

summer stump
#

I sent you that link like three times

cinder crag
#

oops

#

mbmb

#

needed to put it in start or awake method

#

iirc

autumn tusk
#

ok nvm im stupid, .sprite just works

summer stump
#

Don't NEED to, but that is the best place to. And you don't want to call the function over and over

autumn tusk
#

specifed the wrong variable as well

cosmic dagger
#

yep . . .

cinder crag
cinder crag
burnt mantle
summer stump
dusky pike
#

Hey guys i have a really random problem.

Im generating an Object with an Script. Im attaching a Mesh Collider onto it (with a script).

The Objects Mesh Collider doesnt work tho. But if im enabling convex is does. The problem is it doesnt work if i enable Convex by default. Changing the State (or interacting with options of the default filter) enable it

cinder crag
#

Do I put the DontDestroyOnLoad in the save and load system script?

burnt mantle
summer stump
#

What is line 24 of MainMenuManager

burnt mantle
summer stump
#

Things seem really convoluted going back and forth with references

summer stump
summer stump
cinder crag
burnt mantle
burnt mantle
burnt mantle
cinder crag
deft grail
# cinder crag

this is just where you declare it, have you not learned anything from yesterday?

cinder crag
#

mb , im tired its almsot 3 am

summer stump
#

This seems like the exact same issue as yesterday. Declaration vs actually setting the reference

summer stump
cinder crag
#

dont wanna stop until i fix the problem doe

deft grail
summer stump
#

Don't waste your time and ours by coding by approximation without fully even getting it

cinder crag
deft grail
#

this is one of the first things you learn

burnt mantle
cinder crag
burnt mantle
cinder crag
barren violet
#

This convo brings up a question I have that may have a simple answer.

Initializing properties in code vs in the inspector.

At first glance it seems ambiguous, as in its user preference. But what is the standardized answer? I don’t recall the junior programming pathway addressing this.

frosty hound
#

Whatever is easier and your preference is the standard.

#

That is to say, it really doesn't matter.

#

Just that if you do it in code, do it in Awake.

timber tide
#

it matters when unity decides to dereference your editor values :(

#

usually if it's supposed to be part of the same GO, i'd just use require component attribute with GetComponent

#

otherwise reference by editor

barren violet
#

@frosty hound @timber tide gotchya, thanks guys.

barren violet
timber tide
#

gameobject

barren violet
#

Ah, Duh 😂

timber tide
#

useful attribute

barren violet
#

Cool, RequireComponent is a new one for me.

nimble aurora
#

I grabbed this folder for Twitch Integration, it's got its own folder in the Assets folder, I haven't added it to my project's hierarchy proper. The scripts seem to just run on their own, which doesn't quite make sense to me since I thought I'd need them in the project proper, as a part of a gameObject, in order for them to do that. If I want to start my game w/o the scripts in this project enabled, how do I do that when it's not even in the hierarchy, yet seems to be getting run anyway?

river glade
#

Hi everyone, sorry, I came across this problem, when the enemy opens the doors, he often gets stuck in a corner like this, he keeps walking towards the wall/door, how could I overcome this problem?

timber tide
#

make em half ghost so they can phase through the door and add that to the lore to disguise the real reasoning

#

more serious answer, fix the pathfinding obviously, or make the doors always open inward

#

make it a obstacle, recalculate the destination, ect

river glade
#

the idea is not masculine hahaha It remains the same if the doors are on the inside, it will still get stuck in the corners

summer stump
#

Or just make the door an actual obstacle.

river glade
#

the structure is made of many anoles, it would still remain blocked
I try to make the door itself an obstacle, even if it would then cause problems to enter other rooms, since it would not calculate the pathfind from one room to another with an obstacle in the middle

summer stump
#

Or make doors not obstacles, and only make them obstacles when opened

river glade
harsh wraith
#

For my game I am trying to create a main menu. The main menu is simple and just has a play button. When the play button is pressed the screen is supposed to fade to black. The way the fade works is that there is a black screen image that is transparent within a camera render mode canvas. When the button is pressed the script slowly adds to the A value of the RGBA to that it decreases it's transparency. For some reason this isn't happening and my cursor isn't being highlighted when I'm hovering over the button as well. How would I fix these issues. Also here is the script for the button.
https://gdl.space/axucesoquv.cs

frigid sequoia
#

Can I call a method as an animation event and pass a parameter to it?

frigid sequoia
#

So.... yes it does, I would had swear that I tried before and didn't let me pass anything

rocky gale
#

https://hastebin.com/share/akuzaseziq.csharp how come after a few times of the player throwing the katana consecutively the next time they throw it will throw for like half a second and immediately return back

rocky canyon
#

you need to reset the returnForce

#

the returnForce variable is getting excessively high after each throw

#

returnForce += Time.deltaTime * 5; this keeps getting bigger and bigger.. each time u use it

#

you could just use = Time.deltaTime * 5;

#

not sure why you use += edit: if you want to use the += to simulate some kind of increase.. you still should reset the variable before each time you use it

rancid tinsel
#

what does this mean?

#

wait nvm

#

im an idiot

#

im meant to set the clip lol

onyx tusk
rocky canyon
#

thats what the method is expecting

#

ya, ulong is a 64bit integer

rancid tinsel
#

there we go

rocky canyon
#

👍 hoorah!

rocky canyon
# rancid tinsel

PlayOneShot(music); is an alternative to assigning the clip and then playing

#

2 lines becomes 1 line

rancid tinsel
#

btw im kinda worried about adding sfxs to my game

static cedar
#

Also i think Play has a limitation of not being able to play multiple things but someone should confirm this. UnityChanThink

rancid tinsel
#

im not sure how it will work since (tower defence game) the towers can scale attack speed infinitely, and there will be multiple at once - how will that work with one audio source?

#

would it play multiple at once

#

or would it overwrite it

#

ive never done sound before

rocky canyon
#

OneShot will play like 3 clips at once i believe..

#

i normally just stop it..

#

src.Stop();
src.PlayOneShot();

static cedar
onyx tusk
rocky canyon
#

32*

#

it can play 32 clips at once

rancid tinsel
rocky canyon
#

id just Stop(); and then Play();

rancid tinsel
#

i should probably somehow figure out a way to scale the sound effects length with attack speed tho?

charred spoke
#

It’s limited by the number of real and virtual voices. PlayOneShot essentially copies the audio source under the hood and plays the clip on the new source. If used many times in a frame there are performance considerations in using it.

onyx tusk
rancid tinsel
#

what happens if you exceed the 32 number? will it just start overwriting the previous one? as in stop the last one in the "queue" and play the new one?

still forum
#

Hey so this is my code provided "https://gdl.space/raw/keyunogune"
Descrp: Me and my partner tried fixing the issues with just errors for the past hour and how to add the navmesh surface component which I finally figured out. Partner left me to finish the project due tomorrow which is no problem. The issue I am currently having is the enemy is moving in a straight line ,slowly spinning, but not following me. I was hoping to find a solution to this with some help. Some troubleshooting I tried doing was increasing the obstacle radius , checking if any obstacles were blocking , did speed and acceleration but to no avail.I also did make sure to bake within the navmesh surface .
Currently no error messages.

rancid tinsel
#

SoundManager.Instance.PlaySFX(soundEffect) basically

onyx tusk
rancid tinsel
rocky canyon
#

AudioManagers are a common use-case for Singletons

rancid tinsel
#

i think your method would be fine or maybe even better

#

but it would take a lot more time i feel like

#

also fixing potential bugs would be annoying

charred spoke
rancid tinsel
charred spoke
#

Audio source has a priority setting by default its the same on all

rocky canyon
rancid tinsel
charred spoke
#

So no, if you exceed the 32 limit a new sound will not play since it will not have a higher priority

rancid tinsel
#

i see

#

but it shouldnt break anything in that case?

rocky canyon
#

if ur playing more than 32 audio sources at a time imma uninstall the game anyway..

#

thats stimulus overload 🤣

charred spoke
rancid tinsel
#

as in, it would wait for the slot to free up and if its empty then play it?

rancid tinsel
#

else if not empty, not play

charred spoke
#

It will go into the void never to be seen again

rancid tinsel
#

im not going to go crazy with the sound effects

#

im just hoping the scaling nature of my game doesnt affect it too much

rancid tinsel
rocky canyon
#

not unless u have logic running to queue it up

charred spoke
#

Yes

rocky canyon
#

ah, i thought he meant one he called previously when the 32 was full

charred spoke
#

By wants to play if you mean that you called Play somewhere in code then yes

#

There is no built in queue

#

The 32 limit can be changed from the settings

rocky canyon
#

i just use an audiomanager.. if theres not enough sources it creates one.. plays the sound and then destroys itself..

#

i haven't implemented pooling yet.. but its on my To-do list

#

i think i might give Unity's pooling system a try too

#

i haven't used it yet.. and its been something ive been wondering about

charred spoke
#

So the way our sound system works is we have sound banks. Each sfx in a bank has it’s own audio source settings. When it’s time to play a sound the system grabs a source from a pool, applies the settings, places the source in the world(if it is spatialized) and plays it.

rancid tinsel
charred spoke
#

It also handles environmental sources by stopping them when they are far away from the player.

rancid tinsel
#

i dont even necessarily need to do it, but its like the last thing on my to-do list

rocky canyon
charred spoke
#

It’s a bit more complicated than that since it also has an internal queue but that is the gist of it

rancid tinsel
#

im running into a bug because of a bit i changed just now

#

this bit always results in the if being true despite being on the other scene

rocky canyon
#

which bit now?

rancid tinsel
#

if (main menu) bit

#

and when i go back to the main menu it says its on the other scene

#

maybe its to do with when the method is called

#

let me double check

rocky canyon
#

possibly..

#

scene management will run into issues like that

onyx tusk
#

I have code, that applies on all of the text & all of the objects on the desk```c#
figure.transform.localScale = new Vector3(size, size, size);
text.transform.SetParent(figure.transform);
text.transform.localPosition = new Vector3(0, size / 2, 0);

rancid tinsel
#

i love game dev

#

fixed the bug

#

still dont know what the issue was

rocky canyon
#

heck ya

full wave
#

how do i apply a force to a gameobject at an angle?

rocky canyon
#

AddForce for example uses a Vector3 for the force.. force is applied along the direction of the Vector..

#

so you'd calculate the direction of ur angle and use that..

rancid tinsel
#

im so happy old me was lazy enough to make separate scripts for different projectiles

rocky canyon
#

trigonometry has entered the chat

rancid tinsel
#

now I just had to add one line for the sound effects to each one lol

rocky canyon
#

something like this ```cs
public float angleInDegrees = 90f; // starting angle in degrees

    float angleInRadians = angleInDegrees * Mathf.Deg2Rad; // convert angle to radians
    Vector3 forceDirection = new Vector3(Mathf.Cos(angleInRadians), Mathf.Sin(angleInRadians), 0f); //calculate the direction using some trig
    rb.AddForce(forceDirection * forceMagnitude, ForceMode.Impulse);```
#

if the object has a initial rotation already you might wanna run it thru TransformDirection to get the proper direction

#

Vector3 forceDirection = transform.TransformDirection(new Vector3(Mathf.Cos(angleInRadians), Mathf.Sin(angleInRadians), 0f));

#

since I'm actually not good with trigonometry and the whole sin/cos stuff i actually took some snippets from the unity forums.. google search led me there lol

warm geode
#

someone pls help ive been trying to fix this problem for hours now, im trying to crouch but im not able to uncrouch

#

imma send code now

#

i would really appreciate if anyone could help

#

im using a coroutine to transition my camera up and down when im crouching and swithching colliders at the same time, when i play the game, crouching is working but uncrouching is not working

#

i also cant move either after i implemented this

teal hemlock
#

hey i hope this thing is related to coding but after i created the backbutton C# script i wanted to insert it to the game object so i can insert it to the button but for some reason i get this error any idea ?

warm geode
#

it says the script should derive from monobehaviour

#

why do you want to insert to a game object

#

you add the script to the canvas

#

i think you can only add a script to a gameobject if it is derived from monobehviour

static cedar
#

Yes.
Classes need to inherit mono behaviour to be used as a component.

#

This is beginner stuff, you should look for more tutorials first. UnityChanThink
Especially C# programming that you won't learn in unity tutorials but used everywhere.

languid spire
warm geode
#

i changed that

#

sorry wait

#
while (Mathf.Abs(heightDiff) > 0.01f)
{
    heightDiff = targetHeight - currentHeight;
    elapsedTime += Time.deltaTime;
    float lerpValue = Mathf.Lerp(0.0f, 1.0f, elapsedTime * crouchSpeed);
    cameraTransform.localPosition = new Vector3(cameraTransform.localPosition.x, currentHeight + (lerpValue * heightDiff), cameraTransform.localPosition.z);
    yield return null;
#

you think it is okay now

#

but it still doesnt work

languid spire
#

of course not, that makes no difference whatsoever

warm geode
#

what else do you think i could do

#

for context i want to move the camera up and down when the player crouches

languid spire
#

recalculate currentHeight might be favourite

teal hemlock
languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

warm geode
warm geode
teal hemlock
languid spire
warm geode
#

because current height keeps changing everytime the code runs because of lerp the camera transform and height diff would become zero at some point

languid spire
#

no it does not

#

current height is a value type not a reference

#

it is set once and only once

warm geode
#

how can i fix this

#

how can i pass by reference in c#

languid spire
#

you dont need to

heightDiff = targetHeight - cameraTransform.localPosition.y;

now it is using the correct value which changes

warm geode
#

oh ok i will try now, thanks a lot for your help

languid spire
#

had you bothered to add a few Debug.Log statements you would have seen this yourself a long time ago

warm geode
#

oh now i also realized what you mean

#

and it still wont work

#

i dont know wtf is even wrong

languid spire
#

Debug your values and find out

warm geode
#

there is also no tutorials anywhere for adding crouching like this

#

sure i will try to use debug log more and find out

#

thanks for helping

warm geode
#

i just understood that what im doing doesnt even make any sense

#

because the currentHeight variable keeps changing even when i jump

#

making realistic crouching isnt easy

rocky canyon
#

u can use local positions

teal hemlock
languid spire
teal hemlock
#

or must be different versions

languid spire
still forum
teal hemlock
#

im just in a hurry because my college project AR app needs to be done by the next week

still forum
#

its weird , i just need it to face me and shoot, i tried rotating it to follow but no avail

teal hemlock
#

and i don't know what to exactly focus on since there's UI and coding and 3D and audio to set up

#

there's many buttons too

loud mango
#

animation channel dead ;-;

burnt vapor
lean bear
#

error when trying to add Firebase to Unity 2D. Can someone help solve this problem?
InitializationException: Firebase app creation failed.
Firebase.FirebaseApp.CreateAndTrack (Firebase.FirebaseApp+CreateDelegate createDelegate, Firebase.FirebaseApp existingProxy) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/app/swig/Firebase.App_fixed.cs:2628)
Firebase.FirebaseApp.Create () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/app/swig/Firebase.App_fixed.cs:2128)
Firebase.FirebaseApp.get_DefaultInstance () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/app/swig/Firebase.App_fixed.cs:2103)
Firebase.Auth.FirebaseAuth.get_DefaultInstance () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/auth/swig/Firebase.Auth_fixed.cs:4100)
AuthManager.InitializeFirebase () (at Assets/Login Scene/Scripts/AuthManager.cs:101)
AuthManager+<CheckAndFixDependencies>d__19.MoveNext () (at Assets/Login Scene/Scripts/AuthManager.cs:55)

languid spire
lean bear
languid spire
#

I'm not sure if the Xeon is even supported

lean bear
languid spire
neon ivy
#

trying to remap floats but I see that Mathf.InverseLerp is clamped 0-1, and there's no unclamped version of inverse lerp like there is for lerp. anyone got a better way of remapping?
this is my function rn:

public static float RemapFloat(float value ,float initialMin, float initialMax, float targetMin, float targetMax)
{
    float t = Mathf.InverseLerp(initialMin, initialMax, value);
    return Mathf.LerpUnclamped(targetMin, targetMax, t);
}
gray elk
#

I am working with game managers using start/game/end screens to function in a triangle by pressing buttons. These were working, but now the start screen doesn't show up at all and the button doesn't work and I'm not quite sure on why. Everything looks correct? Very confused.

deft grail
gray elk
#

Yes

deft grail
# gray elk Yes

put a debug.log into the LoadGameScene at the beginning to check if it runs

gray elk
#

So it's still sensing input but not changing scenes for some reason

deft grail
gray elk
#

`public void LoadStartScene() // Game START
{
SceneManager.LoadScene(0);
}

public void LoadGameScene() // Game GAME
{
    SceneManager.LoadScene(1);
    Debug.Log("Test");
}

public void LoadEndScene() // Game END
{
    SceneManager.LoadScene(2);
}`
deft grail
gray elk
languid spire
languid spire
#

So your indexes are wrong

gray elk
#

oh huh thats weird
i think start is supposed to be 0
maybe thats what is causing it?

#

how do i fix that

deft grail
#

move it

gray elk
#

ahhhh that fixed it! Thanks so much!! UnityChanCheer

onyx tusk
#

I have code, that applies on all of the text & all of the objects on the desk```c#
figure.transform.localScale = new Vector3(size, size, size);
text.transform.SetParent(figure.transform);
text.transform.localPosition = new Vector3(0, size / 2, 0);

I expect, what i will have texture conflict named overlay, but i have this. Please, feel free to ask stupid questions like "is the size int?"(it's float), because i can make a mistake even in so simple things
modest dust
#

Just because scale is size doesn't mean the actual model size is size

#

If the size is indeed <= size then placing the text slightly higher should be enough

languid spire
#

Good point, you should use the bounds from the renderer of the figure to calculate the local position of the text

neon ivy
#

ok I made my remap unclamped using math but now it can't handle inverse ranges.
like if I do RemapFloat(x,0,10,1,0) it breaks because 1-0 isn't a valid range.
is there a way to fix this?

public static float RemapFloat(float value ,float initialMin, float initialMax, float targetMin, float targetMax)
{
    float output = targetMin + (targetMax - initialMin) * ((value - initialMin) / (initialMax - initialMin));
    if(float.IsNaN(output) || float.IsInfinity(output))
    {
        Debug.LogWarning("remap failed, output is infinity or NaN");
    }
    return output;
}
languid spire
#

your logic is incorrect. It should be
value = x as a normalized percentage of initialMax-initialMin
result = Lerp of targetMin, targetMax, value

neon ivy
#

I copied this from processing source code

languid spire
#

use inverse Lerp and Lerp, job done

neon ivy
#

that had the issue of being clamped

verbal dome
#

@languid spire I thought that too but inverselerp is clamped (and so is Lerp, but there is LerpUnclamped)

#

Could make your own InverseLerpUnclamped though

languid spire
#

ok, then my solution

neon ivy
languid spire
#

if you cannot do it in your head

neon ivy
#

no I mean like, how does inverse lerp even work

lime mural
verbal dome
#

Yeah that

neon ivy
#

oh

verbal dome
#

First result with 'inverse lerp' google

neon ivy
#

guess I was making it too difficult

lime mural
#

should have just used "inverse lerp formula"

neon ivy
#

googling is an art, and sometimes I suck at art UnityChanOops

languid spire
languid spire
lean bear
#

can anyone add Firebase to Android Unity 2D? and give me control?

onyx tusk
amber basin
#

https://paste.ofcode.org/5VeBAPKQVhvmYQLjGcdfhU
https://paste.ofcode.org/drhxYQ2ZXRvyZEBxBDAjvx
https://paste.ofcode.org/5D4Sgkum4GfenskMauTnQu
https://paste.ofcode.org/axPsbAazd98cGNa4gNZJyj
I have a tower defence game that i am trying to make but for some reason my retry button inside my Pause menu and my Game over scene dont reload the level Properly. Enemies dont spawn in, my timer for the next wave is stuck and the scene itself just doesnt wanna load in properly. The only time the scene actually loads in properly is when i pause the game before the timer reaches 0 and the enemies spawn in. That is when the scene will reload and it will go back to the point where it counts down until enemies spawn.

Same with when i go to the main menu from the Pause screen. When i go to main menu with the click of the button i made, it takes me to the main menu. I then go to level select, then i go to the level i was in and the same thing happns. If enemies spawn, the level cant reload properly after i go to menu and then back to level. If the timer hasnt reached 0 yet and no enemies spawn, going from Pause menu, to main menu, to level again is suddenly fine? I am not really sure why that happens and could really use some help on this. Hope i explained things well enough here? ^^'

summer shard
#
public IEnumerator ChangeCameraPosition(Transform cameraTransform, float lerpTime, bool lockAfterLerp) {
    canInteract = false;
    canLook = false;
    canMove = false;
    float t = 0f;
    Transform startingTransform = _camera.transform;
    while (t < lerpTime) {
        _camera.transform.position =
            Vector3.Lerp(startingTransform.position, cameraTransform.position,  t / lerpTime);
        _camera.transform.rotation =
            Quaternion.Lerp(startingTransform.rotation, cameraTransform.rotation, t / lerpTime);
        t += Time.deltaTime;
        
        yield return null;
    }
    
    _camera.transform.position = cameraTransform.position;
    _camera.transform.rotation = cameraTransform.rotation;

    if (!lockAfterLerp) {
        canInteract = true; //This 3 lines in this if
        canLook = true;
        canMove = true;
    };
    
    yield return null;
}
``` why does it take so long to run those 3 lines, it looks like the lerp is finished but it takes like one second to run those lines
hollow dawn
#

when I click on configure nothing happens how can I fix this?

green ether
#

lerpTime

#

no?

summer shard
#

i'll record a vid

green ether
#

I dont see any mistakes in the code, you could debug it to see if it actually takes longer but it should be pretty much exactly the lerpTime

icy bramble
#

Does anybody know what kind of coding I have to to implement a pikmin like script?

autumn tusk
#

unity is acting up again

#

im working on a pause button systemm

#

and for some reason it functions perfectly in my main game scene but in every other scene it doesnt work

green ether
#

well theres probably something different in those other scenes then

#

just gotta figure out what it is

night raptor
#

if not that, there's definitely still something different between the scenes as pointed out

autumn tusk
#

yep turns out i was missing an event system in the second scene

#

added it to the player

night raptor
#

player?

#

may not matter but usually you want the event system to be an own gameObject. otherwise you may disable or remove it by accident

summer shard
fringe plover
#

Im so tired, i tried to make screenshot taking in game (at game over), but image is always based on screen size (texture.ReadPixels) and of i dunno how to make in 1080x1920 like it supposed to be

autumn tusk
night raptor
silk night
molten dock
fringe plover
cosmic quail
summer shard
green ether
#

as I said, you should debug and check what the actual time taken is

#

Or at least debug.Log(lerpTime)

#

To make sure you call it only once with the correct time

warm geode
#

does anyone know a simple way to make your character not jump while crouching, i mean you should not be able to jump if u press space while crouching

#
if (Input.GetKey(crouchKey))
{
    state = MovementState.CrouchState;
    moveSpeed = crouchSpeed;
}
#

what can i add in here

#

there is a function call jump() and a variable called isJumping

#

and keycode called jumpkey

green ether
#

in Jump()

#

you could do

#

if (crouching)
Dont jump/ return

warm geode
#

oh wait

#

yeah im so dumb

#

i didnt think of this

#

thanks very much

#

i finally finished my character controller

nimble wigeon
#

That’s the code making my goblin move and follow player

#

Hey guys so I’m working on a 2d platformer game and I’ve added a goblin as my enemy but for some reason he’s floating and doing weird stuff

green ether
#

!code

eternal falconBOT
nimble wigeon
#

ok let me try that

#

Sry didn’t know

green ether
#

no worries, its just hard to read

silk night
warm geode
#

free character controller that anyone can use 🙂

nimble wigeon
warm geode
#

dont screen shot

#

just copy paste it?

#

for the code part

nimble wigeon
#

Cant access discord on schools computer

#

Once I paste code on hate bin how do I share link?

silk night
#

just post it here

nimble wigeon
#

yea I don’t think it worked lol

warm geode
#

dont use hate bin

#

use gdl space

#

the only i pasted above

nimble wigeon
warm geode
#

yeah

#

u can use pascal case for public variables @nimble wigeon

#

use public RigidBody, private rigidBody

nimble wigeon
#

So instead of doing serialize field I just do public Rigidbody rb;?

warm geode
#

no use serialize field, i meant for public variables use pascal case where all words start capital, rn u are using camel case for everything which first words start with small and rest start with caps

nimble wigeon
#

Oh is pascal better?

#

I just do that because in my CSA class they told us to always use camel case

warm geode
#

no it is used to distinguish between private and public variables

nimble wigeon
#

Ok ty

#

But do u see anything wrong with the code? I’ll see if I can see video of what is wrong with my enemy

warm geode
#

where do you have this script attached

nimble wigeon
#

It’s attached too the goblin

#

He’s floating and when he crashes into my player he pushes the whole background and tilemap

warm geode
#

the flip variable is never used

#

does character flipping work properly

green ether
#

its a bit messy

#
if(health <= 0)
        {
            goblinAnim.SetBool("isDead", true);
            Destroy(gameObject);
        }
#

why does this need to be checked every frame?
Why is it not at the end of TakeDamage()

warm geode
#
private void Flip()
    {
        Vector3 scale = transform.localScale;
        if (player.transform.position.x > transform.position.x)
        {
            scale.x = 1;
        }
        else
        {
            scale.x = -1;
        }
    }
#

i think this will work

#

your script is very incomplete you also never used the take damage function anywhere

#

but i think u can also put that code in the end of take damage

undone rampart
#

why not just send the screenshot you made on pc

rigid valve
deft grail
rigid valve
#

whats that error?

polar acorn
slender nymph
# rigid valve
  1. use TryGetComponent instead of two separate GetComponent calls
  2. do you have a component called InteractableObject
rigid valve
#

#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We will start with basic FPS movement, inventory building, and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival open-world...

▶ Play video
charred spoke
#

Oh boy is the counter about to go up?

deft grail
frosty hound
#

Are you starting from Part 3 of a tutorial series?

rigid valve
#

no

#

from 1

slender nymph
#

you haven't answered my question yet, do you have a component called InteractableObject

rigid valve
#

idk I am following a tutorial 🥺

slender nymph
#

try paying attention to it then?

deft grail
polar acorn
deft grail
#

!code

eternal falconBOT
rigid valve
#

thats what I am coufsed ab there is not such thing

#

but he used it in code

deft grail
rigid valve
#

no ?

deft grail
#

yes

rigid valve
#

ohh that script I have that as well its basic for naming tress and diff stuff in evironment

slender nymph
#

lmao the video covers it after writing that code apparently

rigid valve
#

InteractableObject

slender nymph
#

so just keep watching the video i guess

#

what a terribly structured tutorial series

polar acorn
#

This is not a tutorial you should be following. This is a tutorial for people who already know the engine and need to see the concepts put together into a large project

#

This is more about the workflow and project structure. This is not something you follow verbatim.

#

Still, they do have the script in the tutorial and you don't so it counts.

"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 159
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-4-30
rigid valve
#

do u know a better tutotrial?

polar acorn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

deft grail
#

what does that even mean, also like i already said !code

eternal falconBOT
deft grail
#

you know what whatever thats fine, no where in the message it said use a screenshot but its OK, its fine for me

#

whats the problem with the code?

rich adder
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

tranquil hollow
#

let me fix that

slender nymph
eternal falconBOT
hollow dawn
#

my player is floating and when i play the game i cant jump because the player is floating i tried moving it down but it goes back up how do i fix this?

hollow dawn
rich adder
hollow dawn
rich adder
#

🪄 🔮

hollow dawn
# deft grail need to show the code

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

public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;

public float speed = 12f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;



Vector3 velocity;
bool isGrounded;

// Update is called once per frame
void Update()
{

    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

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


    }

    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x + transform.forward * z;

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

    if (Input.GetButtonDown("Jump") && isGrounded)
    {


        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }


    velocity.y += gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);



}

}

eternal falconBOT
rich adder
rocky canyon
#

why I guess you can't jump

  1. your inputs aren't being read / used correctly
  2. your conditional (isGrounded for example) is never true
  3. your forces are wrong/ inadequate
  4. other (missing layermask for example, see [2])
rich adder
#

this is like the worst way to use grounded

rocky canyon
#

lol.. is it? 😬

#

ive always used it w/o issue..

rich adder
#

yes , only works whilist the Move is called

rocky canyon
#

lol ¯_(ツ)_/¯

rich adder
#

its very finnicky

rocky canyon
#

ohh.. yea ive never not had my Move() function not running in update.. so i never noticed :S

rich adder
#

also only works when controller is exactly touching another collider and u cant filter out the layers

#

its a mess

rocky canyon
#

ahh, okay.. noted

rich adder
#

CheckSphere is pretty good, though personally would use OverlapNonalloc

rocky canyon
#

i guess my groundcheck is trash then 😛

#

i'll fix up a nicer one one day

rich adder
#

instead of return cc.isground just return OverLap returned colliders > 0

polar acorn
#

It works perfectly fine as long as:

  1. You are calling Move exactly once every Update
  2. You are properly applying gravity even when grounded
  3. You have no solid objects other than ground
slender nymph
rich adder
#

iirc even the unity third person character controller uses overlap instead

slender nymph
slender nymph
rich adder
rocky canyon
#

now that i think about it i do have a weird groundcheck issue here

#

was trying to make a mechanic when u land.. so ur head would bob.. so (rationally thinking)
i thought if i set a bool at the end of the frame.. and then check the controller's bool against it I would find out when i land..

#

ofc that didn't work.. but when i cached it at the beginning of the frame.. (before the conditional) it works as i suspected it to work the other way

#

intereesting.. thats all i know

hollow dawn
#

when ever i start the game why does my player spawn above the ground and when i stop the player goes back on the ground

rocky canyon
# rocky canyon

if i do it this way (the way it makes sense in my head) it doesnt work

rich adder
rocky canyon
#

ya its the skin variables..

#

makes the capsule hover slightly above the ground

crystal chasm
rocky canyon
#

oh yea ^ if thats ur player.. its just b/c the mesh's feet aren't at the bottom of the capsule

rich adder
rocky canyon
hollow dawn
#

not working

rocky canyon
#

well, if it has been moved down.. and its standing a bit off hte ground tahts the skin width

#

either lower it.. or start the game.. move the mesh down while its playing.. to get ur real Y offset.. and paste it back in after u stop

#

ur scale is weird too

#

should try to keep a Uniform scale on Root gameobjects, especially Rigidbodys and CharacterControllers

deft grail
# hollow dawn not working

what sort of programming is that? 16 different scripts for just having a speed value for the movement?

#

just put it in 1

rich adder
#

jesus

rocky canyon
#

its the Composition workflow guys

rich adder
#
{
//put stats
}```
rocky canyon
#

ScriptableObject

#

fight me bro 😄

deft grail
#

need
Walk Controller Settings Sprint Controller Settings Idle Controller Settings
all with different values, best ScriptableObject approach

#

having 1 is not good enough

rich adder
#

well you don't need it , but probably smarter to

rocky canyon
#

its a class i assume

rich adder
#

Oh i mean inside

rocky canyon
#

i actually have a struct version as well..

rich adder
#

this way they are easier to copy over for mutable data

rocky canyon
#

i was experimenting with different methods of storing the settings

#

still havent figured out whats best to use

crystal chasm
#

I like to encode all my settings into colors and save them as texture2d. XD

rocky canyon
#

lmfao 🤣

rich adder
#

im going to store all my stats in QR codes

rocky canyon
crystal chasm
#

It's a good idea whatever it is.

rocky canyon
#

and i've never wrote/read pixels before

#

good time to learn

rich adder
#

Vince McMahon says "There is no stupid idea"

hollow dawn
#

why is it still floating?? i dont understand

crystal chasm
#

You still aren't at the bottom of the collider.

#

Maybe use orto view when setting it

rocky canyon
#

its always going to float a little

#

just drop ur mesh down until it touches the ground..

summer stump
#

Also, the mesh is likely up a little

hollow dawn
summer stump
#

Moving it down will raise your mesh up

#

Because the CC is a collider

rocky canyon
#

just do this ^

#

adjust it during playtime.. copy the variable.. and paste it in

stuck palm
#

im trying to make a custom editor script. i want to put these two objects into this template prefab. however when the new prefab is created, it only does metarig. this is after debug logs are telling me there are two child objects and telling me their correct names. how can i fix this?

private void CreatePrefab()
    {
        GameObject newPrefab = Instantiate(prefab);
        GameObject newFBXObject = Instantiate(fbxObject);
        
        foreach (Transform child in newFBXObject.transform)
        {
            GameObject newChild = Instantiate(child.gameObject);
            newChild.transform.SetParent(newPrefab.transform, true);
        }
hollow dawn
rocky canyon
#

u should be dragging the mesh (graphics)

#

u dont drag ur player into the ground.. ofc that will pop back up.. b/c colliders dont like to be inside other colliders

#

im dragging the Mesh not my SpawnCampController <- CharacterController

#

if its popping back up theres something in ur code/animations thats positioning it automatically (if ur dragging the graphics like you should be doing.. and not an actual collider)

summer stump
hollow dawn
#

yes

rocky canyon
#

u telling me this guy pops back up from the ground?

hollow dawn
#

yh

#

when i try to drag him down he pops back up

chrome tide
#

is it better to calculate camera physics in FixedUpdate(), or multiply X and Y values by Time.DeltaTime ?

rich adder
#

only way that would happen if yu have script/animation moving it back up

rocky canyon
#

then ur animations ^ must be doing it..

chrome tide
hollow dawn
rocky canyon
#

you can create an empty parent.. around the mesh and move it down instead