#💻┃code-beginner

1 messages · Page 27 of 1

random sand
#
    {
        transform.rotation = Quaternion.LookRotation(transform.position - CameraControl.hitDist);```
this script makes my object face the direction I want it to face but
```void FixedUpdate()
    {
        cj.targetRotation = Quaternion.LookRotation(transform.position - CameraControl.hitDist);```
doesn't. cj is a configurablejoint and angular drive is 10000. anyone know why?
hybrid karma
#

sorry where am i using that?

slender nymph
#

where you intend to start the Mark coroutine

west arch
#

Guys I just upgraded my TextMeshPro to version 3.2.0-pre.6 but I got this error Library\PackageCache\com.unity.textmeshpro@3.2.0-pre.6\Scripts\Editor\TMPro_CreateObjectMenu.cs(339,31): error CS0117: 'Object' does not contain a definition for 'FindFirstObjectByType'. And when I checked inside the script that line and many other lines is white color. Definitely there's something wrong here but I just have no clue.

languid spire
west arch
languid spire
#

Hmm, docs say it should be there

west arch
#

What should be there?

languid spire
#

FindFirstObjectByType

west arch
#

Yea but that's the issue. Starting from Object is not there. Also GameObjectUtility. Basically I was just upgrade and import TMP essentials. Then I got that weird error

azure zenith
#

Help

teal viper
# azure zenith Help

Don't crosspost. No one would be able to help you if you don't provide details.

royal linden
#

can someone help me understand wwhy this sends my camera to the moonatwhatcost

queen adder
#

Hey im looking for some help, im using Mirror and SteamWorks so i can play with some friends once me and my boy are done with the game. I just got done setting up the Player Model and animating it.

for some reason the transform.position.y in the inspector is constanly changing values same happens with the rotation.y which makes my camera turn by itself.

Also whenever im standing the characterController.isGrounded is constantly returning false for some reason which makes my player go into a part of the jump animation, and when i jump characterController.isGrounded is true and goes back to false...

Code:
https://pastie.io/hncegw.cs

Any help is appreciated

languid spire
queen adder
#
Options.SetResolution (System.Int32 resolutionIndex) (at Assets/2D/Scripts/Options.cs:51)``` what does this mean
royal linden
languid spire
royal linden
languid spire
queen adder
# north kiln https://unity.huh.how/runtime-exceptions/nullreferenceexception
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;

public class Options : MonoBehaviour
{
    /// <summary>
    /// - Manages the options menu
    [SerializeField] private AudioMixer audioMixer;
    [SerializeField] private TMPro.TMP_Dropdown resolutionDropdown;

    Resolution[] resolutions;

    // Resolution Options
    void Start()
    {  
        resolutions = Screen.resolutions;

        resolutionDropdown.ClearOptions();

        List<string> options = new List<string>();

        int currentResolutionsIndex = 0;
        for (int i = 0; i < resolutions.Length; i++)
        {
            string option = resolutions[i].width + " x " + resolutions[i].height;
            options.Add(option);

            if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
            {
                currentResolutionsIndex = i;
            }
        }

        resolutionDropdown.AddOptions(options);
        resolutionDropdown.value = currentResolutionsIndex;
        resolutionDropdown.RefreshShownValue();
    }

    public void SetVolume(float volume)
    {
        audioMixer.SetFloat("Volume", volume);
    }

    public void SetResolution(int resolutionIndex)
    {
        if (resolutions != null)
        {
            Resolution resolution = resolutions[resolutionIndex];
            Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
        }
    }

    public void Quit()
    {
        Application.Quit();
    }
}

well why is my resolution list null

west arch
# languid spire FindFirstObjectByType

Not sure why you delete your answer but not problem. Okay so I've tried to regenerate the project files. I also even rebuild the solution lol(I have no idea why am I doing this). But still no luck 😢 . Re import also didn't help

languid spire
languid spire
#

yes

queen adder
west arch
languid spire
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

west arch
static cedar
#

And you never noticed? ;-;

languid spire
west arch
topaz mortar
#

what is the easiest way to generate/make getters for all my private variables?
[SerializeField] private ItemTypeSO itemType;
I got a whole bunch of these and want to be able to only read the value from other scripts

#

I'm using Visual Studio

#

I've been looking at properties vs fields a bit, but don't really understand when I should use each

#

Is this how I create a property that is read-only?
[SerializeField] public Sprite Sprite { get; }
Is there any reason I shouldn't be doing this?

north kiln
# topaz mortar Is this how I create a property that is read-only? `[SerializeField] public Spri...

You can't serialize properties.
You can serialize their backing fields if they have a setter, but it's generally best to do it separately.

Choosing one over the other... Use a field when you're serializing something. Generally that's private. Then use a property where required to control access from the outside and to add validation.

Though, properties are slightly slower than fields, so sometimes people avoid them in high performance situations. There are caveats

topaz mortar
#

when/why would I want to serialize something?

north kiln
#

So you can set it in the inspector

stiff birch
#

Also when you want the data set in inspector not to be discarded

topaz mortar
#

so I need to do it like this?

public Sprite Sprite { get => sprite; }```
topaz mortar
stiff birch
north kiln
#

That is one way, yes. The C# standards have private variables prefixed with an underscore, but that is preference

languid spire
topaz mortar
#

so I should use something like itemSprite instead?

languid spire
#

yes

topaz mortar
#
public Sprite Sprite { get => _itemSprite; }```
#

ew need to change the property name too

languid spire
#

no it was the variable Sprite you should not use sprite is fine

delicate portal
#

Hey, somehow my Player cant really move, the CapsuleCast doesnt really seem to work, either for the radius I guess, but it should be right. Can you help me?

    {
        //Collision detection
        float moveDistance = movementSpeed * Time.deltaTime;
        float playerRadius = .5f;
        float playerHeight = 1.5f;
        bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);`

**More code```
topaz mortar
languid spire
#

no

#
[SerializeField] private Sprite sprite;
public Sprite ItemSprite { get => sprite; }
topaz mortar
#

ah kaj

#

ty 🙂

topaz mortar
delicate portal
#

But the height and the radius should be right

ashen ferry
#

whats up with the ItemSprite { get => sprite; } does it do anything different than just ItemSprite => sprite;

ashen ferry
#

aa ok

neon ivy
#
void Start()
    {
        backendActive = true;
        StartCoroutine(TickUpdater());
    }

    IEnumerator TickUpdater()
    {
        while (backendActive)
        {
            if (active)
            {
                TickPing.Invoke();
                yield return new WaitForSeconds(1 / TickSpeed);
            }
        }
    }

trying to make a tick event, I'm subscribed to it in another script but it doesn't seem to work. anyone know why? backendActive is only there to avoid a while(true) loop

north kiln
#

If backendActive is true and active is false you have an infinite loop

#

Also, waitforseconds will wait and then occur on the next available frame, so this is an inaccurate way to make a tick

sacred cradle
#

uh

#

what do i do here

#

i wanna learn CSharp

north kiln
#

Look at the pinned messages, as directed

sacred cradle
#

ok thx

#

yeah but i like uh

#

want someone to teach me

#

reading isnt my profesion

#

no?

north kiln
#

Then pay a tutor or take a course

sacred cradle
#

i have no money!

west arch
#

I'm gonna report this as a bug I assume?

north kiln
#

No. Does the IDE look configured when you look at your own code (not text mesh pro's code)?

#

Also not in your screenshots is the external tools setting in Unity's editor preferences

sacred cradle
west arch
north kiln
#

Then it's configured

west arch
#

This right?

north kiln
#

Yup

sacred cradle
#

BRO

west arch
#

Yea. Then it's a bug

sacred cradle
#

c# is 10X easier then i thought

north kiln
#

What is a bug? It's configured

languid spire
west arch
north kiln
#

Your Unity version musn't be compatible with that version of the package

sacred cradle
#

this didnt work

#

it told me to do that

#

ohhhh

#

wait

#

ik what they mean now

west arch
#

Some name is confidential

sacred cradle
#

why does this just keep loading
string myFriend = "GreenX";
myFriend = "Ezra";
Console.WriteLine(myFriend);

languid spire
sacred cradle
#

oh

#

just my wifi

#

😄

west arch
neon ivy
languid spire
#

it is ok, I checked for you

west arch
languid spire
west arch
#

Damn right, must be the version problem

#

but

sacred cradle
west arch
#

Case closed. Thank you guys! You're awesome

sacred cradle
#

just keeps loading

#

BRO

#

its still loading

#

why

#

@north kiln

#

my thing wont load

#

DDEWvugjergejr

#

can someone just help me 😭\

#

bro

#

@fickle plume

#

can you help me?

fickle plume
#

@sacred cradle Don't ping people into your questions. And don't ping moderators with non moderation issues.

sacred cradle
#

sorry

#

im new here

#

and idk who to ask

fickle plume
sacred cradle
#

oke

topaz mortar
sacred cradle
#

ig ill just figure it out by myself god damnit 😦

north kiln
#

Well, this isn't even Unity-related at this point

sacred cradle
#

im tryna learn the thing but its not loading

north kiln
#

Well, that's Microsoft or your wifi, we can't help

sacred cradle
#

, _ ,

heavy geyser
#

Hello I am having an issue with changing the transform position of a gameobject. we are supplying a direction for the gameobject to move in, and for how many steps (think sort of like chess). The for statement in the "Move" function is being called, but the game object is not being moved. if anyone could help that would be great! thank you!

p.s the code is a hellscape cause this is for a uni game jam and we are in crunch mode rn: https://pastebin.com/ZFDRMWJe

heady nimbus
#

!ide

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

heavy geyser
#

I am getting no errors in Unity, or my IDE. Sorry, I should have stated before

heady nimbus
#

Oh sorry that was for me, not you. Lol

heavy geyser
#

oh gahaha my bad

heady nimbus
#

Trying to determine if there have been any new options for IDE since VSCode had been fully dropped at this point

tiny leaf
#

is there a way to calculate the velocity from a collision or would it be too difficult since it looks likes the velocity keeps decreasing over time

languid spire
north kiln
tiny leaf
#

wait nvm

heady nimbus
heady nimbus
#

Thank you, I'll take a look through this

heavy geyser
languid spire
heavy geyser
queen adder
#

Okay so I'm not a Unity beginner but I am a VR Beginner, I'm starting a VR project and I was wondering if Unity or Unreal is the better engine. The specifics of my project is for it to run efficiently and reliably on low-end devices with a lot of content, multiplayer (on my own server), and an entire storyline. No biased answers, please.

languid spire
heavy geyser
#

Of course please bear with

heavy geyser
languid spire
#

post code where you call it

random sand
#
{

    private ParticleSystem particle;
    
    void Start()
    {
        particle = this.gameObject.GetComponent<ParticleSystem>();
        particle.Emit(1);
    }
    void Update()
    {
        if (!particle.isPlaying)
        {
            Destroy(this.gameObject);
        }
    }
}```
hey, I made this script to put on a prefab that instantiates at the position that a raycast makes contact with something. problem is, the animation doesn't play. also is there a more efficient way to do this?
ashen ferry
#

also higher floor overheads and u need that fps for vr

heavy geyser
# languid spire Are you sure you are calling the script on the correct object?

I am calling the Move() function from the InterpretMorse() function which is called from an external script called InputMachine. Here is the where I am calling it:

 if ( pI > 3 ) {
            playerController.InterpretMorse(ControllerArray);
            pI = 
            
            if (pI == 3) {
                ...
            }
            MorseReset();
        }```
the `ControllerArray` variable is an array that is updated with values that change depending on which type of morse code symbol they type.
queen adder
# ashen ferry low end devices with lots of content makes this unity or nothing situation imo, ...

Tbh, I think the only things Unreal have over Unity is that Unreal has Nanite and Lumen; also the fact that Unreal allows you to create AAA games as an indie developer in no-time, but I will say it def makes games look more bland. I think I will go with Unity but the only reason I am considering Unreal because of the recent trust breach and the fact that a massive amount of Unity developers are switching to unreal.

heavy geyser
#

the controllerArray is parsed into the InterpretMorse() function in the other file (that has the broken code) and is being split into two 2-digit arrays, the direction, and time arrays which are then parsed into the Move() function

teal viper
languid spire
queen adder
#

I'm not saying you can create a AAA game in Unreal as an indie dev, was more using that as an expression or whatever. Just saying that it's much easier to implement quality un Unreal.

languid spire
# heavy geyser indeed

I see you also have a PlayerAgent prefab, are you sure you used the GameObject from the scene not the prefab?

heavy geyser
#

AH!

#

Fixed it!

#

Thank you so much Steve

queen adder
#

I plan on programming my own server functionality but I want to use a third-party server as well. Are there any 3rd party servers that can give me manual server-client-server responses that allow you to program implementation manually? Or do they all have custom libraries?

languid spire
heavy geyser
#

I fixed it man

#

it somehow decided to work when I changed transform.position += new Vector3(...); to transform.position = new Vector3(...);

broken anvil
#

can anyone help me with a script? i want to child an object to a child of the collided object on trigger

languid spire
heavy geyser
sacred cradle
#

YO

tiny leaf
#

Let’s say I wanted to access different weapon objects on the ship. Would it be better practice to give each one its own serialized field (more fields) or to have an array of them (less descriptive naming when accessing them since indexing)

languid spire
tiny leaf
#

okay

charred spoke
#

Or a Dictionary

cosmic dagger
#

ohhh snap!

charred spoke
#

What did I do?

cosmic dagger
#

we went from an array + enum to a dictionary. what will we see next?

#

the options are endless . . .

mellow ledge
#

[2D] yo, i implemented a jump mechanic that uses a raycast for a ground-check. Now im watching a guide on wall-jumps and they use empty transforms positioned right (or left) of the player. Obviously this works but i'm trying to understand why use this approach and not a horizontal raycast? Can i use this method for ground jumps too? is one better than the other?

timber tide
#

You can do it many ways, but the empty transform way gives some better debugging visuals probably

charred spoke
#

Empty transforms? Or two colliders on each side?

timber tide
#

oh yeah they probably have colliders^

charred spoke
#

Cause a empty transform wont do jack

cosmic dagger
#

yeah, they probably have colliders on them . . .

mellow ledge
#

uh they have a field of type Transform and they place a new Empty to the right side. They do have colliders yeah mb for poor word choice

charred spoke
#

Well if anything a box collider is a bit heavier collision calc than a raycast

#

Maybe they want some thickness due to gameplay reasons, but then there is box cast

cosmic dagger
mellow ledge
#

yeah it seems weird not to just use a raycast to e

charred spoke
#

I wouldn’t call it weird. It all depends on what you want

mellow ledge
#

all i need is "am i touching a wall" (so not a ledge smaller than the player)

#

Does using the collider have a clear benefit over the raycast

timber tide
#

coverage

mellow ledge
#

but then i can just increase the ray size no?

charred spoke
#

It does not and for your ledge case a raycast might be better. I would even do 3 raycasts and make sure all of them are hitting the same object, that way you can calc the step hight too

cosmic dagger
charred spoke
mellow ledge
#

mm right

charred spoke
#

Well they dont have thickness they have a length

mellow ledge
#

gotcha

#

ill just use the raycast for now then. Thanks for ur advice

topaz mortar
#

Does this look ok/good?

{
    List<Item> itemList = character.Equipment.GetEquippedItems();

    foreach (Item item in itemList)
    {
        characterArmor += item.BonusArmor;
        characterMinDamage += item.BonusMinDamage;
        characterMaxDamage += item.BonusMaxDamage;
    }
}```
#

It's kind of a trip to go from CombatScript -> Character -> Equipment -> Item to get the bonus stats

timber tide
#

ye

cosmic dagger
topaz mortar
#

yeah not gonna call it every frame 😛

cosmic dagger
#

i'd invoke an event after an item is equipped to update the stats . . .

topaz mortar
#

I'll look into that

#

currently working with pre-equipped items, there's no actual item-equipping yet 😦

silk night
ashen ferry
#

spoiler alert if u plan on having debuffs on those stats and unequipping at any point it will be hard asf to handle all the cases without just recalculating each frame

#

or that was skill issue on my end idk

formal bolt
#

Oh my gosh

#

Why is it so hard to make a simple movement!!!!! >>>>:(

topaz mortar
formal bolt
#

nahg

#

its undertale like

#

and collision is kinda weird idk why am i make it weird

#

and i have issue at making player can slide when walking toward wall

#

i fixing it rn

queen adder
timber tide
formal bolt
#

having a bad time rn

swift crag
#

ah, you're doing the movement for the combat segments

#

So the problem is that you can't slide when moving diagonally against a wall?

formal bolt
#

yes

swift crag
#

How are you doing movement? You can show us your !code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

formal bolt
#

how to show

swift crag
#

see the bot message

formal bolt
#

its to much character in the code

swift crag
#

you'll want to use one of the pastebin sites.

#

paste your code in, click the save button, and copy the link

formal bolt
#

like this?

#

i have not much time left

#

i going to sleep

swift crag
#

That looks like a reasonable approach. But when does CollisionDetector.isOutsideBox update?

#

I think you need to check if you're outside the box after each attempted movement

#

It sounds like you're only checking once per frame

formal bolt
#

uh

#

okay

#

but its on other gameobject

swift crag
#

How does it work?

formal bolt
#

a box where player can only walk

#

on the second script

swift crag
#

ah, so it's using a trigger collider

formal bolt
#

yes

#

pls dm me

#

i dont want

swift crag
#

I would suggest using a Bounds instead.

You can ask if a point is inside of a Bounds.

dry tendon
swift crag
#

So you can just check if the player's position is inside a rectangle

formal bolt
#

how?

swift crag
#

actually, Rect would be more appropriate for 2D

formal bolt
#

im new

swift crag
#

I would put down two empty objects at the top left and bottom right corners of your play area.

queen adder
#

Is the problem like the player cannot go right next to the wall because of collision boxes?

formal bolt
#

dm me the answer i dont want the answer to gone and i need to scroll up when wake up

#

im going to sleep

swift crag
#
public Transform topLeft;
public Transform bottomRight;

Rect bounds;

void Awake() {
  float width = bottomRight.x - topLeft.x;
  float height = bottomRight.y - topLeft.y;

  bounds = new Rect(topLeft.x, topLeft.y, width, height);
}

void Update() {
  if (bounds.Contains(Vector2.zero)) {
    Debug.Log("[0,0] is inside the rectangle");
  }
}
formal bolt
#

dm me ok?

#

i want the answer in dm

queen adder
formal bolt
#

oh

swift crag
#

I don't want to DM people. You can just search for this mention tomorrow @formal bolt

formal bolt
#

how?!?!?!

queen adder
#

Also don’t demand things from other people when they are the ones helping you

swift crag
formal bolt
#

ok.

swift crag
#

That way, you can check if your horizontal move was okay, then check if your vertical move was okay

#

Another option would be to just use Bounds

formal bolt
#

bye bye

swift crag
formal bolt
#

ima sleep

swift crag
#

this can just snap you back in bounds

formal bolt
#

kk

#

if im not going to sleep my dad is gonna cut my wifi for 2 days

#

zzzzzzz

dry tendon
#

Hey, does someone know how could I do that kind of animation to the icon of my game in unity?

final kestrel
#

https://hatebin.com/lszsdtmkfo
I have this rotator on my player. Whenever I enter trigger that is either called rotator 1 or 2, player turns that way. But the thing is. When I fall off the platforms. The character just rotates without entering trigger. Can someone point why this happens?

#

I can post a video if needed.

queen adder
final kestrel
#

Of course.

swift crag
#

i see a rigidbody is involved

final kestrel
#

Yes with rigidbody

queen adder
final kestrel
#

This is the player movement script

queen adder
#

And everytime you trigger the rotations

#

You could unlock it

#

And rotate it

final kestrel
queen adder
#

And lock it afterwards

final kestrel
#

The part where I fall down the platforms.

swift crag
#

ah, so the direction is changing

#

Are you logging when you enter these triggers?

final kestrel
#

no not really

swift crag
#

Make sure you aren't just hitting a trigger you forgot about

final kestrel
#

I'm positive there is no trigger in there

queen adder
#

Using updates

swift crag
#

Log every time you enter a trigger.

#

I'm positive about a lot of things until I'm not (:

queen adder
#

Casaken there has to be some sort of trigger because how would you trigger the death screen?

swift crag
#

oh, look at this

#
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("RotatorLeft")&& canRotate)
        {
            diff = Quaternion.Euler(0, -90, 0);
            canRotate = false;
            StartCoroutine(EnableRotationAfterDelay(.4f));
        }
        

        if (other.CompareTag("RotatorRight")&& canRotate)
        {
            diff = Quaternion.Euler(0, 90, 0);
            canRotate = false;
            StartCoroutine(EnableRotationAfterDelay(.4f));
        }
        _rb.rotation *= diff;
        _rb.velocity = diff * _rb.velocity;
    }
#

this unconditionally causes you to rotate every time you enter a trigger

swift crag
#

it doesn't matter if the trigger doesn't have the appropriate tag

final kestrel
#

you're right the base ground

swift crag
#

You should return early if you didn't hit a valid trigger

final kestrel
queen adder
final kestrel
#

So the base ground which is a fail condition trigger. Causes me to rotate cos im triggering rotator regardless of its name

final kestrel
#

Can you tell me how it does that unconditionally? I have the rotator names in the if parameter?

near saddle
#

How can i access a variable from another script in a prefab script

queen adder
#

Vector 3*

swift crag
queen adder
#

And make the methods that move the player disabled

final kestrel
swift crag
#
  • If you hit "RotatorLeft" and you can rotate, set diff and disallow rotation
  • If you hit "RotatorRight" and you can rotate, set diff and disallow rotation
  • Rotate the player
#

The third point is not conditional.

#

You should bail out immediately if the tags aren't right.

#

maybe

unique hull
#

Either bail out or set a bool for "If dead" or the like

swift crag
#
if (left) { ... }
else if (right) { ... }
else { return; }

_rb.rotation *= diff;
_rb.velocity = diff * _rb.velocity;
#

I would call this an early return

#

returning early can be useful for a method that does a series of checks and, if they all succeed, runs some more code

#

you just return if the condition is not met.

final kestrel
#

all right

unique hull
#

Doesnt he want to update velocity even if either left/right is conditional?

queen adder
# final kestrel

To that method add another condition like a bool like “Dead” and if true disallow the movement code

#

If its false you allow it

swift crag
#

Any other trigger would be able to cause the bug.

#

You should fix the root cause (touching any trigger makes you change direction), not the symptom (touching the death trigger makes you change direction)

queen adder
unique hull
#

Put a bool for the _rb.rotation inside the left/right check?

final kestrel
#

uh okay i will try. Thanks

#

Okay i made it. Thanks everyone.

near saddle
#

how can u make a prefab access another variable without it being on the screen

#

i cant reference

queen adder
swift crag
near saddle
#

Yeah

#

How do i work aroudn that

#

around

shy cloud
#

I've got a slider which isn't interactable, I've already researched about it on the internet, but none of the fixes I found worked

swift crag
#

Whoever spawns the prefab should assign the reference.

mellow ledge
#

i make a raycast going right or left, depending where im facing, for a wallcheck.

void OnJump()
    {
        if (IsNearWall() //???
        {

        }

        if (IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
        }
        else if (canDoubleJump)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpSpeed * doubleJumpMult);
            canDoubleJump = false;
        }
    }

private RaycastHit2D IsNearWall() // Other return type maybe?
    {
        Vector2 facingDirection;
        if (transform.localScale.x < 0) facingDirection = Vector2.left;
        else facingDirection = Vector2.right;

        RaycastHit2D hit = Physics2D.Raycast(hitbox.bounds.center, facingDirection, 0.1f);
        return hit;
    }

What's the better approach here?

  • Should IsNearWall() return the direction of the hit wall to its caller OnJump() OR
  • Should OnJump() do the direction check and tell isNearWall() which direction to check for by passing a Vector2
heavy quarry
#

when installing new unity version, it asks me to install vs 2019. but i already have 2022 version. can i untick 2019 and just use 2022 with game dev for unity workload?

silk night
#

All LTS versions should support 2022

final kestrel
#

Hello! is me again... https://hatebin.com/aqvnooukeg
https://hatebin.com/cvmmkgdzaq. These are my player controller and player triggers scripts. I am trying to disable movement on death. Taking the isDead bool from player triggers and putting it in the if condition on FixedUpate. I thought It would not run the codes in there if player was dead but it does not seem to be working.

silk night
mellow ledge
silk night
silk night
mellow ledge
#

oops i wanted to use a gif as exmple

mellow ledge
silk night
#
        public void Test()
        {
            var (a, b) = IsNearWall();
        }
        
        public (bool, bool) IsNearWall()
        {
            return (true, false);
        }
mellow ledge
#

tht makes sense. Can you compare it to this for me please and tell me why yours is better

#

private Vector2 forward;

bool IsNearWall()
{
  //Perform raycast to forward vector
}

void OnJump()
{
  if(isNearWall())
  {
    //Jump code
  }
}

void Flip()
{
  if (movementInput < -0.01f)
  {
    transform.localScale = new Vector2(-1, 1);
    forward = Vector2.left;  
  }
  else if (movementInput > 0.01f)
  {
    transform.localScale = new Vector2(1, 1);
    forward = Vector2.right;  
  }
}
final kestrel
silk night
near saddle
#

how do i slow down GetKey

#

so it waits a bit

mellow ledge
near saddle
#

Im using it for my shooting script

rich adder
silk night
near saddle
#

how would i do that?

#

Okay

#

i found it

silk night
#

If you are already using DoTween the DoVirtual.DelayedCall might be an option too

near saddle
rich adder
near saddle
#

o

rich adder
#

you need a coroutine

near saddle
#

ah okay ty

rich adder
#
void Update()
{
    if (Input.GetKey(keycode) && canShoot)
    {
         //shoot
        StartCoroutine(Cooldown(shootSpeed));
    }
}
 IEnumerator Cooldown(float delay)
{
    canShoot = false;
    yield return new WaitForSeconds(delay);
    canShoot = true;
}```
final kestrel
#
  private void FixedUpdate()
  {
      if (!playerTrigger.isDead)
          Debug.Log("Is not dead");
          Move();
          if (canJump)
          {
              Jump();
              //set it to false after jump because we dont wanna go flying upwards.
              canJump = false;
          }
      else
      {
          Debug.Log("Is Dead");
      }
       ```
It keeps saying is dead.
#

does not see the if above.

polar acorn
final kestrel
#

where are my curlies

#

ahh

polar acorn
final kestrel
#

okay the log works now but I still got movement.

private void FixedUpdate()
{
    if (!playerTrigger.isDead)
    {
        Debug.Log("Is not dead");
        Move();

        if (canJump)
        {
            Jump();
            //set it to false after jump because we dont wanna go flying upwards.
            canJump = false;
        }
    }
    else
    {
        Debug.Log("Is Dead");
    }

}
#

after death that is

polar acorn
#

Are you sure that movement is coming from here

final kestrel
#

this is the whole thing now

#

and yes this is where I do the movement

#

the only thing thats coming from another script is isDead

polar acorn
#

So, you set a velocity

#

but you never stop moving when you're dead

final kestrel
#

yes

polar acorn
#

so that velocity still exists

final kestrel
#

I made this

#

Ahh so. After setting the velocity once, It does not matter if i keep setting it in fixed? Thats why it keeps moving whether player is dead or not?

polar acorn
#

Newton's First Law of Motion

#

An object at rest remains at rest, and an object in motion remains in motion at constant speed and in a straight line unless acted on by a net force.

final kestrel
#

wohhh thats cool

languid spire
#

I don´t think they teach basic physics in school anymore

final kestrel
#

I just thought it would stop if im dead thats all 😄

#

with the isDead boolean

languid spire
#

why would a boolean affect a Vector3?

polar acorn
final kestrel
#

I mean true

final kestrel
#

Thanks guys.

amber spruce
#

how exactly would i get the first thing in the list in another class

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

[Serializable] public class PickMoveset : MonoBehaviour
{
    public string moveset;
    public List<string> moves = new List<string>();
    public void PickGravity()
    {
        moveset = "gravity";
        moves.Add("push");
        moves.Add("pull");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        Debug.Log(moveset);
        Debug.Log(moves);
    }
    public void PickLevitation()
    {
        moveset = "levitation";
        moves.Add("levitate");
        moves.Add("float");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        Debug.Log(moveset);
        Debug.Log(moves[0]);
    }
}
#

like i want to get moves[0] but in a different class

amber spruce
#

so lets say i wanna use serialized references do i gotta serialize my string and list

#

and would i use serialized reference

languid spire
#

your string and List are already serialized because they are public

amber spruce
#

ok so in another class how would i refernce them sorry if im not understanding

languid spire
#

first get a reference to the GameObject the script is on
second get a reference to the script
third access the variable

amber spruce
polar acorn
amber spruce
#

alright thanks

amber spruce
# polar acorn You would need to know _which_ `PickMoveset` you want to get the `moves[0]` from...

this is my code what its meant to do is set text to those variables but it doesnt

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

public class ChangeUIText : MonoBehaviour
{
    public GameObject Text_Move1;
    public GameObject Text_Move2;

    PickMoveset pickMoveset;
    

    TextMeshProUGUI textmeshpro_Move1_text;
    TextMeshProUGUI textmeshpro_Move2_text;

    // Start is called before the first frame update
    void Start()
    {
        textmeshpro_Move1_text = Text_Move1.GetComponent<TextMeshProUGUI>();
        textmeshpro_Move2_text = Text_Move2.GetComponent<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        textmeshpro_Move1_text.text = pickMoveset.moves[0];
        textmeshpro_Move2_text.text = pickMoveset.moves[1];
    }
}
#

anyone know what im doing wrong

polar acorn
#

Second where do you assign pickMoveset

amber spruce
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PickMoveset : MonoBehaviour
{
   public string moveset;
   public List<string> moves = new List<string>();
    public void PickGravity()
    {
        moveset = "gravity";
        moves.Add("push");
        moves.Add("pull");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        Debug.Log(moveset);
        Debug.Log(moves);
    }
    public void PickLevitation()
    {
        moveset = "levitation";
        moves.Add("levitate");
        moves.Add("float");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        Debug.Log(moveset);
        Debug.Log(moves[0]);
    }
}
polar acorn
#

This has nothing to do with either of my questions

amber spruce
#

thats where i assign it isnt it

gaunt ice
#

this is just a script

polar acorn
#

This is what the class PickMovement is

languid spire
#

no, thats where you declare it

amber spruce
#

ah

polar acorn
#

I'm asking where you assign the variable pickMovement inside ChangeUIText

amber spruce
#

here??

rich adder
polar acorn
#

At what point do you tell the code which PickMoveset you put in the variable named pickMoveset

amber spruce
#

i dont think i did that lol no clue what that is

rich adder
polar acorn
gaunt ice
#

i think you dont know what variable=something is called, but you have used it, the = is assigning something to the variable

amber spruce
polar acorn
#

there could be one

#

there could be seven trillion

amber spruce
#

So how do I tell it the right one

polar acorn
amber spruce
#

The one I have 😂

polar acorn
#

How are you telling it which Text objects you want to use to display the text?

polar acorn
amber spruce
#

How

polar acorn
#

Drag it in

hard ore
#

Guys, how do i make it so perlin noise would only generate a few stone blocks here and there instead of layers of blocks

rich adder
#

bloons is never assigned

#

bloons is null because you never assigned it

#

no you're only assigning dmg from towerData.damage

summer stump
#

That is a declaration

Assignments happen in the inspector or with an = sign

rich adder
#

just make it public and assign it in the inspector

#

same way you did BaseTowa

#

so?

#

make aprefab

#

which object has bloons script and which one has ProjectileDmg

summer stump
#

What IS Bloons? You want that to be the single bloon that should take damage?

I'm confused by the goal with this script? If you want the balloon you hit, use the collision passed in from OnCollisionEnter

rich adder
#

dont you want the one from the collision ?

polar acorn
#

Which bloons do you want to call TakeDamage on

rich adder
#

Collision2D collision your parameter has that info

polar acorn
#

So get the Bloons script from the object you collided with

#

write what

summer stump
rich adder
#

you already check that object for a layer

#

instead look for the component you want, bloons

vale blade
#

google what a NullReferenceError usually means, from there it's pretty clear that something isn't initialized. Then you search how to initialize that variable with a target in Unity.

#

if you configure your IDE properly that helps too with suggestions as to what could be going wrong.

#

!ide

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

rich adder
#

yeah this is good, would be better to write something more robust with TryGetCompnent

#

if one is not found somehow

#

it doesnt break yes

#
if (collision.gameObject.layer == LayerMask.NameToLayer("Balloons"))
{
    if(collision.gameObject.TryGetComponent(out Bloons bloons))
    {
        bloons.TakeDamage(dmg);
    }
    Debug.Log("Bhealth");
    Destroy(gameObject);
}``` @lament kernel  
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
vale blade
#

I'm experiencing some issues getting a character to properly orient towards my player. Why is my character rotating off axis? I thought LookRotation was supposed to only rotate around the given axis?
var lookRotation = Quaternion.LookRotation(LookAtTarget.position - transform.position, transform.up);
LookAtTarget and transform.position are both at the same height (y), so I wouldn't expect this tilt to occur?

#
using UnityEngine;

public class RotationMotor : MonoBehaviour
{
    public Transform LookAtTarget { get; set; }

    private void Update()
    {
        var lookRotation = Quaternion.LookRotation(LookAtTarget.position - transform.position, transform.up);
        if (Quaternion.Angle(transform.rotation, lookRotation) > 5f) // 5f is the tolerance angle
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, lookRotation, .1f);
        }
        else
        {
            enabled = false;
        }
    }

    private void OnDisable()
    {
        LookAtTarget = null;
    }
}
rich adder
#

so it tilts up

#

you can make a new V3 look target not include that axis

vale blade
rich adder
vale blade
# rich adder you could use this also https://docs.unity3d.com/ScriptReference/Quaternion.Rota...

Thanks, this works fine for now

private void Update()
{
    // Calculate 2D target diff in X and Z
    var diff = LookAtTarget.position - transform.position;
    diff.y = 0;

    // Find the rotation that looks at target
    var targetRotation = Quaternion.LookRotation(diff, transform.up);
    
    // If the angle difference between these rotations exceeds tolerance
    if (Quaternion.Angle(transform.rotation, targetRotation) > _angleTolerance)
    {
        // Lerp towards target rotation
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, _smoothingSpeed);
        return;
    }
    
    // Disable once target rotation has been reached
    enabled = false;
}
rich adder
#

hmm as long is works ig lol very strange code..lerp is still wrong..

#

gpt strikes again

amber spruce
rocky owl
#

Hello people, i need help. Im doing a follower of the camera but the camera is blinking

#

pls help me 😦

#

this is my code

rich adder
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

summer stump
#

The value needs to go from 0 to 1

But you are multiplying a set value by a value that goes up and down but is generally a tiny fraction like .06. Which won't work

rocky owl
#

where?

summer stump
rocky owl
#

nah sorry

#

i remove time.deltatime?

charred spoke
amber spruce
#

anyone know how i can attach a script to a script component

desert wedge
#

hoping someone can point me in the right direction. im trying to clean up my code but i have hit a snag
right now i have all these fields im trying to compact down, they are set via the inspector and need to continue to be so

        [BoxGroup("Buttons")] [SerializeField] private TextBlock useEquipText;
        [BoxGroup("Buttons")] [SerializeField] private UIBlock2D combineButton;
        [BoxGroup("Buttons")] [SerializeField] private TextBlock combineText;
        [BoxGroup("Buttons")] [SerializeField] private UIBlock2D discardButton;```

So im moving them into a seperate class, each containing one UIBlock2D and one TextBlock (These are novaUI classes, monobehaviors)
``` [Serializable]
    public class NovaUIButtonCombo
    {
        public UIBlock2D button;
        public TextBlock text;
    }```

then im testing with
``` [SerializeField] public NovaUIButtonCombo TestButton;```

issue is that its not showing in my inspector at all. I need both the button and text to be serialized but they arent i dont even see just a single field for the entire object. how can i get this working? it would make my code a lot more organized...
vale blade
#

dotnet version doesn't have much to do with your IDE configuration but you do you

amber spruce
rocky owl
#

does it also work for movetoward?

vale blade
polar acorn
amber spruce
desert wedge
# rocky owl this is my code

what i do is value = mathf.lerp(value, goal, 1f - mathf.exp(-sharpness * time.deltaTime)) where sharpness is how fast you want the lerp to be

vale blade
desert wedge
rocky owl
#

Thanks 😄

vale blade
amber spruce
#
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;

public class ChangeUIText : MonoBehaviour
{
    public GameObject Text_Move1;
    public GameObject Text_Move2;
    public MonoScript Moves;

    

    TextMeshProUGUI textmeshpro_Move1_text;
    TextMeshProUGUI textmeshpro_Move2_text;

    // Start is called before the first frame update
    void Start()
    {
        textmeshpro_Move1_text = Text_Move1.GetComponent<TextMeshProUGUI>();
        textmeshpro_Move2_text = Text_Move2.GetComponent<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        textmeshpro_Move1_text.text = Moves.moves[0];
        textmeshpro_Move2_text.text = Moves.moves[1];
    }
}
rocky owl
vale blade
amber spruce
desert wedge
vale blade
desert wedge
vale blade
#

Isn't this what you're looking for?

polar acorn
amber spruce
#

it does though

#
   public List<string> moves = new List<string>();
polar acorn
desert wedge
polar acorn
desert wedge
#

and my IDE (rider) does say that its serialized but its not in the inspector

amber spruce
amber spruce
polar acorn
#

If you want to use pick moveset use that type

#

Why did you use monoscript

vale blade
amber spruce
rich adder
#

if you're manually picking in Unity, then you doing it wrong

polar acorn
vale blade
amber spruce
desert wedge
amber spruce
polar acorn
amber spruce
# polar acorn Show the current code
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

public class ChangeUIText : MonoBehaviour
{
    public GameObject Text_Move1;
    public GameObject Text_Move2;
    public PickMoveset pickmoveset;

    

    TextMeshProUGUI textmeshpro_Move1_text;
    TextMeshProUGUI textmeshpro_Move2_text;

    // Start is called before the first frame update
    void Start()
    {
        textmeshpro_Move1_text = Text_Move1.GetComponent<TextMeshProUGUI>();
        textmeshpro_Move2_text = Text_Move2.GetComponent<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        textmeshpro_Move1_text.text = pickmoveset.moves[0];
        textmeshpro_Move2_text.text = pickmoveset.moves[1];
    }
}
polar acorn
amber spruce
#

oh i get this

desert wedge
#

and this is how it looks in IDE

polar acorn
amber spruce
#

my bad

polar acorn
#

Look at the line the error is on. Something there is null but you're trying to use it anyway

vale blade
# desert wedge

that's odd. I don't know the origin of TextBlock etc so I'm not sure what the issue is there.
maybe just restart the editor haha

amber spruce
polar acorn
vale blade
#

but if I remove that Serializable above SomeOtherObject it dissapears both inside and outside the test object

desert wedge
#

hmmmmm

#

yeah idk i just backtraced the UI blocks and it turns out they arent monobehaviours? but they do attach to game objects like mono behavious. but at no point could i find them inheriting from monobehavior

amber spruce
vale blade
#

might be some funky serialization setup in that framework then. i think you're better off asking on a forum dedicated to that ui framework, sorry bud

amber spruce
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PickMoveset : MonoBehaviour
{
   public string moveset;
   public List<string> moves = new List<string>();
    public void PickGravity()
    {
        moveset = "gravity";
        moves.Add("push");
        moves.Add("pull");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        Debug.Log(moveset);
        Debug.Log(moves);
    }
    public void PickLevitation()
    {
        moveset = "levitation";
        moves.Add("levitate");
        moves.Add("float");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        Debug.Log(moveset);
        Debug.Log(moves[0]);
    }
}
#

why does moves not save?

desert wedge
vale blade
desert wedge
amber spruce
desert wedge
polar acorn
amber spruce
#

moves is null

#

but pickmoveset is moves and moveset so if they are null then so is it

amber spruce
#

the debug that says what it is in Pickmoveset says what it is but the debug in CHangeuitext has it as null

polar acorn
#

So, is pickMoveset null inside ChangeUIText

amber spruce
#

Yes

polar acorn
#

Then fix that

#

Where do you set pickMoveset

amber spruce
#

i think thats this

    public PickMoveset pickmoveset;
polar acorn
amber spruce
#

wdym

polar acorn
#

Where do you set the variable

amber spruce
#

thats in the ChangeUIText

polar acorn
#

where do you say which PickMoveset you are putting in the variable pickMoveset

amber spruce
polar acorn
amber spruce
#

yeah

#

thats attached to the canvas

polar acorn
#

Show the inspector for that object

amber spruce
polar acorn
amber spruce
#

there is no pickmoveset object

polar acorn
amber spruce
#

the pickmoveset script

polar acorn
#

So you don't have any PickMovesets in the scene

hexed cosmos
#

Does anyone know how to solve plugin issues?

#

I'm trying to build an apk

amber spruce
#

so now i just got this

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
polar acorn
amber spruce
#

So I add 2 moves to it and I try and get 2 moves

#

Not sure how it’s outside the index

#

so yeah it doesnt seem to save it or whatever

#

cause getting moves[0] says it outside of it

vale blade
desert wedge
polar acorn
amber spruce
amber spruce
# amber spruce

it gets stuff added to it when you press a button on the start screen

polar acorn
#

So there's nothing in it

polar acorn
amber spruce
#

so it happens in the pickmoveset script

polar acorn
amber spruce
polar acorn
#

Ah, I see now

amber spruce
#

its in a differnt scene

polar acorn
# amber spruce

Okay, and do you click this button before a single frame has had a chance to render

amber spruce
#

dont think so lol i aint that fast

polar acorn
#

which is looking for the first two elements in moves

#

which don't exist

#

because you haven't clicked yet

amber spruce
#

well changeuitext doesnt start happening till you enter that next scene i think

#

cause its not in a scene besides that one

polar acorn
amber spruce
#

isnt it the same as the pickmoveset in the old scene

polar acorn
#

Have you done anything to make it so?

amber spruce
#

and i also have it change scenes first then add stuff

#

so wouldnt it be doing it for the scene your in

polar acorn
amber spruce
#

so how do i fix this

polar acorn
#

You have two PickMovesets. One in the old scene and one in the new scene

amber spruce
#

how do i have them be the same and sync

polar acorn
amber spruce
#

i got it to work with just making the variables static

#

thank you very mucj

amber spruce
#

now i gotta figure out how to fix the text cause rn its super scuffed

silk night
#

what part of it is scuffed? to big? 😄

amber spruce
#

the fact that the text isnt centered

silk night
#

make the text-element canvas the same size as its parent and then in the text option you can use the center option

#

I assume the background thingies are their parents?

amber spruce
silk night
#

so the 2 background lines is one image? or are there 2 images?

polar acorn
amber spruce
polar acorn
#

and make sure the rect for the text spans the whole area you're centering it on

amber spruce
polar acorn
amber spruce
#

ah ok thanks

silk night
#

depending on if you want the same height, you can also use the bottom right in the first panel

amber spruce
#

works now thank you very much this helps so much

thorn perch
#

script 1: Enemyhealth (screenshot 1)
script 2: ProjectileBehaviour (screenshot 2)

i am trying to figure out How exactily my projectile behaviour deals damage to an enemie and how those 2 objects interact. And WHY it works because i really dont understand it

What i understand is that i have a maxhealth, and currenthealth.

looking at the script the currenthealth should reflect the same amount of maxhealth, though i dont know why, and wouldnt this then imply that in theory, if i made a heal item, theres actually no limit to the nemies health ?

Then i see that if the "takedamage" is being used it will subtract the same amount of the value to "damage"

Since damage is a public in projectile behaviour, this is what causes the script being able to "communicate with eachother" and i am therefore able to call upon "damage" it will subtract the amount listed with damage value.

If the value of current health reached 0 then a "event" called die should take place wihich is then destroying the game object.

But in projectilebehaviour, under check if the collision is with an enemy, i dont really understand this part. and why i have written EnemyHealth and enemyHealth and there is nothing in between, what does this do ?

Would the first one be a direct representation of "Enemyhealth" sccript ? i figure that "enemyHealth" is just the action of which is defined below in an if statement which calls upon takedamage and the value damage to deal damage to enemie.

I see that in the getcomponent it references the EnemyHealth script and looks for a object that has a collider and contains a Enemyhealthscript ?

silk night
thorn perch
cyan gate
#

Don't know what channel this fits in, but i can't figure out basic first person character controls. I tried to follow a tutorial but it didn't work and had no error messages. Can someone send me a project file with a standart capsule that has first person character controls set up? I'm using unity 2022.3.11f1 btw

silk night
cyan gate
#

Yes

silk night
#

Can you paste us the !code ?

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

buoyant knot
#

EnemyHealth doesn’t sound like a good component. I would probably define an EnemyState component, to hold different sorts of mutable data about an enemy

#

that way it can hold more than just health

silk night
buoyant knot
#

in that case it would be a HealthBar class, which reads from a generic enemy state script. Just looking at futureproofing

cyan gate
#

The ''tools'' section didn't appear on my toolbar

#

So i couldn't set it up properly

#

I tried to do it manually

mellow ledge
#
 void OnJump()
    {
        Debug.Log("Jump");
        if (IsNearWall())
        {
            if (movementInput != 0 && (Mathf.Sign(movementInput) == Mathf.Sign(forward.x)))
            {
                float launchDirectionX = -forward.x * 4;
                Vector2 jumpDirection = new Vector2(launchDirectionX, jumpSpeed * wallJumpMult);
                Debug.Log($"Launching to {launchDirectionX}");
                rb.AddForce(jumpDirection, ForceMode2D.Impulse);
                Debug.Log("Walljumped!");
            }
            return;
        }

        if (IsGrounded())
        {
            Debug.Log("Grounded");
            rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
        }
        // else if (canDoubleJump)
        // {
        //     rb.velocity = new Vector2(rb.velocity.x, jumpSpeed * doubleJumpMult);
        //     canDoubleJump = false;
        // }
    }

private bool IsNearWall()
    {
        Debug.Log($"Raycast to x {forward.x}");
        RaycastHit2D raycastHit = Physics2D.Raycast(hitbox.bounds.center, forward, 0.5f);
        if (raycastHit.collider != null) Debug.Log(raycastHit.collider);
        else Debug.Log("No wall detected");
        return raycastHit;
    }

void FixedUpdate()
    {
        rb.velocity = new Vector2(movementInput * moveSpeed, rb.velocity.y);

        if (!canDoubleJump)
        {
            if (IsGrounded())
            {
                canDoubleJump = true;
            }
        }
    }

Hi, hours later im still stuck on the walljump. every msg log happens, it even logs the "launching" msg with the correct Vector values, but i dont actually jump off the wall. all i see is vertical gain. What am i missing?

#

i disabled dbl jump on purpose to test this btw

keen dew
#

You overwrite horizontal velocity on every fixedupdate

polar acorn
mellow ledge
#

i thought that was the issue, but every solution i thought of didnt work

#

what do i need to modify so it doesnt override it?

polar acorn
#

What do you want to happen if you walljump away and hold a direction in the air?

mellow ledge
#

besides i did expect the velocity change from the walljump to affect that things value

mellow ledge
#

up and awy from the wall

polar acorn
#

Do you want the direction held to have any affect on air movement or do you want to just cancel out any sort of lateral movement until you land?

#

At what point can inputs start working again?

mellow ledge
#

if u switch it before jumping, nothing, if after, the usual knock

mellow ledge
#

but i do like the thought of being able to jump climb up a wall

open vine
#

Hey, im trying to make a grenade but do I need to just attach an explosion force to the grenade or would i have to get all the rigidbodies in the area and affect and add explosion forces starting from the grenade position?

polar acorn
mellow ledge
#

rb.AddForce(jumpDirection, ForceMode2D.Impulse); my main confusion is why this doesnt override it. Like, my fixedupdate is reading velocity which should have been affected by this previous update call

polar acorn
mellow ledge
#

obv 3

#

but i dont see why x = 3 happens

polar acorn
#

So why would your velocity be any different?

#
velocity = MovementInput;
velocity += wallJumpForce;
velocity = MovementInput;
mellow ledge
#

cuz i _think its doing

int x = 7;
x += 14;
x = x + smth;
Debug.Log(x);
#

hmm

polar acorn
#

rb.velocity = new Vector2(movementInput * moveSpeed, rb.velocity.y);

#

The X component of this velocity is movementInput times moveSpeed

#

Neither of which has anything to do with your walljump velocity

mellow ledge
#

right im seeing

#

the thing is

#

if i make my current velocity part of that ill just speed up a lot over time

polar acorn
#

So you could use AddForce and then clamp the speed to some maximum value

mellow ledge
#

addforce in the jump

#

clamp in where?

polar acorn
#

AddForce for normal movement

mellow ledge
#

the sad thing is ive been coding in c# for yrs but this physics stuff stvll confuses me

polar acorn
#

Clamp the magnitude after you set it

mellow ledge
#

hold on

edgy prism
#

When I have a function that takes parameters that can be null do I have to say "MyFunction(X = null, Y = null, Z = null, ActualParameterIWantTouse)" or is there a simpler way?

polar acorn
#
void MyFunction(ActualParameter, X = null, Y = null, Z = null)
edgy prism
#

My ActualParameter is nullable too

summer stump
edgy prism
polar acorn
#

You can still pass a null, but if you want to be able to ignore it, you need it to be optional and after any required ones

mellow ledge
# polar acorn Clamp the magnitude after you set it

so i have this now

 void FixedUpdate()
    {
        //rb.velocity = new Vector2(movementInput * moveSpeed, rb.velocity.y);
        rb.AddForce(new Vector2(movementInput * moveSpeed, rb.velocity.y));

        if (!canDoubleJump)
        {
            if (IsGrounded())
            {
                canDoubleJump = true;
            }
        }
    }

i still struggle to understand what i should clamp tho

#

sorry if im being sloww, my brains fried

edgy prism
polar acorn
edgy prism
#

Obviously I can ignore it when im not using any of the nullable parameters just in the scenario I want to include one and not the others

polar acorn
mellow ledge
summer stump
polar acorn
mellow ledge
#

ok i get what it does but not where it should go

summer stump
#

Like... the line immediately after

mellow ledge
#

OH

summer stump
#

Because that is where it may be above the max speed

edgy prism
mellow ledge
#

i thought i had to calc the clamp at the same time but its supposed to cut it off

mellow ledge
polar acorn
#

Yep that should do it

summer stump
mellow ledge
#

yes

#

but it didnt work

#

my jump height is much lower than it was now and movement acceleration and decelration is super slow. Not even walljumping

polar acorn
#

You've just made a pretty significant change to your movement system, you're gonna need to mess with numbers.

#

You might also want to consider clamping just the X component instead of the whole thing

mellow ledge
#

clampMagnitude expects a vector tho, how am i gonna clamp only the x

split sage
#

I don't know why but my visual studio keeps breaking, I cant put a method undernetth void update or have void update under other things. its missing them dotted lines and unity is reading it differently to what im seeing. Can someone clear up what I might be doing wrong? I have a feeling its using tab to move code to the left but also feel its not that?

mellow ledge
split sage
languid spire
#

you cant clamp the x value of velocity because it's a Property

queen breach
#

why i can't build the game to IOS?

mellow ledge
#

its derived

slender nymph
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

polar acorn
mellow ledge
#

that doesnt change anything. My jump launches me to the sky, and horizontal movement has vry slow acceleration and deceleration

polar acorn
split sage
# eternal falcon

Followed the top link and got it installed, reopening the script results in the same issue

polar acorn
#

You'll probably need to have a different value for how much you add and your top speed

swift crag
#

you don't just install the editor

#

you also install a package, and then configure Unity to use that editor

slender nymph
mellow ledge
#

this feels like a recursive circle to me

#

unless im just really bad at english

polar acorn
#

So, what you need to do is get the velocity into a variable, clamp the x value of it, then set the velocty back to that variable

split sage
#

ooohhh I see the mistake I made, I was trying to change a value for a int but stupidly put the access modifier at the start when it was in void update

mellow ledge
#

ok that makes more sense. ty

slender nymph
heady nimbus
#

Alright, I'm having a weird issue with VSCode set up... It's a new project, I only have 2 scripts right now. The first one I made, everything is highlighted correctly, intellisense seems correct, but the second script in the exact same location, syntax highlighting is off, and intellisense is spotty...

swift crag
#

Has Unity reloaded since you created the second script file?

#

It needs to recreate the project files before you will get any intellisense (beyond text-based suggestions)

heady nimbus
#

It's recompiled, but I haven't fully closed it... I dont' think

swift crag
#

Recompiling should be enough.

#

Close and reopen VSCode. If it's still happening, then show us what the editor looks like with the broken file open.

heady nimbus
#

Yea it's not doing it. I've recompiled, closed VSCode and "Open C# Project"

#

Oh, wait a minute, got a version error for Visual Studio Editor when re-opening this time. That's new. I'll update that real fast. 1 min

swift crag
#

!ide

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

swift crag
#

the instructions require updating the Visual Studio Editor package to 2.0.20 or later.

heady nimbus
#

Yea, I missed the update apparently. Still, that didn't seem to do it. Here's the comparison. They're at the exact same path.

swift crag
#

since you were missing one step, you should really make sure you haven't missed any others.

swift crag
thorn perch
#

Hi again, sorry to bother,
but in my enemyhealth script i am trying to detect collision with "player" which has a Playerhealth script that should allow it to take damage but when doing debug.log on the collision in enemyhealthscript. Nothing comes out, Any idea why ?

ive checked the collision matrix. Everything is colliding with everything.
Player has a tag "Player"

both has rigidbody2d on it and collision components.
istrigger is unticked, both has colliders approperiately sized.

on enemyhealthscript i use the collision detection from my "projectile" and it works perfectly, the enemy dies when hit by projectiles.

but my player doesnt take damage when enemy touches it. Any Ideas?

the link below contains 3x script.

1st: PlayerHealth.CS - not taking damage from Enemyhealth
2nd: Enemyhealth.cs - not detecting collision with player using debug.log

3rd: Projectilebehaviour - this one collides and detect properly with enemye, but why doesnt this same script work on enemy vs player?

https://gdl.space/dovudinaku.cs

swift crag
#

share your !code correctly, please

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

thorn perch
deep glacier
#

You're using OnTriggerEnter

#

Use OnCollisionEnter

thorn perch
# eternal falcon

i dont really understand this comment, can you give me an example?

heady nimbus
#

Yea, I don't see any other missed steps here... I restarted unity and VSCode again after updating that package and checked all the extensions to make sure they're all up to date

#

Wait, what the hell??

#

Uhh... I fixed it. Lmao...

polar acorn
thorn perch
heady nimbus
thorn perch
# deep glacier You're using OnTriggerEnter

this didnt work for me, also note i use a projectile with the exact same portion of the script which does work (ontriggerenter) really appreciate the suggestion though! 😄

deep glacier
#

You said you unticked "isTrigger" right? On both colliders?

#

If that's the case, I'm curious how you're still getting trigger events

thorn perch
polar acorn
thorn perch
polar acorn
#

Do you have 3D colliders?

thorn perch
#

ehm nope

#

its all 2d

polar acorn
#

Then why are you using the 3D collision message

thorn perch
#

Oh actually i think it was a suggestion from someone higher up and it didnt work so forgot to change back xD the original was a direct copy of ontriggerenter2d which works on projectilebehavioru

#

lemme fix it and try again

#

nope still nothign

polar acorn
#

Show updated code

thorn perch
#

will do one sec

polar acorn
# thorn perch

Okay, so, show the inspectors of the two objects involved in this collision

deep glacier
covert nest
#

does OnPointerEnter only work on canvas elements? it doesnt seem to be working at all for my object.

thorn perch
#

screenshots of enemy and player inspector
ffs... it doesnt previiew ? (using snipping tool)

thorn perch
slender nymph
thorn perch
#

I just used copy paste from snippingtool really, did it again with 1 image, now it works dunno why xD

polar acorn
thorn perch
#

but this one works: and its set up the same way, i dont understand

polar acorn
#

If you want to use OnTrigger___ then at least one of them needs to be a trigger

thorn perch
#

oooooh so making a prefab automatically makes it a trigger?

polar acorn
#

Just the fact that you've changed the one in the scene

swift crag
#

The bold text means you have modified that property.

polar acorn
#

But did not change the prefab

thorn perch
#

ohshit,,, i put in a new prefab,, ur right, it is a trigger

#

damn... so i need to use one that doesnt require a trigger (dont want trigger because it makes enemy and player phaze through eachother

polar acorn
#

If you want to detect a collision, use OnCollision

thorn perch
#

thank you for the pointer and helping me on this, sorry im thick as brick when it comes to this stuff

#

now i need to google how to use oncollision xD

#

YESSSSSSSSSSSSSSSSSSSSSSSS its workign !!!!!!!!!!!!!!!!!
@polar acorn
@swift crag
@slender nymph
Thanks guys !!!!

sacred zenith
#

Hello everyone,
In this scenario I have, switch_controllable(GameObject) is declared in CAMERA CONTROLLER. How can I call this function from other scripts?
I tried using delegate/event, but the way I see this is not a good case for that.
Is there a better solution than what I am doing now?

#

Without using the UI reference please

polar acorn
sacred zenith
#

I try at max to keep stuff in code, just in case I delete a gameobject from the scene and to add it back I have to look at all the references it needs and drag them again

#

In the prototyping phase that I am right now, this happens a lot

polar acorn
#

Setting references in code is just as vulnerable to that

#

You could still be attempting to reference something on an object you've deleted

sacred zenith
#

Very true

#

Is this "design" I showed in paint unpractical?

#

Should I approach this from another angle?

polar acorn
#

I don't really know what the image is indicating, honestly

sacred zenith
#

Three separate scripts, I want the ORANGE and BLUE to be able to call the method SWITCH_CONTROLLABLE that is declared inside the RED script

static cedar
polar acorn
#

Yeah, so, having them reference the red script and call it is the way I would go about that

ashen ferry
#

why not a simple singleton

sacred zenith
ashen ferry
#

on camera controller, u can do stuff to it from anywhere then

sacred zenith
#

Nice, will try that

#

If I declare the switch_controllable as static, is that a specific programming pattern?

#

Just that method would be static

ashen ferry
#

just declaring method as static isnt suddenly some pattern kekW singleton isnt about methods u looked up something else

frosty hound
#

Have the bullet keep a list of cookdowns

ivory bobcat
#

Or set the bullet instance to ignore the specific collider after hitting once UnityChanThink

frosty hound
#

That's probably easier if you don't expect the bullets to hit them again at some point (bouncing bullets)

twilit trail
#

hey if i need to hold on to three sets of key-value pairs, what is the best container to use, an array of Dictionaries? I'm having trouble with the syntax.

private Dictionary<string, int>[] appearanceData = [new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string,int>()]; 
#

well it doesn't really need to be key-value pairs, i just need the values, the keys are fixed

ivory bobcat
#

Looks overly complex. What are you doing in particular?

twilit trail
#

but i don't want to access them with magic numbers

#

character customization for three characters. I need to move their appearance data from the scene where they are created in the UI using Images to the gameplay scene where they use SpriteRenderers. The values are things like shader values, etc.

tame thorn
#

I have a sword as a child of the player. I want the sword to move in relation to the player, but its just going to a specific x and y in the map.

public class SwordController : MonoBehaviour
{
    public Transform swordCursor;
    public Vector3 defaultPosition;
    public Quaternion defaultRotation;
    public float rotationSpeed = 5.0f;

    void Start()
    {
        defaultPosition = transform.position;
        defaultRotation = transform.rotation;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (swordCursor != null)
            {
                //Point towards SwordCursor Object
                Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
            }
        }
        else
        {
            // Smoothly move back to default position and rotation
            transform.position = Vector3.Lerp(transform.position, defaultPosition, rotationSpeed * Time.deltaTime);
            transform.rotation = Quaternion.Slerp(transform.rotation, defaultRotation, rotationSpeed * Time.deltaTime);
        }
    }
}
twilit trail
#

i guess a 2d array of ints accesed using an enum would work actually

ivory bobcat
ivory bobcat
twilit trail
#

where the first field is the player index

#

and the second is an enumerated set of fields

soft timber
#

no

tame thorn
tame thorn
#

oop, ty!

#

woa it worked
Im certified genius now

ashen ferry
#

maybe when spawning weaker enemy pass into it reference of bullet which killed stronger one and ignore that bullet in ur take damage method

sacred zenith
#

In Unity, 1 unit is 1 meter. So, if I want a 1.7m character, I can create a cylinder with scale 1.7 in the Y axis?

swift crag
#

assuming the cylinder's height at the default scale is 1 unit, yes

#

This does not appear to be the case.

#

(for the default Cylinder object, at least)

#

it has a radius of 0.5 meters and a height of 2 meters

sacred zenith
#

oh

#

Alright, thank you

light moss
#

I am having a problem with my terrain. As you can see there are weird lines in my terrain, they came out of nowhere and I do not know how to fix it. I am using a material called FixGaps that prevents from screen tearing so I do not even know if the material is the problem or the terrain is.

light moss
#

Can someone please help?

teal viper
tame thorn
#

I have the main camera separate from the player, so when my camera moves vertically, the sword doesnt stay in the middle of the screen
how can i make it follow the vertical movement of the camera?

public class SwordController : MonoBehaviour
{
    public Transform swordCursor;
    public Vector3 defaultPosition;
    public Quaternion defaultRotation;
    public float rotationSpeed = 10.0f;

    void Start()
    {
        defaultPosition = transform.localPosition;
        defaultRotation = transform.localRotation;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (swordCursor != null)
            {
                //Point towards SwordCursor Object
                Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
            }
        }
        else
        {
            // Smoothly move back to default position and rotation
            transform.localPosition = Vector3.Lerp(transform.localPosition, defaultPosition, rotationSpeed * Time.deltaTime);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, rotationSpeed * Time.deltaTime);
        }
    }
}
open apex
#

What's the difference between void start and void update?

summer stump
swift crag
#

right

#

int Foo() returns an integer; string Bar() returns a string

#

and void Baz() does not return anything

#

the methods are named Foo, Bar, and Baz, respectively

cosmic dagger
#

yeah, i don't have a return type either . . .

teal viper
cosmic dagger
teal viper
#

But if you're overriden, the signature must stay the same. We wouldn't even know you were replaced by a different person.

cosmic dagger
#

exactly . . . 😉

open vine
#

Hey guys I was wondering if someone could point me in the direction to make an inventory. For functionality I'm trying to have 3 slots that you can equip in fps fashion.

teal viper
#

See what there is and choose the one that suits you best.

open vine
hushed spire
#

Using an AnimatedTile, need to pause the animation and saw I could do so with something called a TileAnimationFlag.(https://docs.unity3d.com/ScriptReference/Tilemaps.TileAnimationFlags.PauseAnimation.html)
I can't find any information on how to use it, and as expected doing tile.TileAnimationFlags.PauseAnimation() only results in errors stating
"'AnimatedTile' does not contain a definition for 'TileAnimationFlags". Help is greatly appreciated!

teal viper
hushed spire
hushed spire
#

Which seems to go directly against the Tilemap public methods api

teal viper
#

Unless it's only a getter. The docs don't reveal that.

hushed spire
teal viper
teal viper
hushed spire
#

this is the line:

#

animatedTiles[0].AddTileAnimationFlags((-22, 4, 0), PauseAnimation);

#

I realize I need to convert the ints into a vector

#

Still doesn't recognize the method however

teal viper