#💻┃code-beginner

1 messages · Page 107 of 1

wintry quarry
#

Use a paste site to share code !code

eternal falconBOT
wintry quarry
#

I think whatever version of Unity you're using doesn't support switch expressions

#

but the code for this asset is using it

ivory bobcat
#

Fix your IDE

wintry quarry
#

Unity 2019 doesn't support C# switch expressions

#

it's too old

#

Your options are:

  • upgrade Unity
  • rewrite that code
  • don't use that asset
wintry quarry
#

note you really shouldn't go around sharing code for paid assets

oblique gale
#

will there be a change if I used Visual Studio Code instead of Visual Studio in terms of speed? because my pc is barely holding on with Unity alone...

patent compass
#

Hello. why am i getting this error.

fringe plover
#

i started working with Networking rn, and i dont know, do i need to use NetworkRigidbody instead of normal one?
ok ill use it cuz some components are asking for it

wintry quarry
#

I think you meant StoveCounter.State not stoveCounter.State.

#

StoveCounter is the class
stoveCounter is a reference to an instance of the class

patent compass
#

u are right. lmao, thanks

rotund sparrow
#

The numbers get turned around, (42 becomes 24) is there a way to fix it

wintry quarry
ivory bobcat
#

Log the value of integer to display

nimble apex
#

somehow i encountered a strange thing

bright zodiac
#

such as?

nimble apex
#

theres a card object in my game scene , this card object will have its material loaded when we enter the scene, it has no valid material until then

#

i have a script, that will modify a parameter of the material

#

however, it seems that even it successfully modified the param, the card cannot reflect the changes

#

i need to get into the inspector and manually modify the value in order to get it works

north kiln
#

Are you modifying emission by any chance

wintry quarry
#

You know that Renderer.material creates an in memory copy of the material. It won't modify the original.

nimble apex
#

i know, but it will modify that object with the renderer mat right

ivory bobcat
#

Show some code

nimble apex
#

ok

#

sry i cant use discord on my working mac, so i will do screenshot

wintry quarry
#

Yep you made a copy of the material

#

With Renderer.material

nimble apex
#

yes

north kiln
#

You reassign the shader??

nimble apex
#

and the code successfully changed the parameter of that material

north kiln
#

That's not a check, that's an assignment

nimble apex
#

right

#

the card shader was replaced

north kiln
#

Implicit bool conversion strikes again

#

Also doesn't onenable occur before start

wintry quarry
#

Right so that will always be false yes?

rare basin
#
    public GenericDictionary<int, UnityEvent> diamondHPThresholdIncome;
    private HashSet<int> triggeredThresholds = new HashSet<int>();

    public void CheckForDiamondIncome()
    {
        var currentHealthPercentage = enemyUnit.healthSystem.LifePercentage();

        foreach (var threshold in diamondHPThresholdIncome.Keys)
        {
            if (currentHealthPercentage <= threshold && !triggeredThresholds.Contains(threshold))
            {
                diamondHPThresholdIncome[threshold]?.Invoke();
                triggeredThresholds.Add(threshold);
            }
        }
    }

What's the difference here if I'd use private List<int> triggeredThresholds instead of HashSet<int>? None?

nimble apex
north kiln
#

I don't even know what happens if you assign a null shader

wintry quarry
bright zodiac
#

instantiate a new one via Material mat = new Material(Shader.Find("someShaderType"));
then just copy the properties via mat.CopyPropertiesFromMaterial(oldMat)

nimble apex
wintry quarry
nimble apex
#

we change the shader

rare basin
#

so If i just want to check if a collection contains element X (not plan to do anything with that element, just check if it's there) it is better (faster) to use HasSet?

nimble apex
#
  1. this script should be executed after 4
wintry quarry
north kiln
nimble apex
#

yeah i just found out its not replacing material , but the shader instead

bright zodiac
nimble apex
#

damn wait

nimble apex
#

bruuuh its fixed!!!!

bright zodiac
#

magical

#

😅

nimble apex
#

the weird thing is, even i put the urp ref on start, the parameter still changed

#

i swear i saw that

#

so i think , welp it should be fine? but then the changes didnt reflect

#

lol ty guys

north kiln
#

Check with the debugger next time and you'll see what executes when and can be extra sure what you saw

nimble apex
#

ok ty

rotund sparrow
north kiln
#

I have no idea how that could occur, but maybe enabling RTL on the text component can do that?

rotund sparrow
#

Thanks, it works now

oblique gale
#
public void NewGame()
    {
        this.gameData = new GameData();
    }
public class GameData
{
    public int time, day, week, money;
    public float stamina;
    public int LustLevel;
    public int LustExperience;

    public GameData()
    {
        this.time = 0;
        this.day = 1;
        this.week = 0;
        this.money = 1000;
        this.stamina = 100f;
        this.LustLevel = 1;
        this.LustExperience = 0;
    }
}

I don't understand why is it not loading the new instance of GameData. It's returning day 0 instead of day 1. It's working before but now it's not...

eternal needle
oblique gale
eternal needle
languid spire
#

what is the difference between gameData and data ?

queen adder
#

Vector3 Direction = (transform.position + Player.transform.position).normalized;
transform.position -= Direction * Time.deltaTime * MiniSpeed;
i was trying to make a projectile move towards the player but for some reason it just mirrors the players moves anyone got any ideas on why?

oblique gale
# eternal needle how are you sure that currentDay isnt 0?
{
    public int time, day, week, money;
    public float stamina;
    public int LustLevel;
    public int LustExperience;

    public GameData()
    {
        this.time = 0;
        this.day = 1;
        this.week = 0;
        this.money = 1000;
        this.stamina = 100f;
        this.LustLevel = 1;
        this.LustExperience = 0;
    }
}```

```//DAY
    private Text[] dateNDay;
    private int currentDay;

    //DATE
    private string[] week = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
    private int weekPos;
    public int WeekPosition { get { return this.weekPos; } }

    private bool napChoice = false;

    public void LoadData(GameData data)
    {
        this.currentDay = data.day;
        this.weekPos = data.week;
        this.currentIndex = data.time;
    }```
keen dew
eternal needle
queen adder
teal viper
#

Well, it's definitely not gonna work as it is now

#

I think we went over it earlier today or yesterday...

queen adder
#

mhm we did and that worked for smth else

teal viper
#

Well, it's the same issue...

queen adder
#

actually its not

#

if we use what we talked about earlier it will go directly away from the target which is what we needed

#

i swap the values and it just mirrors movements

#

now we just want it to go to the target

teal viper
#

First let's clarify one thing: when we say target, we mean the position/direction that we want to move to. Not any specific target in your game.

queen adder
#

yes

teal viper
#

Yes. And so the direction of movement is always target position - origin position.

#

And you move the object by adding direction times speed to it

queen adder
#

yes

teal viper
#

This is common sense and anything else would make things more complicated

#

And that's not what you have currently

shrewd swift
#

Hey, is there a thread or website with some basic "do"/"dont do" tips for beginners ?
Like how to use references, components, tricks,...

languid spire
shrewd swift
queen adder
teal viper
shrewd swift
#

Another question to be sure, private vars are usually named with the _ prefix yes ?

queen adder
#

yep

oblique gale
#

It did turn it back to 1 but for some reasons, when the saving happens, it returns back to 0 even tho it's already been set to 1

teal viper
#

Before/after

eternal needle
#

it doesnt matter what you think it was for, if thats the only place you assign a value to .day, then that is the place where it is assigned 0

#

im not sure where that 3rd debug comes from, because theres only 2 shown here. But its still clear that its initialize to 1 correctly

teal viper
#

Or it's not assigned at all and it's the default value.

eternal needle
#

assuming they didnt cut out a default ctor

oblique gale
teal viper
#

Sounds like your code is erroring and not executing as expected.🤷‍♂️

oblique gale
#

It shows an error for Line 46 rooting from Line 26

teal viper
#

gamedata is probably null before you load.

#

Where is that debug that prints 0 located btw?

oblique gale
teal viper
#

A method that errored would return immediately, so that's not possible.

#

You should show us the stack traces of the messages.

eternal needle
eternal needle
#

then you should properly look at why the error happens through the stack trace, which you can see by clicking on the log. At the very bottom you should see more about it, like what even called the method that caused the error

fringe plover
ivory bobcat
#

Cool feature

#

Without code, folks won't be able to help (video code isn't useful)
How to post !code

eternal falconBOT
fringe plover
#

its not animation bug, i tried removing animator

ivory bobcat
#

Does jumping allow you to move forward?

hoary karma
#

any way to play animation just once via script?

fringe plover
fringe plover
ivory bobcat
#

Either way, your else immediately removes all velocity on the z

#

Comment out line 47

fringe plover
#

lemme check

#

ye u right, tysm

sour fulcrum
#

somewhat silly question, I have a poco class like this

public class TypeData
{
    [HideInInspector] public string name;
    [HideInInspector] public string typeString;
    public List<string> assetList;

    public TypeData(string newTypeString)
    {
        typeString = newTypeString;
        assetList = new List<string>();
        name = newTypeString;
    }
}

and I have a list of them, How could I go about sorting that list based on their name?

#

usually i would just use Sort() but this doesn't implement that and It wouldn't know to reach for name

keen dew
#

but List does implement that, this one doesn't need to

sour fulcrum
#

Mhm?

keen dew
#

Why would this need to implement Sort? The list does the sorting, not this class

twilit pilot
sour fulcrum
#

oh that might work

sour fulcrum
#

usually linq scares be but finally doing editor stuff that can let me go nuts with that kind of stuff

fringe plover
hoary karma
#

Transform snowParticleClone = GameObject.Instantiate(snowmanParticle, transform.position, transform.rotation); Destroy(snowParticleClone.gameObject, 1f); why is this giving me Can't destroy Transform component of 'SnowmanEffect(Clone)'. If you want to destroy the game object, please call 'Destroy' on the game object instead. Destroying the transform component is not allowed.?? i literally use that same code for all of my particle and all of them works fine except for this one

ivory bobcat
#

Show us the console error

#

It should provide line/character count

hoary karma
hoary karma
charred heart
#

Ah anyone here use Mirror for multiplayer? I'm facing a problem, the OnCollisionEnter method doesn't call on client but it work on host (to popup a canvas). Here my setup:

  1. Car (networkbehaivor, boxcolider, rigidbody networktransform, networkrigidbody).
  2. House (monobehavior, boxcolider)
  3. All client control 1 car, client has no authority, client call Command[bypass authority] method to tell host to move the car.
    Whether it's the host or the client who is moving the car, the house only popup the canvas on host.
ivory bobcat
#

Fix errors from top to bottom, if possible. Else you may be evaluating false positives

#

I'm assuming you're destroying a reference to a Transform component somewhere.

hoary karma
#

i instantiate and destroy that particle during 3 scenarios. the first one is if the object/snowman lifetime hit zero i instantiate the particle then destroys the snowman, for this scenario the script is not attached to the snowman that is being destroyed. the second one is if the snowman hit a bullet before a certain time. the third one is if the snowman hit a bullet after a certain time. for the second and third scenarios the script is attached to the snowman that is being destroyed

hoary karma
#

if(other.CompareTag("PistolBullet") && timerSnow > parryTimer) { snowScript.isCooldown = false; snowScript.timerSnow = null; snowScript.snowmanLifetimeTimer = null; CameraEffects.ShakeOnce(); parryTxt.Play("parry", -1, 0f); Transform snowParticleClone = GameObject.Instantiate(snowmanParticle, transform.position, transform.rotation); Destroy(snowParticleClone.gameObject, 1f); Destroy(this.gameObject); this is the second

#

else if(other.CompareTag("PistolBullet") && timerSnow < parryTimer) { CameraEffects.ShakeOnce(); Transform snowParticleClone = GameObject.Instantiate(snowmanParticle, transform.position, transform.rotation); Destroy(snowParticleClone.gameObject, 1f); Destroy(this.gameObject); } this is the third

hoary karma
#

i also happens to forget about that scenario

dapper solstice
#

for hats,shoes.sunglasses,hoodies and stuff is that a character change script or a cosmitc script?

teal viper
woven crater
#

no eventmanager?

keen dew
#

What do you expect it to be?

cosmic dagger
woven crater
#

isnt it a built in code in unity?

#

oh nvm i see now. wops

woven crater
#

whats the different between using
public UnityEvent onshoot;
and
public delegate void onshootdelegate();
public static event onshootdelegate onshoot;

teal viper
#

Not much difference.

woven crater
#

beside one is use in the editor and other in script

teal viper
#

You can use both in script.

woven crater
#

okie

shrewd swift
#

what is the name of the method to trigger something when a key is down/up/hold ? instead of getting the key on update

bright zodiac
woven crater
#

what does that mean? the event tab appear on unity editor?

#

oh its storing instance of game object?

eager elm
shrewd swift
#

ok ty

hoary karma
#

whats wrong??

#

`public float GiftSpeed;
public Transform GiftObj;
Transform GiftObjClone;

public void Update()
{
if (Input.GetKeyDown(KeyCode.J))
{
GiftObjClone = GameObject.Instantiate(GiftObj, transform.position, transform.rotation);
Rigidbody rb = GiftObjClone.GetComponent<Rigidbody>();
//rb.velocity = transform.up * GiftSpeed * Time.deltaTime;
}

}`

eager elm
eager elm
stark sonnet
#

its referencing my unit selections code for the instance but i just don't understand why its erroring

hoary karma
#

i didnt realize i accidentally put that script in other object aswell

keen dew
#

best guess is that you didn't create the list

stark sonnet
gaunt ice
#

UnitSelections.Instance.unitList.Add(this.gameObject);
three possibilities, instance is null, unitList is null, or both of them indeed after you fix one

stark sonnet
#

thats my unit selections code that its supposed to be referencing

gaunt ice
#

where you set the _instance?

stark sonnet
#

yes that should be one of the first things set in the code.

#

Im sorry. This is all new to me. I didn't realize selecting multiple units would be so difficult 😫

keen dew
#

So does that mean you figured out what's wrong?

stark sonnet
#

I've looked it over again and again and I just cannot see what's wrong. I've even went back through the tutorial to see if I maybe typed in something wrong and I didn't see any errors.

keen dew
#

The Awake method in UnitSelections is only halfway finished. Look that up in the tutorial.

stark sonnet
#

Oh! I see now. I'll change that and see if it works

#

That absolutely worked. I must have been typing too fast and forgot my else statement. Im a dumbass 😫 thank you for the help!

autumn tusk
#

ok so i know theres a better way to do this

#

so right now i have an enemy script, with my enemy script being divided into two parts

one controls the movement and manages health and collisions
the other controls the enemy's hands, which pivot towards the player

#

what i want to do is make it so that when the enemy dies, the hands stop moving and the enemy no longer flips to face the player

#

i set my health to public and my hand script to pull the health value, but it falls apart when i summon in multiple instances

#

once i kill all enemies, all hands on all enemies stop pivoting

teal viper
autumn tusk
#

ok i was thinking

#

if i use an if statement to check for the current tag that could work

rare basin
#

how can I swap animator controller in the animator? i've created public AnimatorController enemyAnimator; then i just replace the animator.runtimeAnimatorController = enemyAnimator and it works perfectly fine, but I cannot make a build with it as this is a part of UnityEditor

shrewd swift
#

hey
i got a OnCollisionEnter function in a parent gameobject, it has a Rigidbody and a script only
i got a child with a meshcollider

when the meshcollider detects a collision, OnCollisionEnter is called in parent

my question is: can i get the "source" of the call of OnCollisionEnter from the parent ? I would like to know what child is the source

edit: or even can i pass some extra data to the parent ?

rare basin
#

i meant the namespace

verbal dome
#

I think you gotta use the RuntimeAnimatorController type

rare basin
#

oh didin't know it exists

#

that fixes it then

verbal dome
#

Not sure, I have done that but dont remember how, can check in a moment probably

rare basin
#

damn even the references are kept

#

when changing the variable type

verbal dome
#

Yeah the editor version inherits from the runtime version

#

And unity is chill like that

rare basin
#

got it

#

thanks

nimble scaffold
#

Guys can I do animation on key press without animator controller?

swift crag
#

Why don't you want to use an animator controller?

woven crater
#

can i invoke an event with an argument that trigger two method one with and the other without using said argument?

acoustic berry
#

How do you insert an element at runtime into the middle of a layout group? Say I have a vertical layout group, with buttons #1,3,4 already in it, and now the player just unlocked button #2 so I want to create it and add it to the UI. I only know the SetParent() way of adding to the group, which adds it to the bottom

polar acorn
acoustic berry
#

ahhh it was a property buried in the Transform, ty so much

polar acorn
#

Yeah there's no way to directly spawn it in at a specified index, it'll need to be a two-liner

nimble scaffold
swift crag
#

It is not complex. You just don't know how to use it yet. Making an animator play an animation when you push a button is very straightforward.

#

the legacy Animation component is very annoying to work with.

nimble scaffold
#

Why annoying sir?

polar acorn
nimble scaffold
#

Just sir can u pls say how to do animation on key press with animation controller

polar acorn
#

You should learn it. You're going to need it

nimble scaffold
#

Just say it step by step

#

Pls

hexed terrace
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
nimble scaffold
#

How to do the last part

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
swift crag
#

the Learn course will be even better for picking them up

tender stag
#

i clicked the link cause i wanted to look at the code and i get this

#

lmao

frosty hound
#

@tender stag public links are editable. Just trolls.

tender stag
#

oh alright

stuck palm
#

why isnt this working?

#

what is a ref flaot

safe root
#
public class Walking : MonoBehaviour
{
    Rigidbody rigidBody;

    public float walkingSpeed = 5f;

    void Start()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            Addwalk();
        }
    }

    public void Addwalk()
    {
        rigidBody.AddForce(transform.forward * walkingSpeed * Time.deltaTime, ForceMode.Impulse);
        Debug.Log("Got to here");
    }

Shoulden't my character move forward?

raven kindle
#

I am making a 2d endless runner game with randomly spawned platforms, and items for the player to college.

I have a script attached to a game object called generate platforms, which is randomly generating platforms at 3 different layers. I have another script called generate coins, but i want the coins only to be generated ontop of platforms. How would i do this?

verbal dome
#

smoothdamp needs a ref float to remember its "velocity" between frames

#

The float should be in your class, not local

stuck palm
#

right

stuck palm
#

i wanted to use lerp but apparently thats not a good idea

verbal dome
stuck palm
verbal dome
#

Simpler example than the one in the docs:cs float smoothTime = 0.3f; float velFloat = 0.0f; float smoothedFloat; void Update() { float targetFloat = // Enter target value here smoothedFloat = Mathf.SmoothDamp(smoothedFloat, targetFloat, ref velFloat, smoothTime); }

verbal dome
stuck palm
#

okay

#

that example u gave looks easier, thanks

#

i'll use that

sullen canyon
#

I heard that mmorpg server games need to handle each client as a separate thread to avoid waiting for the client to complete the job.?

safe root
verbal dome
safe root
verbal dome
#

Also, continuous forces should be added in FixedUpdate not Update

#

And don't multiply the force with deltaTime - it already does that

fossil drum
verbal dome
#

Aand check the value of walkingSpeed in the inspector

safe root
verbal dome
#

Also, ForceMode.Force or ForceMode.Acceleration for continuous forces

sullen canyon
verbal dome
#

Impulse/VelocityChange is for one-shot forces (jump, dash etc)

fossil drum
sullen canyon
fossil drum
safe root
verbal dome
solemn fractal
#

Hey guys, Sometimes during my game, something wierd happen and I am not sure why. I have 2 code. One to keydown SPACE and other F1 but sometimes during the game when i use SPACE it does what is inside the F1 code.. and I cant understand why.. here are both: ```cs
if (Input.GetKeyDown(KeyCode.Space) && _canShield){

        if (!_hasShield && !_uiManager.isCooldown){

            StartCoroutine(ShieldOnTimer(3, _shieldCD));
            _uiManager.StartCooldown();
            
        } 
    } ```  and the other: ```cs

if (Input.GetKeyDown(KeyCode.F1) && _isF1 == false){
ToggleF1();
_f1.SetActive(true);
} else if (Input.GetKeyDown(KeyCode.F1) && _isF1 == true){
ToggleF1();
_f1.SetActive(false);
} ```

#

why in the world would the game do what is inside the F1 keycode if I use space?

safe root
verbal dome
#

Yeah, in other words not snappy

#

The solution I linked solves that while still using forces instead of directly changing rb.velocity

safe root
#

Got it thank you

stuck palm
#

how can i add an offset to this

wintry quarry
verbal dome
#

You can't "offset" a transform. You can offset a vector though with addition

wintry quarry
#

Yeah note it's the position you likely want to offset. The Transform represents position, rotation, scale, and hierarchy relationships.

#

you can also use spawnTransform.TransformPoint(offset) if you want it to be relative to the object's rotation and scale

safe root
safe root
#
public class Walking : MonoBehaviour
{
    Rigidbody rigidBody;
    Camera playerCamera;
    public Vector3 moveDirection;
    public Vector3 desiredVelocity = new Vector3(1f, 0f, 1f); 
    

    public float walkingSpeed = 5f;

    // Start is called before the first frame update
    void Start()
    {
        rigidBody = GetComponent<Rigidbody>();
        moveDirection = Vector3.zero;
        playerCamera = Camera.main;
      
    }

    // Update is called once per frame
    void Update()
    {
        Addwalk();
        
    }

    void Addwalk()
    {
        Vector3 difference = desiredVelocity - rigidBody.velocity;
        Vector3 cameraForward = playerCamera.transform.forward;
        cameraForward.y = 0f;

        cameraForward.Normalize();

        moveDirection = Vector3.zero;

        if (Input.GetKey(KeyCode.W))
        {
            moveDirection += cameraForward;
        }

        if (Input.GetKey(KeyCode.A))
        {
            moveDirection -= playerCamera.transform.right;
        }

        if (Input.GetKey(KeyCode.S))
        {
            moveDirection -= cameraForward;
        }

        if (Input.GetKey(KeyCode.D))
        {
            moveDirection += playerCamera.transform.right;
        }

        if (moveDirection.magnitude > 1f)
        {
            moveDirection.Normalize();
        }

        rigidBody.AddForce(difference * walkingSpeed, ForceMode.Force);
    }
rich adder
verbal dome
#

Then calculate the difference, then add the force

wintry quarry
#

only in FixedUpdate

safe root
wintry quarry
#

If you don't put it in FixedUpdate, you are going to move at different speeds at different framerates

#

Which is a very poor player experience.

safe root
wintry quarry
#

That is what I said, yes

#

technically input handling should be in Update, and physics in FixedUpdate, but in this particular case for now it will work alright if it's all in FixedUpdate

safe root
#

Alright, thank you

wintry quarry
#

If and when you add jumping you'll likely need to switch to a more robust separation between input handling and physics

safe root
#

I already have jumping

safe root
solemn fractal
verbal dome
#

When calculating difference

safe root
verbal dome
#

Yeah or do thiscs Vector3 desiredVelocity = moveDirection * walkingSpeed;

verbal dome
#

Try to understand how it works otherwise I'm just spoonfeeding you here

verbal dome
#

You have a target velocity, you calculate a difference from current velocity to target velocity.
If your current velocity is already close to the target velocity, the difference is minimal, and very little force is added.
If the difference is bigger, the force will be bigger

safe root
#

OH, I think I get it

verbal dome
#

It's like a rubber band

safe root
#

Yeah, it's kinda cool

verbal dome
#

Also don't multiply the difference with walkingSpeed inside AddForce

#

Multiply it with a separate float, like acceleration

#

It lets you control the 'snappiness'

woven crater
#

need help this suddently not working anymore for some reason

hexed terrace
#

"this" is what

woven crater
#

debug.log

hexed terrace
#

Which one.

woven crater
#

onpointer enter and exit

hexed terrace
#

Exit doesn't have a Debug.Log, and Enter has two.. so.. which Debug.Log isn't working?

woven crater
#

both

#

the whole onpointerenter and exit is not working

hexed terrace
#

Is the object you're trying to interact with 3d or UI ?

woven crater
#

UI

#

have collider

hexed terrace
#

Event System present in the scene and active ?

woven crater
#

yes

polar acorn
#

The Pointer interfaces work with raycast targets, like the Image component here

#

Check to make sure you don't have another raycast target covering them up, it'll only call the functions on the topmost thing you're hovering.

#

If you select your Event System in the scene, at the bottom of the inspector is a little status window (you might need to drag the handle up to see more than a line of it). If you keep that visible while playing, it should display the name of the object you're hovering over

safe root
safe root
verbal dome
#

Like I said, use a different float to multiply the force so you can control the acceleration

safe root
#

That's make sense

woven crater
rare basin
polar acorn
#

That's why it was like the first thing you were asked once it was confirmed to be UI

woven crater
#

sorry. im dumb

safe root
#
public class Grapple : MonoBehaviour
{
    private RaycastHit lastRaycastHit;
    [SerializeField] private float maxDistance = 2f;
    private bool PullSurface = false;

    CharacterController characterController;
    // Start is called before the first frame update
    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 origin = Camera.main.transform.position;
        Vector3 direction = Camera.main.transform.forward;
        RaycastHit raycastHit = new RaycastHit();
        

        if (Physics.Raycast(origin, direction, out lastRaycastHit, maxDistance))
        {
           if (raycastHit.collider.gameObject.CompareTag("GrappleAble"))
           {
                print ("Can grapple to!");
                if (Input.GetMouseButtonDown(0))
                {
                    GrapplePull();
                }
           }
            
        }

    }

    public void GrapplePull()
    {
        characterController.enabled = false;
        transform.position = lastRaycastHit.point + lastRaycastHit.normal * 2;
        characterController.enabled = true;
    }

Why do I need to select a object refernece to set a instace of an object?

polar acorn
#

If you're asking why you have to assign a value to a variable to use it, it's because what would you be referencing if you weren't referencing something?

#

Like, how would you call a function on nothing

frigid sequoia
#

Which is lane 29?

safe root
#

if (raycastHit.collider.gameObject.CompareTag("GrappleAble"))

languid spire
#

if (raycastHit

frigid sequoia
#

You didn't create the raycast itself right?

polar acorn
#

You never actually store anything in it, you just create an empty one

#

so it has no object in it

safe root
#

Oh

frigid sequoia
#

You just told the engine "when a raycast that I didn't declare hits something" and it was like "?????"

safe root
#

I see now.

#

Thank you and the problems fixed

woven crater
#

imma lurking in here to absorbing knowledge

stuck palm
#

im getting null errors with this field, even though it is being set in the inspector. how do i fix this?

polar acorn
rich adder
polar acorn
#

Make sure you aren't changing it in the code and make sure you've set it on the specific instance of this script that's throwing the error

oblique gale
#
    {
        data.stamina = this.staminaBar.value;
    }```

```public void SaveGame(string dataFileName)
    {
        foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
        { 
            dataPersistenceObj.SaveData(ref gameData);
        }
        dataHandler.Save(gameData, dataFileName);
    }```
#

I don't understand why I'm getting a null error on the first code

polar acorn
lusty flax
#

my jump physics are extremely floaty and weird. what's happening? (isGrounded functions properly btw)

void FixedUpdate()
{
    xInput = Input.GetAxis("Horizontal");
    zInput = Input.GetAxis("Vertical");
    player_rb.velocity = new Vector3(xInput * speed, player_rb.velocity.y, zInput * speed);
    if (Input.GetButtonDown("Jump") && isGrounded())
    {
        player_rb.velocity = new Vector3(player_rb.velocity.x, jump_force, player_rb.velocity.z);
    }
}
#

oh wait

#

i fixed it

#

nevermind...

oblique gale
hallow acorn
#

is there another way to jump isntead of addforce? or can somebody explain me why it boosts the player up insanely fast and it falls isanely slow?

polar acorn
hallow acorn
oblique gale
#

here in datapersistancemanager. the gamedata is a serializable

polar acorn
cerulean kestrel
#

does this animation setup work?

hallow acorn
cerulean kestrel
#

sorry for interrupting

polar acorn
oblique gale
polar acorn
languid spire
polar acorn
cerulean kestrel
#

it probably does

#

just checkin

#

ah ok i checked it ty

#

it works👍

hallow acorn
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float Speed = 10f;
    [SerializeField] private float JumpForce = 400f;
    [SerializeField] private float CrouchSpeed = 6f;
    [SerializeField] private float SprintSpeed = 18f;

    [SerializeField] private bool IsFacingRight = true;
    [SerializeField] private bool IsGrounded = true;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private playerControls PlayerControls;
    [SerializeField] private Animator anim;

    private bool Jumping = false;

    private void Awake(){
        PlayerControls = new playerControls();
    }
    private void OnEnable(){
        PlayerControls.Enable();
    }
    private void OnDisable(){
        PlayerControls.Disable();
    }

    private void OnTriggerEnter2D(Collider2D collision) {
        IsGrounded = true;
    }
    private void OnTriggerStay2D(Collider2D collision) {
        IsGrounded = true;
    }
    private void OnTriggerExit2D(Collider2D collision) {
        IsGrounded = false;
    }

    void Start()
    {
        Application.targetFrameRate = 60;   
    }

    void FixedUpdate()
    {
       float move = PlayerControls.Floor.Move.ReadValue<float>();
        rb.velocity = new Vector2(move * Speed, 0);

        float Jump = PlayerControls.Floor.Jump.ReadValue<float>();
        if (Jump >= 0.1)
        {
            Jumping = true;
        }
        else
        {
            Jumping = false;
        }

        print(Jumping);
        if (IsGrounded && Jumping)
        {
            rb.AddForce(new Vector2(0, JumpForce));
        }
    }
}
```  we dont talk about graphics and leveldesign just a test
polar acorn
hallow acorn
hallow acorn
safe root
#

Ok I have code that teleports me to a object but I want to teleport on top of that said objecrt. How would i do that?

polar acorn
hallow acorn
safe root
hallow acorn
#

sry

polar acorn
#

Two options, depending on your use cases

hallow acorn
#

have another question how do i "Cancel" the jump so the hight changes depending on how long i press space for exaple?

safe root
hallow acorn
verbal dome
hallow acorn
verbal dome
#

Yes, look it up

cerulean kestrel
#

I GOT THE DOOR TRIGGER TO WORK LETS GOOOOOOOO

queen adder
#

are those mc textures

cerulean kestrel
#

no

queen adder
#

that looks like dark gray concrete powder

cerulean kestrel
#

its bricks

#

grey bricks

#

oh

#

its dirt

hallow acorn
cerulean kestrel
queen adder
cerulean kestrel
#

and in 120 secs, it closes

#

and opens again

eager elm
oblique gale
eager elm
polar acorn
lusty flax
#
void FixedUpdate()
{
    xInput = Input.GetAxis("Horizontal");
    zInput = Input.GetAxis("Vertical");
    player_rb.velocity = new Vector3(xInput * speed, player_rb.velocity.y, zInput * speed);
    if (Input.GetButtonDown("Jump") && isGrounded())
    {
        player_rb.velocity = new Vector3(player_rb.velocity.x, jump_force, player_rb.velocity.z);
    }
}

This is the code for the movement of my character controller, but my character isn't moving in the direction that it's facing in. I know that this is due to the fact that the Vector3s are moving the player relative to the world and not to its own orintation. How can I fix this?

slender nymph
#

you need to transform your input into the direction the object is facing. you can do so by creating a Vector3 from the input then pass it through transform.TransformDirection

oblique gale
#

wait im reopening my pc

lusty flax
oblique gale
# eager elm you can probably fix is by changing it to: GameData gameData = new GameData(); o...
    private List<IDataPersistence> dataPersistenceObjects;
    private FileDataHandler dataHandler;
    public static DataPersistenceManager instance { get; private set; }

    private void Awake()
    {
        if(instance != null)
        {
            Debug.LogError("Found more than one Data Persistence Manager in the scene.");
        }
        instance = this;
    }

private void Start()
    {
        this.dataHandler = new FileDataHandler(Application.persistentDataPath);
        this.dataPersistenceObjects = FindAllDataPersistenceObjects();
        LoadGame("save0");
    }
    public void NewGame()
    {
        this.gameData = new GameData();
        this.gameData.day = 1;
    }

    // Saves the game
    public void SaveGame(string dataFileName)
    {
        foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
        { 
            dataPersistenceObj.SaveData(ref gameData);
        }
        dataHandler.Save(gameData, dataFileName);
    }
    public void LoadGame(string dataFileName)
    {
        this.gameData = dataHandler.Load(dataFileName);

        if (this.gameData == null)
        {
            Debug.Log("No data was found. Initializing data to defaults.");
            // Initialize gameData to defaults
            this.gameData = new GameData();
        }

        foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
        {
            dataPersistenceObj.LoadData(gameData);
        }
    }```
polar acorn
waxen adder
#

Does anyone have any cool tips and tricks for debugging endless loops? On my end, I just slap a bunch of breakpoints everywhere until I can narrow down what's causing the problem

oblique gale
polar acorn
hallow acorn
#

how can i add crouching in my game the best with the new input system? new action and adding bindings with modifiers?

swift crag
#

Either way, you only need to use one/two modifier bindings if you want to do something like

#

ctrl-A
ctrl-shift-click

hallow acorn
swift crag
#

Okay, so you'll make a new input action and call it "Crouch"

#

then add one or more bindings

#

You'll leave the action as the default kind -- "Button", rather than switching it to "Value"

hollow carbon
hallow acorn
#

k thank you

hollow carbon
swift crag
#

How are you getting input right now? There are several options.

#

InputActionReference, the Player Input component, the generated C# class, ..

hollow carbon
#

when i lost i cant see the image of the button

#

look

swift crag
#

the image is disabled

#

you've turned on the text, but not the image

hollow carbon
hallow acorn
hollow carbon
#

this is how it should look like

swift crag
eternal falconBOT
swift crag
#

If you're using the generated C# class, this will be very easy

hollow carbon
eternal falconBOT
hollow carbon
#

cs

#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class UIGameOver : MonoBehaviour
{
private TextMeshProUGUI textMesh;
public AudioSource GameOver;

// Start is called before the first frame update
void Start()
{
  textMesh = GetComponent<TextMeshProUGUI>();
}

// Update is called once per frame
void Update()
{
    if (GameManager.instance.gameOver == true && textMesh.enabled == false)
    {
        textMesh.enabled = true;
        GameOver.Play();
    }
}

}

hollow carbon
#

the buttons should only be visible if i die yk

swift crag
# hollow carbon

your code does not turn the images on. the images are disabled.

hollow carbon
#

ok but when i able the image it will also show when i turn on the game

swift crag
#

then make your script enable the image

#

it's exactly the same as enabling the text

hollow carbon
hollow carbon
swift crag
#

you already know how to enable a TextMeshProUGUI

swift crag
#

so you know how to enable an Image

swift crag
#

e.g.

#
PlayerControls.Floor.Move.ReadValue<float>();
#

this is reading a float value from your Move action

#

PlayerControls.Foo.Bar.IsPressed()

This will return true if Bar is a button action that's currently pressed

#

So, maybe, PlayerControls.Floor.Crouch.IsPressed()

hallow acorn
#

ok ty i try

hollow carbon
swift crag
#

Image is not image

#

capitalization matters.

#

you've declared a private field named image

hollow carbon
#

ah wait

swift crag
#

also, you'll need to give image a value

hollow carbon
swift crag
#

i would suggest adding [SerializeField] to those two fields so that they show up in the inspector

#

then just assigning them

polar acorn
hollow carbon
swift crag
#
[SerializeField] private Image image;
#

or, equivalently

#
[SerializeField] Image image;
#

fields are, by default, private

hollow carbon
#

i dont understand im sorry

hallow acorn
swift crag
#

This works for any press-and-hold action

polar acorn
swift crag
hallow acorn
swift crag
#

Get rid of this using line.

#

There are many places that declare Image

#

and your code editor can't know which one you meant to use

#

You want using UnityEngine.UI;

hollow carbon
#

how to deinstal it?

#

ok

swift crag
#

literally just remove the line

#

using allows you to use things without typing the entire name

hollow carbon
#

ok

#

before the game starts i have to make the image of the button invisible so that it only shows when i die

#

how do i do that?

swift crag
#

you already know how to make it invisible from the start, don't you

#

by disabling it

hollow carbon
#

yeah wait how can i upload a video

#

my englisch is not the best and its complicate

#

look

hollow carbon
swift crag
#

Show me your current code.

hollow carbon
swift crag
#

Drag the Image component into the field down here.

#

that's why we added [SerializeField]

hollow carbon
#

ahhh

swift crag
#

this shouldn't change anything, though, since you still had the GetComponent

#

you'd get an error in the console if the variable was null

#

One thing, though..

#

restard.enabled = true will do nothing, because the button was already enabled

#

Oh, and the button was already enabled!

#

So the if condition was never met

#

Disable the button in the inspector. It should start working.

hollow carbon
#

ok

fossil tree
#

hi i get the following error and wanted to know how i can make for add random number to my list in a fonction ?
the error: ```UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'boutonJouer' on game object 'Image'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.Random.Range (System.Int32 minInclusive, System.Int32 maxExclusive) (at <40205bb2cb25478a9cb0f5e54cf11441>:0)
boutonJouer..ctor () (at Assets/boutonJouer.cs:14)

swift crag
#

as the error suggests, Awake or Start are often a good replacement

swift crag
# hollow carbon ok

If you aren't sure if your code is running, you can add a Debug.Log statement to check

#

Debug.Log("Showed the game over text!");, for example

wintry quarry
fossil tree
swift crag
fossil tree
#

mb i have understand that

swift crag
#

Awake and Start are the names of methods.

#

specifically, they're messages

#

Unity will call them at specific times

hollow carbon
#

still like that but now even the button wont work

fossil tree
hollow carbon
swift crag
#

I see nothing wrong with using Awake

#

Awake runs the instant a component is created (as long as its game object is active)

fossil tree
#

i use trigger event

#

so i need a method i call by myself

swift crag
#

"trigger event"?

polar acorn
fossil tree
#

yeah

amber cliff
#

!bug

eternal falconBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

swift crag
#

Do you mean EventTrigger?

fossil tree
#

the thing in the right

#

event trigger

polar acorn
eternal falconBOT
swift crag
#

Do your setup in Awake.

fossil tree
#

i want when i click on my ui that run this code public void down() { myButtonStart.SetActive (false); boutonController.boutonListe.Clear(); boutonController.boutonListe.Add(random); boutonController.boutonListe.Add(random2); boutonController.boutonListe.Add(random3); boutonController.boutonListe.Add(random4); timer.temp = 30; timer.jouer(); }

#

if i put it in awake that gonna run at the start of my game not when i click

polar acorn
#

No one is saying to move any of this

swift crag
#

Share the entire script.

fossil tree
#

wait i have a better idea

wintry quarry
meager sentinel
#

I have a trigger enter that reproduces a sound (basically the most basic code in the world) But it dont works, i dont really know what i am doing wrong since i saw 2 different tutorials and tested with different things that may cause the error, someone could help me?

silver heron
#

Hey how do i start a test run in virtuel studio community?

#

i dont see a run button or something

wintry quarry
swift crag
#

Walk through this. It troubleshoots all of the ways physics messages can go wrong.

fossil tree
# swift crag Share the entire script.
using System.Collections.Generic;
using UnityEngine;

public class boutonJouer : MonoBehaviour
{
    public timer timer;
    public score score;
    public GameObject myButtonStart;
    public boutonController boutonController;   
    
    
    
    
        int random = Random.Range(1,9);
        int random2 = Random.Range(1,9);
        int random3 = Random.Range(1,9);
        int random4 = Random.Range(1,9);
     

    
    public void down()
    {
        myButtonStart.SetActive (false);                                    
        boutonController.boutonListe.Clear();
        boutonController.boutonListe.Add(random);
        boutonController.boutonListe.Add(random2);
        boutonController.boutonListe.Add(random3);
        boutonController.boutonListe.Add(random4);                          
        timer.temp = 30;
        timer.jouer();
    }
}
wintry quarry
#

that's your problem
those Random.Range calls need to go in Start or Awake, as mentioned earlier.

polar acorn
#

as we said before

#

put them in Start or Awake

swift crag
#

Ah, I think I see a misconception

#

int random = Random.Range(1, 9);

fossil tree
swift crag
#

This does not mean that random will constantly get new random values

wintry quarry
#

not the variable declaration

swift crag
#

It's just running Random.Range(1,9) once and sticking the result in random

fossil tree
#

ohhhh ok ty

meager sentinel
wintry quarry
#

e.g.^

wintry quarry
polar acorn
#

Honestly just get rid of the fields and put Random.Range directly into the Add calls in down

wintry quarry
#

Show it with the log

#

and show what printed

meager sentinel
wintry quarry
#

show code

#

I don't know what this means, this is just random

meager sentinel
#

i just placed it

wintry quarry
#

If you have a sound issue it has nothign to do with this code or OnTriggerEnter

#

1st make sure there are no errors in console

#

second, double check you don't have audio muted or something

#

or that the volume is not just too low etc.

swift crag
#

(you can, indeed, mute scene audio)

wintry quarry
meager sentinel
meager sentinel
meager sentinel
rare basin
#

where did that question come from

meager sentinel
#

like the object

#

am not very good at english tbh

swift crag
#

I don't think Play re-winds the audio

#

use Stop, then Play

#

maybe i'm just misreading the docs though

#

If AudioSource.clip is set to the same clip that is playing then the clip will sound like it is re-started. AudioSource will assume any Play call will have a new audio clip to play.

meager sentinel
#

but one stays without working

#

Oh wait

#

it does work

#

i confused the trigger for the other one

#

thanks

dawn rampart
#
using System.Collections;
using UnityEngine;

public class SwordCollision : MonoBehaviour
{
    public AttackingEnemies enemies;
    public int damage = 2;

    private bool isHit = false;
    private float hitCooldown = 0.5f;

    private void Update()
    {
        // Your other Update logic here
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Enemy") && !isHit)
        {
            enemies.enemyHealth -= damage;
            Debug.Log("Hit Health is: " + enemies.enemyHealth);

            if (enemies.enemyHealth <= 0)
            {
                Destroy(other.gameObject);
            }

            // Start the HitCooldown coroutine
            StartCoroutine(HitCooldown());
        }
    }

    private IEnumerator HitCooldown()
    {
        isHit = true;

        float timer = 0f;

        while (timer < hitCooldown)
        {
            timer += Time.deltaTime;
            yield return null;
        }

        isHit = false;
    }
}
#

if i hit the enemy in quick succession isHit never equals false

queen adder
#

Hey in my 2D game i'm getting these errors:

wintry quarry
#

Use Debug.Log and see what's happening

rare basin
wintry quarry
dawn rampart
#

in another script

wintry quarry
fossil tree
#

ty everyone that work perfectly now that was a pretty dumb error xdd

tribal minnow
#

hey, i have 2 animations and i need help with making them work on all characters. as in i have a sitting animation that should work fine but when i play the animation on my characters their arms go through their legs and stuff like this. i believe i need to do something that is called ik or something but i have no idea on how to do it. can anyone help

queen adder
meager sentinel
# meager sentinel

Ik that this may be a extremely stupid question, but someone knows or got a tutorial on how to make a sound not able to repeat anymore? I mean, when i do this and stop hearing the sound. If i get close again i came back to hear the same sound again, someone knows how to stop it?

tribal minnow
eager elm
wintry quarry
#

You should only be setting it true when the coroutine first starts

wintry quarry
#

it's literally in Update

#

think about it

#

isHit is true for the whole duration of the cooldown

#

so you're doing it every frame during that time

dawn rampart
#

ok that makes sense

wintry quarry
#

The cleanest way to do this would be with an event

#

but you can also have the SwordCollision script drive this interaction by calling a function when the coroutine starts

dawn rampart
#

after they do the animation

whole isle
#

so i added slimes into my game
when i attack them there health goes into negative but they dont disappear

polar acorn
#

Also, what calls RemoveEnemy()?

whole isle
#

😭

#

omg idk waht to doooo

wintry quarry
#

Seems pretty obvious - create the parameter

#

or make sure you spelled it correctly

#

etc

polar acorn
#

Also what calls RemoveEnemy()

wintry quarry
#

also make sure you actually call RemoveEnemy from somewhere. Is it happening in an animation event?

#

Don't just throw up your arms and give up. Check on everything

whole isle
wintry quarry
#

Then it will not run

whole isle
#

ok ill re attempt

polar acorn
stuck palm
#

how can i make an equivalent of an oncollisionenter with the floor when im using a character controller? i have an IsGrounded bool which is a raycastspehre, but i want something to run once when they touch the floor (i.e. a ground puff)

wintry quarry
#

Sorry, fixed link^

#

you can also just do this with your grounded check though

#

e.g.

if (!groundedLastFrame && groundedThisFrame) {
  EmitPuff();
}```
stuck palm
#

thank you

whole isle
#

what do i do

wintry quarry
#

make sure the property getter returnt he backing field health and not itself Health

#

If you have it call itself you will always get a StackOverflowException

waxen adder
#

So I want the editor/game to abort if something goes terribly wrong. Right now, I have this:

public static class UnityShortcuts
{
    public static void Quit()
    {
        Debug.Log("Quitting...");
        Application.Quit();
        UnityEditor.EditorApplication.isPlaying = false;
    }
}

While it does close the game, it seems to do so only when the editor has already attempted what it was going to do. I want more of an emergency abort. As in, as soon as this function is called, we instantly quit out of the application. Is that even possible?

wintry quarry
#

only when the editor has already attempted what it was going to do
What do you mean by this?

wintry quarry
#

What was it going to do?

wintry quarry
# whole isle ngl i dont understnad

Your current code is equivalent to this:

int health;

int GetHealth() {
    return GetHealth();
}```
What you want is this:
```cs
int health;

int GetHealth() {
    return health;
}```
#

properties are just functions

#

and you have a function that just calls itself, infinitely, until the computer runs out of memory.

whole isle
#

oh okk i think i understnad

#

so shall i change healthj

wintry quarry
#

you must change the property to return the field, instead of returning itself

waxen adder
wintry quarry
waxen adder
#

dang

wintry quarry
#

the only chance you have is force quit or attach a debugger and cause it to break out of the loop

waxen adder
#

Well, that's certainly good to know

whole isle
#

in the video im watching

#

it like this and its able to work

#

how come they dont face the same issue

polar acorn
whole isle
polar acorn
# whole isle
"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: 139
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2023-12-20
verbal dome
eager elm
rich adder
#

didn't PraetorBlue explain this already to them

polar acorn
wintry quarry
#

stop doing that

polar acorn
wintry quarry
#

Actually a great argument here for _health < this private variable naming convention

rich adder
#

tutorial is shite anyway

#

why is Health a prop if backing field is Public

wintry quarry
#

oof haha didn't notice that

#

kinda silly

timber tide
#

underscore is one more key I have to press though

polar acorn
wintry quarry
#

environmentally unconscionable

whole isle
wintry quarry
#

and it will work lol

whole isle
#

omg i cant even copy right

wintry quarry
#

hint - your error is on line 15, as it says

whole isle
#

i replaced Health with health

wintry quarry
#

you also have the same problem on line 20

#

pay closer attention

verbal dome
#

Do any IDEs warn about recursive stuff inside property getters?
I feel like they should

marsh glade
waxen adder
#

I'm kinda surprised intellisense didn't pick that up

whole isle
#

cause it would infintley repeat until there no memory left

#

why questio mark banned

wintry quarry
#

well it shows at least a recursive icon, there might be an inspection for it too

whole isle
#

OMGGGGGG

#

NOTHING SAVEDD

#

😭

#

why did it save here

#

but not here

verbal dome
#

You didn't save the scene

timber tide
#

scene != assets

verbal dome
#

Those assets aren't in the scene

whole isle
#

dammmmmm the tghing closed cauise of the overflwo error im pretty sure

rich adder
#

if it crashed unity without save prob

timber tide
#

doesn't the scene save when you play though. I wouldn't know because I'm always saving

marsh glade
#

btw, the error is (mostly) in line 20. Your "get" for Health tries to return the value for Health, which tries to return the value for Health, which tries to return the value for Health,... creating an infinite loop

summer stump
whole isle
#

its fine guys learning experience

summer stump
#

Good perspective!

rich adder
whole isle
rich adder
#

eg . it helps knowing what a property is and why is it you're using it in the first place

marsh glade
# whole isle yh i cahnged it to health

Yes, but people were pointing to the fact that the mistake was in line 15, when the issue was actually in line 20. You can keep the "if(Health <= 0)" as is without creating an infinite loop as long as Health doesn't "get" itself

#

This doesn't create an infinite loop, although I wouldn't advise doing it

whole isle
#

GUYSSS

wintry quarry
whole isle
#

im a genius

#

i got it back in assest

marsh glade
#

oh, I looked at the fixed version, my bad

stuck palm
verbal dome
#

Or in a class-level bool at the end of the frame

wintry quarry
sturdy lark
#

To make sure my character grounded the ground has the layermask ground. If i want to make my character be able to walk on certain objects should i put the layer ground to them or make something else?

verbal dome
#

I just have a layer "Scenery" that I put all map objects in

sturdy lark
#

Makes sense

whole isle
#

guys im so lost

#

after thje slime deleted everything all over thje place

#

like my sword animation dosent work now

#

does any 1 know where i canstart to fix this

rocky canyon
#

you're gonna need to explain More, you break down ur problem into smaller steps..
asking a question like that is too unspecific to get any real help..

thats like calling a mechanic and asking why your car "isn't running right"

#

why does the sword animation stop working..

whole isle
#

it started when i went on my movement code

#

made changed then it stopped working

rocky canyon
#

i'd start there and find out whats happening and work backwards until u see something you know doesn't work the way you intended it to

whole isle
#

so i can change that to start attack

rocky canyon
#

theres a warning there in the console..

#

maybe its the code controlling the animator?

slender nymph
rocky canyon
#

^ if u think ur saving often enough, u probably need to save more often 😄

rocky canyon
#

like a backup

upper sphinx
#

versions of your projects so you can go back if something messes up

rocky canyon
#

every day after u work on something important it gets uploaded to a server online..

whole isle
#

oh ok i see what u mean

rocky canyon
#

so if anything messes up u can revert it back to an earlier version

slender nymph
rocky canyon
#

for example

#

its basically your project folder.. theres programs that will pull and push (save and load) for ya

rocky canyon
#

but yea, keep that in mind.. at some point when ur projects get big enough its something u'll wanna start using

rich adder
upper sphinx
#

@whole isle GIT

rocky canyon
#

imagine the power going out and corrupting a project you've worked on for months

upper sphinx
#

You can find basic setup and tutorials on youtube.

whole isle
#

yh i probs do need to add that

slender nymph
#

you should always use it

rocky canyon
#

if u try to learn it i'd use a blank example project

#

until u get it figured out

upper sphinx
#

Because if you push wrong you can overwrite stuff.

whole isle
#

guys i think the problem is somewhere here

#

it was working fine before idk what changed

#

wasnt like that before tho

#

😭

rocky canyon
#

well idk the exact problem, but u do have two if statements that are identical

#

did u know that?

whole isle
upper sphinx
#

So you Animator is trying to look for that parameter but its not there, Check your Animator

rocky canyon
#

^ thas the problem tho..

#

isMoving is not set up as a parameter in that Animation Controller

#

so when u try to call it, it doesn't exist and causes errors/ undesired behaviour

whole isle
slender nymph
#

you should be looking at the parameters list

upper sphinx
#

An good idea to do when working with Animations is to have the animator window pulled aside and run the game as you watch the animator,
What are your paramenters in the controller.

whole isle
# whole isle

in the code i wrote its moving should it not be player walks cause that what it called in my animaotr

rich adder
rocky canyon
#

parameters are on the left there.. you have to create it, bool, trigger, etc and use it as a transition or w/e

#

you create it and name it.. but it has to match w/e u reference in the script

#

if u use isMoving in the script make sure ur parameter is called isMoving

  • IsMoving
  • is Moving
  • etc are not the same
whole isle
#

i just closed unity and re opening it lol

#

but imma go check

#

ty

small gull
#

how would i set a rigidbodys velocity to 0?

wintry quarry
slender nymph
#

do you know how to assign to the rigidbody's velocity?

small gull
rich adder
small gull
#

rb.velocity = 0?

whole isle
rich adder
slender nymph
# small gull rb.velocity = 0?

almost. rigidbody.velocity is a Vector3 or a Vector2 depending on the type of rigidbody you are using. so you need to create a vector that is all 0

rocky canyon
whole isle
#

instead of starting the game when im idle my idle animation is the walking animaiton

rocky canyon
#

u need to mark ur idle animation as the Default starting animation.. (it should be orange)

#

and then u transition into ur movement clips

whole isle
#

OMGGMG NOW IM WALKING IN THE IDLE ANIMATIONM

rocky canyon
#

Set as Layer Default State, thats how I commonly do it.. i'll create an Idle animation.. or for hard surface things, like a blender for example, my idle animation will just be a single keyframe and then i'd transition into the "running" animation

whole isle
#

yh it like that

rocky canyon
#

sounds like a transition problem

#

make sure ur clips are transitioning to the clips they should be..

#

and if not.. check the transitions/ the parameters, and the coding

#

if its not an error in the code then it'll most likely fit better in #🏃┃animation once u start getting into the editor stuff

whole isle
#

k i fixed it

#

and i feel like an idio

tender stag
#

in DetermineHeadbob() on line 64 i set the target amplitude and frequency according to the movemenet type, but it changes instantly when i switch the movement type, i tried like smoothing it on line 82 - 83, and then on lines 92 - 93 i tried replacing the target values with smoothed values, but it gives me weird results, so should i smooth the offsetX and offsetY instead?
https://hastebin.skyra.pw/difipawexe.csharp

stuck palm
#

is there a better way to do this? i think finding objects of type is kinda ass but its meant to account for new joining players

void Update()
    {
        PlayerScript[] players = FindObjectsOfType<PlayerScript>();
        
        if (players.Length == 0) {return;}
        foreach (PlayerScript player in players)
        {
            if (player.ID == playerID)
            {
                rt.position = _camera.WorldToScreenPoint(player.gameObject.transform.position + offset);
            }
        }
    }
slender nymph
#

instead of using FindObjectsOfType every single frame, which is a pretty expensive call. just have the newly joining players register themselves with this component on join

tender stag
timber tide
#

doing that in update is probably the worst way to utilize that

tender stag
#

have like a method OnPlayerJoin and OnPlayerLeave

#

or something

rocky canyon
#

yup, as u work think does this make sense to be running every frame

#

super simple optimization hack

stuck palm
#

yeah thats why i asked

#

cus it felt a bit expensive

#

what does this mean?

#

nvm figured ito ut

#

did the wrong thing

thorn holly
#

Weird question, but if I have a bunch of essentially “nodes” and I want to connect them and fill in whatever shape is made, even as the nodes are moving, how would I go about something like that?

sharp viper
#

Question : how I earth do I begin with making a Shop System for a Portrait Android 2d Game?

timber tide
#

Uh, start with the UI design then implement a shop script

rigid sage
#

sorry if this is a really stupid question but will tuts for character controller work with rigidbody?

#

if not, whats the best tut for rigid body 3rd person movement

night raptor
night raptor
#

CC does lot of stuff for you, rigidbody just simulates physics. Rb requires quite much of code to get character behaving correctly unlike CC which is made just for it

rigid sage
#

can you make momentum based movement similar to sonic frontiers with CC?

summer stump
verbal dome
#

Catlike coding has some text tutorials for RB movement. Haven't checked it much but their tutorials are usually decent
https://catlikecoding.com/unity/tutorials/movement/
If you want a video tutorial, I can't remember a decent one off the top of my head.
That being said, like Aleksi said, RB movement can get complex and you should get familiar with Vector maths

verbal dome
#

CC is easier to get basic movement fast

amber spruce
#

hey so im trying to have a ui image stay on top of a game object and its kinda working this is the code

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

public class InteractPrompt : MonoBehaviour
{
    public Transform target;
    public Camera cam;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Vector2 screenPos = cam.WorldToScreenPoint(target.position);
        transform.position = screenPos;
    }
}

and this is how it looks ingame how do i make it not be so far under it i want it to be right next to it

whole isle
#

why dosent it always let me drag the sprite into the animation

amber spruce
rich adder
whole isle
rich adder
amber spruce
rich adder
meager sentinel
#

in CursorLockMode, what is the thing to make it unlocked?

whole isle
#

oh aniation

#

animations

meager sentinel
polar acorn
polar acorn
meager sentinel
rich adder
polar acorn
meager sentinel
rich adder
#

so its not configured

polar acorn
eternal falconBOT
meager sentinel
#

ok, thank you

queen adder
#

how to get mouse position in the scene tab?

rich adder
meager sentinel
#

ty tho

queen adder
#

huh

meager sentinel
polar acorn