#💻┃code-beginner

1 messages · Page 524 of 1

snow warren
#

Is there any algorithm or code to do so

naive pawn
#

have you googled image compression at all

#

you could also just reduce its resolution

snow warren
#

All I could find was zip

#

And jpeg

#

But image quality is somewhat lost

naive pawn
#

yes, jpeg is a form of compressed image

naive pawn
#

the info has to go somewhere, either in the file or in the trash

slender nymph
verbal dome
snow warren
naive pawn
#

yeah that's just called heavy compression

snow warren
#

I couldn't find any way to do so

#

I don't wanna use zips

naive pawn
#

but at some point you just can't stuff the data into a smaller space

#

how big is your image? what format is it in? how big will it be shown?

naive pawn
#

oh yeah compress that to at least png then

snow warren
#

Which are I think as uncompressed texture format might take a lot more space

naive pawn
#

of course it would

#

jpg wouldn't support the alpha channel you have

snow warren
#

That's why I am using raw bytes

naive pawn
#

why do you need to use unity

snow warren
#

Cuz I am making a game

#

And I want the user to upload the profile pic to the game server

naive pawn
#

no, why aren't you using an external tool to compress it and then use the result in unity

snow warren
#

But due to large size the image is not uploaded

naive pawn
#

let the user upload jpg or png

#

don't use the raw pixels from that

snow warren
#

Unity 6 no longer supports encode to with already compressed images

naive pawn
#

why do you need to reencode anything

#

ok.

#

step back

#

please describe what you're doing

#

because you're leaving out quite a bit of detail here, this is a case of xyproblem

snow warren
#

To convert the already running texture into a PNG bytes

naive pawn
#

it's already a png

#

you let the user upload a png

#

what are you trying to convert to a png

snow warren
#

But as the image uploaded is already compressed
So unity 6 won't be able to encode it

#

Nor I can get the simple compressed bytes

#

I could only get raw bytes

naive pawn
#

why would you want to

snow warren
naive pawn
#

you cannot support all formats

#

that's just not feasible

snow warren
naive pawn
#

just stick to what unity supports directly, or just let the user convert it themselves

snow warren
#

Ok

#

Let's suppose I upload a PNG that is somewhat the size of 20 mbs

naive pawn
snow warren
#

I still can't send 20 mbs to the server

#

The max I could send is 2 to 3 mbs

naive pawn
snow warren
naive pawn
#

very little

snow warren
#

An estimate

languid spire
#

you honestly dont know how to calculate that?

naive pawn
#

i just made one and it took 6kb

snow warren
#

I am not that experienced sadly

languid spire
#

basic math

snow warren
#

Ok I will try this one

naive pawn
#

i made another one, with much more data. 234kb.

#

a 4-channel 8-bitdepth bmp (aka uncompressed rgba32) at 512x512 would be 262144 pixels at 4 bytes per pixel, coming out to 1048576 B, or exactly 1 MiB
png and jpg are compressed, so for legit profile pictures that aren't just pure random noise, it'll be much smaller than that

#

you're really overcomplicating a straightforward task.
have the user upload a pretty small, compressed image, probably just png or jpg, and use that directly.
you don't need to support random formats that a vast majority of people aren't going to care about. if they want to use that image, they can convert it themselves.

languid spire
#

if you really want to reduce the size, switch to a 256 colour palette format which will reduce the size by 75%. You could also add RLE compression to that to reduce size even more

prisma jolt
#

this if statement is not being run even though the rotation is above 90 (spine is a Transform). Any help?

naive pawn
#

is it even being reached? try a debug before it

languid spire
wintry quarry
prisma jolt
#

how do i check for rotation then?

wintry quarry
#

what are you trying to determine exactly

#

like "is the player facing east or west"?

#
bool playerIsFacingEast = Vector3.Angle(player.fransform.forward, Vector3.right) < 90f;```
#

more generally you can use Vector3.Angle or Vector3.Dot to compare the player'sfacing direction with any known direction

#

this is more robust than trying to mess around with euler angles.

prisma jolt
#

alright

wintry quarry
#

The details depend on exactly what you're trying to determine

#

so step one is to make sure you can express that.

prisma jolt
wintry quarry
#

that is very vague

#

what does it mean to be facing 90 or -90 degrees

#

degrees are not directions

prisma jolt
#

if the y value is 90 or -90

wintry quarry
#

the y value of what

prisma jolt
#

the spine

wintry quarry
#

YOu mean "if the rotation of the object around the global y axis is within so and so a range"

wintry quarry
#

I think you're getting bogged down in the details of euler angles and not thinking about, semantically, what you actually are trying to figure out

#

what's the end goal here?

#

like "I want to know if my player is upside down" for example

#

or "I want to know if my player is facing right or left"

prisma jolt
#

an animation is supposed to play if the player looks too far to the right or left so it doesnt look awkward

wintry quarry
#

so left or right relative to what?

#

The global axis directions?

#

or something else

prisma jolt
#

sorry i dont know what that means

wintry quarry
#

"left or right" is very vague

#

If you're looking south and i'm looking north, left and right mean different things to each of us

#

in fact they're exactly the opposite

#

I'm asking you to be very specific about what you actually want here, because you need to be to write the code properly.

undone plume
#

how to access the camera targetTexture? unity documentation said i can access it like this but it doesn't work..

wintry quarry
#

Your inability to express your meaning is part of why you are struggling to write the code.

wintry quarry
#

Given that StartCoroutine is showing up in IntelliSense, I would guess you wrote your own Camera script (public class Camera) which derives from MonoBehaviour. THat is causing the confusion here.

undone plume
wintry quarry
#

You would have to either rename your script that you named Camera or declare your field as public UnityEngine.Camera cameraB;

#

or, third option, using Camera = UnityEngine.Camera; at the top of this file.

#

I would recommend simply renaming your script though

prisma jolt
wintry quarry
#

I vaguely understand but the exact code details depend on your exact meaning

#

So you should be trying to explain. Maybe show some screenshots or diagrams if that helps.

#

For example I don't even know the layout/camera view etc of your game

#

i don't know if it's a top down 2D game or a first person shooter

#

Or a 3D RTS

#

it could be anything

#

I shared a code snippet above that handles the case of a 3D player looking around and the right/left being relative to world space. But without knowing how your game actually works that may or may not actually be helpful for you.

prisma jolt
#

Hey. In this quick tutorial, I am going to teach you how to create a True First Person Character using Unreal Engine 4. The character will lean properly to follow the players' camera movements, as well as playing proper turn animations.
This works well for First-Person and Third-Person games

Project File: https://drive.google.com/open?id=1GDjhx...

▶ Play video
prisma jolt
#

at the point i put in the link

wintry quarry
#

yeah but like

#

what about it.? The rotation of the torso or something?

prisma jolt
#

yes

wintry quarry
#

That can happen at any rotation at all

#

since it's an FPS and you can face any direction

#

what you care about has nothing to do with the player object's current rotation

#

you're going down the wrong track entirely

#

all you need to do is look at the input

#

I guess mouse horizontal input in this circumstance

#

to determine if you are rotating the player right or left (clockwise or counterclockwise)

prisma jolt
#

yeah but the torso and legs shouldnt rotate until a certain point is reached

zealous geode
#
public class Aquarium : MonoBehaviour
{
    public static Aquarium Instance;

    [SerializeField] private List<FishTank> Fishtanks = new();

    [SerializeField] private Dictionary<FishData, int> FishInventory = new Dictionary<FishData, int>();

    [SerializeField] float Money = 0f;

    private void Awake()
    {
        if(Instance != null)
        {
            Destroy(Instance);
        }
        Instance = this;
    }

    private void LoadInventoryKeys()
    {

    }

Hello, I want to know how I could load the dictionary on this class with the keys that would later the player will use to manage the fishes on the aquarium, as buying and placing the fishes on different tanks. Thing is, right now the dictionary uses as key the FishData ScriptableObject. For this purpose I don't know if it would be better to use the prefabs of each fish or just keep it with the FishData.

wintry quarry
#

as for what to use as the key, we don't really have enough information here to make an informed choice

#

The prefab reference might be a good idea

#

or if you have a ScriptableObject, that reference would be too

#

Probably the FishData SO

#

if that SO has a reference to the prefab

zealous geode
#

I see. Right now I don't have a reference for the prefab on the SO. I'm trying to load the keys for the player to have a catalog to check the amount of fishes they have. These amounts would be used later on to "pick-up" an X quantity of fish to place them on a fish tank and vice-versa.

wintry quarry
#

Do you have one prefab per fish

#

or is there a single Fish prefab that uses the SO reference when being spawned to determine what kind of fish it is

zealous geode
#
public class FishData : ScriptableObject
{
    public enum Type
    {
        Saltwater,
        Freshwater,
        Migratory
    }

    public Type _type;
    public string Name;
    public int Health;
    public float Hunger;
    public int Min_Temperature;
    public int Max_Temperature;

}

public class Fish : MonoBehaviour
{
    [SerializeField] FishData data; 
    public void UpdateHealth(int value)
    {
        data.Health += value;

        if(data.Health < 0f)
        {
            data.Health = 0;
        }
        else if(data.Health > 3)
        {
            data.Health = 3;
        }
    }
}

Right now that's what I have referring to the fish object. I was thinking of doing different prefabs for each fish, as, for now, I wasn't expecting to have a lot of them, but, what would you reccomend?

wintry quarry
#

and use FishData for your inventory / Aquarium

zealous geode
#

I see. Thank you so much, I'll check going for the first option.

brave current
#

hey

#

public class ThirdPersonMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float turnSpeed = 700f;
    public Camera playerCamera;

    private float inputX;
    private float inputZ;
    private Vector3 moveDirection;

    private Rigidbody rb;

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

    void Update()
    {
        inputX = Input.GetAxis("Horizontal");
        inputZ = Input.GetAxis("Vertical");

        moveDirection = (playerCamera.transform.forward * inputZ + playerCamera.transform.right * inputX).normalized;

        if (moveDirection.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSpeed, 0.1f);
            transform.rotation = Quaternion.Euler(0, angle, 0);
        }
    }

    void FixedUpdate()
    {
        rb.MovePosition(transform.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
    }
}
#

my character can juste rotate

#

its not normal

languid spire
#

you are doing rotation with the transform, use the rigidbody

#

also don't use transform.eulerAngles as input into any calculation

quick pollen
#

I think the main reason is that the camera's x axis becomes negative if I tilt the camera vertically below a certain point

#

but I have no clue how to fix it

digital dawn
#

i am wanting to create a space game like Kerbal Space Program where you build a rocket and can fly out of planets, orbit etc. I already have the basic rocket physics and building but i am really struggling to get the planets right/have no idea how to do them. how could i make it look like you are on an expansive terrain (unable to see planet curvature) but when you start to fly out of the planet and get higher etc it starts to get smaller and looks like you are exiting the atmosphere

sharp wyvern
still ingot
#

Hi! I'm making a 2d platformer game where you can enter buildings, but I've realized my player always starts at the default position from the scene editor. How may I go about creating a spawn system that allows the player to show up at the entrance and exit points of the building when coming and going??

digital dawn
quick pollen
sharp wyvern
quick pollen
#

although im not sure its a good idea having something like entering houses be handled by scene managers

#

usually just teleporting the player is fine

#

you dont want a loading screen between every house enter probably

still ingot
brave current
glad shuttle
#

Hello! I have a Animated Bird sprite (animated using sprite-sheet) and all I want is for the bird to scroll across the screen. How could I accomplish this?

meager gust
# brave current I need to replace ?

To correctly move a rigidbody, you need to either use AddForce(), or set it's velocity directly.
Using MovePosition is bypassing the physics engine and forcefully setting the position.

To correctly rotate a rigidbody, you need to use AddTorque, or set the angular velocity.
Keep in mind that sometimes it's OK to incorrectly rotate a rigidbody. Like if you have a snappy first person controller, torque or angular velocity might feel very weird.

wintry quarry
glad shuttle
#

im just saying the bird is animated

#

but i want the bird sprite to scroll across the screen

wintry quarry
#

Ok the fact that it's animated is irrelevant

#

give it an empty parent object

#

and put a small script on that parent object to move it across the screen

glad shuttle
#

alright

light briar
#

Anyone have recommendations for an asset from the asset store to handle json files?

I'd like to be able to process the following json into seperate lists, so I'd have a species, prefixes, and prefixes2 list

wintry quarry
#

Unity's built in JsonUtility would handle that just fine

light briar
#

Any tips on how? Because what i could find about it on google I couldn't find anyway to parse it like that sadge

wintry quarry
#
[Serializable]
public class MyExampleClass {
  public List<string> species;
  public List<string> prefixes1;
  public List<string> prefixes2;
}

void Start() {
  string myJsonText = <however you get your json text. Read it from a file or whatever>;
  MyExampleClass ex = JsonUtility.FromJson<MyExampleClass>(myJsonText);
}```
#

It's a pretty straightforward usage of JsonUtility

light briar
#

Ah gotcha I didn't realize I could use it like that, thank you

wintry quarry
#

I mean

#

how else would you use it

light briar
#

I don't think you're wrong I just wasn't thinking about it in the right way kekW

light briar
#

I obviously can't instance a new singleton.

I guess I could create another class just for it but that feels kinda bloaty and I'd like the lists in my singleton if that makes sense

#

I ended up deciding on using an interface

woven dust
#

Hello, im a noob and im having audio issues

#

basically i have a little box collider that the player stands on and i have it trigger a sound effect, but im getting 0 sound no matter what I try

#

the code goes through and adds to the counter on the debug.log, and the audio file is supported, not at a stupid Hz (ive tried 44,100 Hz), and I am honestly just lost

#

im on unity version 2022.3.13f1 <DX11>

north kiln
#

Calling Play repeatedly will cause the clip to constantly restart.

#

your code is quite confusing to read with the lack of braces and loads of booleans

wintry quarry
#

public MyExampleClass myField;

#

you wouldn't deserialize directly into the MonoBehaviour

#

that's not gonna work

woven dust
#

u da goat

#

:)

radiant glen
#

Making a bow that shoots a arrow wherever the mouse is, I have the bow rotate towards the mouse as well but the rotate point is on the corner of the bow, how can I switch it to the middle of the bow so it looks better?

rocky canyon
#

Open Sprite Editor in the texture's inspector
Move the blue circle and Save it

timber tide
#

looks like the pivot is where you're rotating

#

rather, not centered to the bow

brave current
gray jungle
#

Hey guys I'm using the new input system to get the axis for vertical and Horizontal inout but the thing is I don't know how to normalize the diagonal movement of my character. I do know how on the legacy input system tho. I'd appreciate the help 😄

private void FixedUpdate()
{

    Movement();
    Animation();
    shootAnimation();
}
void Movement()
{
    rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
}
public void MoveInput(InputAction.CallbackContext context)
{
    movement.x = context.ReadValue<Vector2>().x;
    movement.y = context.ReadValue<Vector2>().y;
}
keen dew
#

The same way? I don't see why it would be any different

gray jungle
#

oh wait right XD im so dumb

#

so basically I just had to do it like this

void Movement()
{
    movement.Normalize();
    rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
    
}
feral oar
#

fellas i am experimenting with a 3rd person camera on a character controller, and i'm following a tutorial to get it set up. before following the video, i had some very basic movement set up that utilized the input manager's "gravity" and "sensitivity" settings to get the player to smoothly accelerate and decelerate.

when following the tutorial, however, i have lost the acceleration and deceleration, and i'm not sure what part of the code is causing it.
here's a paste of both the tutorial's code and mine: https://paste.ofcode.org/pBRpiCBqqjVjHDJbDdXpnU

i took out part of the tutorial's lines that including normalizing values, as i've learned that can cause the snappier movement that i'm trying to avoid, but that didn't get me where i wanted to be

meager gust
#

2.) Time.fixedDeltaTime isn't really needed in FixedUpdate. FixedUpdate is already framerate independent.

keen dew
#

It is needed for MovePosition (but not for AddForce or setting velocity)

keen dew
#

Because MovePosition sets the position directly. So if you change the fixed update step or timescale, it'll start moving at a different speed.

opal zealot
#

Is there a way to include a double jump on my Input System Controls?
I'm unsure if it should be in PlayaCharacterNormalLocomotionInput(Since it has my OnJump function) or PlayaCharacterNormalController(Since its where most of the character movement takes place in)?

turbid shell
#

how do I make a menu stay on the center of the screen?

rugged needle
#

How could i start learning this engine ?

quaint thicket
burnt vapor
eternal falconBOT
#

:teacher: Unity Learn ↗

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

burnt vapor
eternal falconBOT
woeful schooner
#

am i insane or should this be returning a boolean, not just it's own type?
playerTargetHit is cast as a raycasthit2d, i just didn't want to send a third image for one line

runic lance
runic lance
#

that means you can simply assign that result to a bool variable or use in inside an if statement

woeful schooner
burnt vapor
#

Classic Unity

#

Implicit conversions

#

Why not just add a field/property

woeful schooner
#

speeds it up if you know how it works i suppose
but yeah it sucks if you're figuring it out

runic lance
#

not sure why this API is different from Physics.Raycast with the out paramter

burnt vapor
#

Yeah it would help beginners because implicit cnversions is the most unclear thing in the world

#

Especially here it doesn't even make sense. It's just some weird convenience

woeful schooner
burnt vapor
#

Would be nice if they called it TryRaycast but at least it uses the proper convention for a predicate like this

night raptor
burnt vapor
#

It would be more clear because by convention .NET methods that begin with Try always return a boolean indicating success

#

And if they return false then it should be assumed that you can't use any of the out parameters

night raptor
#

I guess

burnt vapor
#

And in the case of Physics.Raycast it appears that out RaycastHit hitInfo will be null or at least its default value if the method returns false

#

In modern .NET you'd also make sure to annotate your out method with [NotNullWhen] or [MaybeNullWhen] to better help with nullabillity. In the case of Unity this also works, but nullabillity is still completely optional until they update their codebase

#

Useful to know; this type of pattern also exists for AsFoo() to indicate a method casts to a different type, and ToFoo() to indicate the method allocates a new object in order to return the type.

verbal dome
#

I agree with Aleksi, Raycast doesn't "try" to raycast, it always does perform a raycast
It would only make sense if it would be called TryGetRaycastHit

orchid bridge
#

hello guys

#

🙂

naive pawn
#

this server is for helping you make your own thing, not to make stuff for you

#

if you're just looking for examples or whatever, try google

#

if you're having issues with your own implementation, ask about those issues

verbal dome
orchid bridge
#

enemy script not working

#

i did but enemy is not dying

#

even animator also not working properly

naive pawn
#

ok, ask about those issues

#

please provide actual info about what's going on there

languid spire
#

and type in full sentences

orchid bridge
#

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

public class enemydie : MonoBehaviour
{
public int HP = 100;

public void TakeDamage(int damageAmount)
{
    HP -= damageAmount;
    if (HP < 0)
    {
        // play death anime
        animator.SetTrigger("die");
    }
    else
    {
        //play get hit anime
        animator.SetTrigger("damage");
    }

}

#

anything wrong in my code ?

#

enemy is coming to me

#

i shoot

#

but enemy not disappearing , enemy is capsule

cinder schooner
#

i don't see any code for dissappearing the enemy, just setting a trigger

naive pawn
#

!code

eternal falconBOT
naive pawn
#

but yeah you didn't tell it to disappear, so why would it disappear

orchid bridge
#

!code

eternal falconBOT
orchid bridge
#

still not working

naive pawn
#

..did you change anything?

#

"not working" doesn't give us any information

#

we can't help you if we don't actually know what the problem is and how you're trying to solve it

orchid bridge
#

my actaul problem is

#

i am learning how to code

#

new to code

hexed terrace
naive pawn
honest sedge
#

how to fix

fickle plume
#

@honest sedge Don't cross-post. You were pointed to the channel where to post

burnt vapor
burnt vapor
verbal dome
#

Wouldn't that like break all existing code?

burnt vapor
burnt vapor
naive pawn
burnt vapor
#

I am about 99% sure that if Unity were to release the .NET update they have been working on, they would fix all this

#

So it's somewhat useless there, but it would work good with your own code

naive pawn
#

i mean... i guess that is what i said

#

it's [mask](link), lol

burnt vapor
#

Yes, I have that. It doesn't like my link apparently

naive pawn
#

no, you have the link and mask swapped

burnt vapor
#

Oh, oops

#

I see what you mean now

naive pawn
#

lol it does take a while to remember the order. i struggled a quite a bit with the order of brackets/parens lol

burnt vapor
#

Regardless, obviously this all doesn't apply with the raycast here. Though I do think it would point out the possible null reference with RayCastInfo (unless it's a struct, is it?)

#

Unity would have to use the [NotNullWhen] attribute to fix it.

verbal dome
#

You mean raycasthit? It's a struct yes

naive pawn
#

you mean RaycastHit?

verbal dome
#

In 2D it has a implicit bool cast so you can do if(hit) tho

runic lance
prime hinge
#

umm guys can i ask about how to let vscode underline my errors?

rich adder
eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

vague adder
#

if(Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
{
FireLaser();
}

void FireLaser()
{
    _canFire = Time.time + _fireRate;
    Instantiate(_LaserPrefab, transform.position + new Vector3(0, 0.8f ,0), quaternion.identity);
} 

}

#

no errors or anything but for some reason the cooldown system isnt working, i couldnt understand why

rich adder
#

if thats truly your code as is

#

you might want to configure your IDE

burnt vapor
eternal falconBOT
burnt vapor
#

When you've done that your editor will inform you of the issue.

vague adder
#

it already underlines errors though

rich adder
vague adder
#

it doesnt

#

i just wrote what was shown in a course

#

this is what yall mean by underlining right

rich adder
#

well you are using the quaternion from another namespace then

#

probably UnityEngine.Mathematics

vague adder
#

oh yeah

#

i didnt realise that

#

the cooldown system still doesnt work though

rich adder
#

it should still work though

#

they have implicit conversion

#

just from what I see here, I think your issue is that canFire never starts as true

#

assuming the code is actually running at all which you still haven't verified

#

wait canFire is not even a bool ?

#

naming confusion is confusing

#

why is a float named canFire

vague adder
#

lemme check the course again

#

just to make sure i wrote it right

rich adder
burnt vapor
#

Your editor seems to be able to highlight C# specific semanthics and symbols

#

But it doesn't even know if it exists

#

So no, it's not configured

vague adder
rich adder
burnt vapor
#

So configure it first, then come back

#

Hover over quaternion, and tell me what it says

rich adder
#

they just pulled the wrong namespace for Quaternion

#

its from mathematics namespace but works just fine

vague adder
#

yeah

rich adder
#

that aint the issue, the function is probably not even being called.

burnt vapor
#

Fair

vague adder
burnt vapor
#

In this case I suggest you log if your if statement is entered at all

rich adder
#

yeah put some logs and check what is actually happening

burnt vapor
#

And then also log if the Awake of whatever _LaserPrefab is is being called, in one of its scripts

vague adder
#

alrighty

burnt vapor
#

Important thing is pinpointing what specifically doesn't work

rich adder
#

canFire implies a bool at first glance, if your variables dont exactly describe what is at first glance its not a good name

vague adder
rich adder
#

probably bad course

#

good variable names should be most important

#

anyway check the logs, see whats going on in the code

vague adder
#

its an official authorized course tho

rich adder
vague adder
#

this thingy

rich adder
#

ah yes. Udemy trash

vague adder
rich adder
#

where exactly did you put this script ?

vague adder
#

just these

rich adder
#

No i mean which gameObject

#

cause transform.position is relevant

#

you can verify it spawned something just by pausing the game after pressing space, check the hierarchy for new object

burnt vapor
#

What object is this script on?

vague adder
#

its in the blue cube, its supposed to be able to shoot a laser whenever i press space (with a cooldown of 0.5 sec)

#

im trying to make one of those galaxy shooter games

rich adder
burnt vapor
#

Please get the return value of Instantiate and use it as the second parameter in Debug.Log, like this:

Debug.Log("Object: ", spawnedObject);
#

Then click the log message

#

I assume your cooldown system works then right?

#

It's just that the game object doesn't appear

#

So if you do this we can verify if the spawned gameobject is actually there still

vague adder
#

instantiate and everything else works but just the 0.5 cooldown doesnt work

burnt vapor
#

That would be the only thing left

#

Or does it log each time?

rich adder
# vague adder

ok but i meant the blue cube because wantedto see the inspector values

burnt vapor
#

I'm a bit confused by your message

vague adder
#

im quite confused aswell

#

im halfway of a beginner, i dont really know how to log _firerate

rich adder
# vague adder my bad

so it shoots once and stops shooting or it keeps shooting fast on every tap ?
because 0.15 is pretty small amount of time

burnt vapor
vague adder
rich adder
#

make the firerate longer like 1 sec

#

and check its actually doing anything

vague adder
#

oh fuck

#

fuck

#

fuck my brain

#

everything works fine

#

i thought the cooldown was 0.50

#

my bad

#

it works correctly i just forgot that its 0.15 and not 0.50

rich adder
#

always check the inspector values if you have them also in code

vague adder
#

thank you both for the help

rich adder
#

inspector always overrides anything you initialize with

orchid bridge
#

i have been trying from 2 days continuosly but still i unable to code enemy , when enemy got attacked by bullet in unity he doesn't disappear , can anyone help me ? unity pros

steep rose
#

you need to show use some !code and to debug

eternal falconBOT
rich adder
orchid bridge
#

if i hit enemy with bullet the capusle should disappear

orchid bridge
rich adder
#

read it

steep rose
#

read it

rich adder
#

open bin site link, paste the code, save , send the generated link

orchid bridge
#

my scripts

rich adder
eternal falconBOT
#

mad No

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

twilit rivet
#

yo

orchid bridge
steep rose
#

you would use the collision.transform.gameobject to destroy the gameobject it just hit

rich adder
orchid bridge
#

link ?

rich adder
twilit rivet
#

yooo

orchid bridge
#

yea

steep rose
rich adder
orchid bridge
twilit rivet
steep rose
#

C# is C#, it just uses unitys api

rich adder
#

unity is just an API that uses c#

steep rose
#

lol

twilit rivet
#

lol thanks

orchid bridge
#

did you got it ?

rich adder
#

yes

twilit rivet
orchid bridge
twilit rivet
#

so learning c#

#

a normal like

orchid bridge
#

i am new to this things

rich adder
#

did you click the link I sent?

twilit rivet
#

likee ahh 4

steep rose
rich adder
steep rose
#

if you learn unitys API you will understand the API

orchid bridge
steep rose
#

read it

rich adder
twilit rivet
steep rose
#

if you understand C# and unitys API you will be fine

twilit rivet
#

also one more questino

summer shard
#

do y'all sort your scripts into folders?

rich adder
twilit rivet
#

unity does not compile after i save the file in vs studio

rich adder
steep rose
orchid bridge
#

why there is no voice channel or some screen sharing type , so i can tell my problems easily

twilit rivet
summer shard
rich adder
steep rose
#

!ide

eternal falconBOT
summer shard
naive pawn
#

integrated development environment, aka the text editor that knows what code is

rich adder
steep rose
#

But it is not a text editor

rich adder
#

also make it a habit to google things you don't know @twilit rivet

naive pawn
#

good organization isn't just for other people, it's for your future self

rich adder
#

You're the one thats going to be working on it, figure out what works best for you

#

if you're with a team, agree on a specific structure. Trial and error, what works best for you

rich adder
twilit rivet
rich adder
#

stay away

#

you will be copying things you won't understand and that won't help you gain skills

twilit rivet
rich adder
rich adder
twilit rivet
#

thanks guys

rich adder
#

you wont learn anything frankly

twilit rivet
#

byee:>

steep rose
# orchid bridge

anyway you need to use the collision.transform in the OnCollisionEnter, also why are you using Vector3.Movetowards in Moveposition?

orchid bridge
#

you guys didn't understand my problem

rich adder
steep rose
#

well what is it? I thought you said your bullet is not destroying the enemy

rich adder
#

so is the bullet destrying itself ?

orchid bridge
#

bullet is sphere , they move forward , if they hit or pass through a enemy capsule (code) it should disappear

rich adder
#

if so then you just need to add one more Destroy method for enemy

steep rose
#

and use the collision.transform

rich adder
orchid bridge
#

destroy methods

orchid bridge
steep rose
rich adder
#

ohh alr

rich adder
steep rose
orchid bridge
#

how to debug ?

rich adder
#

you know if you followed the steps to what I linked it would tell you this.

orchid bridge
#

ok i got it

orchid bridge
#

is there any vc channel here

steep rose
#

no

orchid bridge
#

i will share it

#

better discuss by screenshare

steep rose
#

navarone and I already gave you your answer above

wintry quarry
steep rose
wintry quarry
#

anyawy you should not be using MovePosition to move your bullet. Just set its velocity (and make sure it's not kinematic)

#

likewise it should not be rotated via the Transform

#

only via the Rigidbody

orchid bridge
#

atleast i need some hints

rich adder
#

seems bullet is

wintry quarry
rich adder
#

MovePosition is the enemy script i think

orchid bridge
#

if anyone like to help me , they can dm me

wintry quarry
#

the enemy should also not move via MovePosition and should not rotate via the Transform

rich adder
steep rose
#

for rigidbody you would use LinearVelocity, Addforce, or moveposition (as long as it is kinematic), NO translation as that causes unreliable collisions

rich adder
#

if you truly want help, LISTEN/READ whats being said to you

orchid bridge
#

from 2 days i didn't sleep well , unable to think

rich adder
#

then get some sleep

#

never good idea to code tired

polar acorn
steep rose
#

Their bullet is not destroying the enemy when hit

orchid bridge
#

bullets going through capsule and capsule are still alive , they should be dead and disappear , shouldn't be visiblle

polar acorn
rich adder
#

does the bullet even have a collider

polar acorn
steep rose
#

3 correct answers have just been said, but also we gave you your answer already

#

your bullet should have a collider and a rigidbody as well (since you are using addforce)

rich adder
#

being tired you won't be able to follow our help, it will appear more confusing than what it is. A well rested mind goes a long way in development

orchid bridge
#

so understood now why NVIDIA CEO told in future there will be no need of coding

#

coding is like notlikethis

steep rose
#

only when tired and when you do not understand it

wintry quarry
#

Everything you're not experienced at seems like notlikethis

rich adder
wintry quarry
#

Pole vaulting is like notlikethis

orchid bridge
steep rose
#

go sleep

rich adder
#

get some proper rest, come back to it. You will be able to better approach the problem

steep rose
#

and you will have a fresh mind when woken up

rich adder
#

We don't say it for fun, its from experience

buoyant finch
#

hello so I have a healthbar like the first image for my game but when I run the script the healthbar turns black like the background I have in 1st and on 2nd is the green health using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HPBar : MonoBehaviour
{
[SerializeField] GameObject health;

public void SetHP(float hpNormalized)
{
    // hpNormalized should be between 0 and 1
    health.transform.localScale = new Vector3(hpNormalized, 1f);
}

}
this is the script pls help

naive pawn
#

sounds like it's being set to 0 and just showing the background

slender nymph
#

you should look into using a filled image for the health bar instead of modifying the scale of the object. much cleaner, and will look much better too

buoyant finch
#

filled image like in?

slender nymph
#

as in an image component set to the Filled type

buoyant finch
#

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

public class HPBar : MonoBehaviour
{
[SerializeField] GameObject health;

public void Start()
{
    health.transform.localScale = new Vector3(0.5f, 1f);
}

}
btw I also tried this

hexed terrace
#

please share !code properly 👇

eternal falconBOT
naive pawn
#

backticks are to the left of the 1 key on most keyboards.

hexed terrace
#

Just copy and paste it

naive pawn
#

or you can copy them from the embed if you can't find yours

buoyant finch
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HPBar : MonoBehaviour
{
    [SerializeField] GameObject health;

    public void Start()
    {
        health.transform.localScale = new Vector3(0.5f, 1f);
    }
}
hexed terrace
#

there we go

#

you do not want to set the scale of the gameobject for a health bar

buoyant finch
#

no its just for the testing as the gameobject health

hexed terrace
#

that doesn't make anything clearer

buoyant finch
vague phoenix
polar acorn
naive pawn
vague phoenix
#

Sorry

#

But if someone could help it would be great 😊

buoyant finch
#

wait I will show what I mean

hexed terrace
vague phoenix
buoyant finch
polar acorn
#

Like we've said a ton of times

#

I linked you the property to use

buoyant finch
#

but wouldn't I have to do it for all states of the hp?

polar acorn
#

what

naive pawn
#

play around with it

#

see how it behaves

buoyant finch
#

like if I want to show it reducing I will have to do it for every time the hp decreases right

buoyant finch
polar acorn
naive pawn
#

you said it was an image component, right?

slender nymph
buoyant finch
naive pawn
#

you don't need an actual image

#

you just need the image component

naive pawn
#

that's a message link

slender nymph
#

i linked to a specific message

buoyant finch
#

ok thank you for helping me everyone hope you have a good day/night

polar acorn
naive pawn
#

you don't even need to do that

polar acorn
naive pawn
#

wdym it's literally clicking the "hidden" button and typing "square"

polar acorn
naive pawn
#

fair

glossy eagle
#

Hello. One question, for the Color variable type, the red value from what value to what value does it have to be please?

#

like is it from 0 to 1 or from 0 to 256?

cosmic dagger
eternal falconBOT
glossy eagle
#

okay thanks

queen adder
#

hey ive got 2 questions regarding my code. 1: Why isnt the cooldown working properly? it makes you unable to move when u try spam clicking (im guessing its performing the routine so many times that it overlaps) 2. How can i make it able to read only one input at once?

#

heres the code:

cosmic dagger
rich adder
#

Store it in a variable

cosmic dagger
#

you should store it in a coroutine variable. that way you can check if it's null (which means it's already running) . . .

#

yeah, what they said . . .

queen adder
#

would that also fix the second issue?

cosmic dagger
#

not sure why you wait for .01 secs.. just yield a frame . . .

queen adder
#

let me specify. the issue is that if you press A and W at the same time it throws you at a random point somewhere in the middle (form 0 to 1.333 for eg.)

#

and i dont want the player to move on the diagonal

cosmic dagger
#

you start the coroutine in two different places:

  • Update
    when Movement is performed and CooldownOn is false

  • Move
    if you can move, Cooldown is called, but you're not calling it as a coroutine. Did you mean for this?

wintry quarry
#

You must use StartCoroutine to start a coroutine

queen adder
#

since i called it wrongly in the first place and fixed it just now

wintry quarry
#

also your movement is just accepting ctx.ReadValue<Vector2>() as the parameter

#

if you have a joystick that can be diagonal

cosmic dagger
wintry quarry
#

you should process that vector to make sure it's only going horizontal or vertical

cosmic dagger
#

☝️ exactly this . . .

queen adder
#

yeah its exactly what i asked about

wintry quarry
#

i mean.. write some simple code

#

a few if statements

#

check which axis has a larger absolute value for example

cosmic dagger
#

you have all the information needed (the ReadValue<Vector2>()) . . .

wintry quarry
#
Vector2 ManhattanizeInput(Vector2 input) {
  float horizontal = input.x;
  float vertical = input.y;

  Vector2 output;
  if (Mathf.Abs(horizontal) > Mathf.Abs(vertical)) {
    output = new(Mathf.Sign(horizontal), 0);
  }
  else {
    output = new(0, Mathf.Sign(vertical));
  }

  return output;
}```
Something like this?
queen adder
#

yeah that would work

wintry quarry
#

there's probably also a built-in processor in the input system. I think "digital" or whatever does it

queen adder
#

ill be able to do it from here

#

thanks you 2

rancid tinsel
#

how does OnDestroy actually work? Will unity wait to destroy the object until everything in OnDestroy is finished?

cosmic dagger
eternal falconBOT
polar acorn
#

If you're asking whether it's called before or after the actual destruction, it'd be before

rancid tinsel
rancid tinsel
#

does anyone know a better approach for this? this doesn't seem very efficient + throws errors when leaving playmode

#

essentially i want any attached SoundObject objects to be put back into the pool before the parent is destroyed (in this case the SoundObject is used to play a grunt on a person, but if that person is destroyed i want the SoundObject back in the pool)

jaunty bay
#
{
    public PlayerInputActions playerControls;
    public InputActionReference interact;
    private bool isInteracting = false;
    private bool isPlayerInRange = false;
    protected override void OnCollided(GameObject collidedObject)
    {
        if (collidedObject.name == "Player" && isInteracting)
        {
            OnInteract();
            isInteracting = false;
        }
    }

    protected override void Update()
    {
        base.Update();
        Debug.Log("isInteracting is " + isInteracting);
    }

    protected void OnEnable()
    {
        interact.action.performed += PerformInteract;
    }

    protected void OnDisable()
    {
        interact.action.performed -= PerformInteract;
    }

    protected void PerformInteract(InputAction.CallbackContext context)
    {
        if (isPlayerInRange) 
        {
            isInteracting = context.performed;
        }
    }

    protected virtual void OnInteract()
    {
        Debug.Log("OnInteract() is executed.");
    }

    // Detect when the player enters the trigger area
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            isPlayerInRange = true;
        }
    }

    // Detect when the player leaves the trigger area
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            isPlayerInRange = false;
            isInteracting = false; // Reset interaction when the player leaves
        }
    }
}```

am i just trippin or is there any better way to handle this kind of interaction system
rancid tinsel
#

the 2nd one is from calling OnDestroy

#

i think both are actually

cosmic dagger
# rancid tinsel

probably because you're returning objects to a pool (that gets destroyed along the scene) when you exit playmode . . .

rich adder
cosmic dagger
#

yeah, try to use events instead. that should work . . .

rich adder
#

Basically my child object that I parent to this, listen to event invoked by this object when you call Destroy on it

rancid tinsel
#

im so confused tho, how is this different from OnDestroy if it happens before the object is destroyed?

rich adder
rancid tinsel
#

... i thought it doesn't start destroying until everything in OnDestroy is finished though? is that not the case?

#

maybe i misunderstood earlier

rich adder
#

once you call Destroy the object is marked for cleanup for the GC , once the GC comes to collect the object is cleaned but if you did a null check the object would probably show nul

rancid tinsel
#

wait i just realised - if its already "marked" because its parent is being destroyed, is there no way to save it?

#

because that was the idea with my approach

rancid tinsel
#

that makes more sense

normal coyote
#

hey guys, can someone help me? a friend of mine is coding a game, and has found this bug, where the [SerializeField]; GameObject and Interactable is not getting the green color (idk how to name it LMAO), he asked for my help, but i've never seen something like this happening with me, any ideas of what is causing this to happend?

wintry quarry
#

!ide

eternal falconBOT
wintry quarry
#

(IDE means the program he is using to write code - in this case, Visual Studio)

pliant pecan
#

Is there a way for me to reference one script inside of another? Ie script 1: Potatofarm.cs, has the "createpotato()" method, script 2: farmmanager.cs, calls "potatofarm.createpotato()". Specifically i also want to change a variable in potatofarm, in farmmanager.

white egret
#

Yo i need help with my unity game, its a school project and its due in an hour can someone please help me <@&502884371011731486>

north kiln
white egret
#

then who do i ping?

north kiln
#

Nobody.

#

!ask

white egret
#

aight

eternal falconBOT
orchid flare
#

working on ML-Agents Hummingbirds tutorial. These errors came, but I don't think they should exist

the reason I don't think they should exist is cause i was really frustrated by following the tutorial and it still giving errors so I copy and pasted the source code
and it still gave errors, the ones I put above
only happens when it says "public override void" like here

so I tried removing the "override" from it, and then there were no more errors. But then when I saw my scene there was nothing in it and I do not know why
Help would be extremely appreciated. I don't know how much people care for ML-Agents these days but this is for school so it's rather urgent

astral citrus
wintry quarry
eternal falconBOT
#

:teacher: Unity Learn ↗

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

pliant pecan
astral falcon
pliant pecan
#

imma be real i already know the basics, i haven't used unity in a while and i just wanted to be reminded how to do this cause i didn't remember, and a quick google wasn't giving me what i want.

#

But honestly? It's the beginner channel? For beginners? Even if i literally just opened up the software literally just answer my question its not hard? Watch this:
"Yeah you reference scripts like they're types:

public helperscript h = new HelperScript();
h.fun();

But you should probably learn the basics first <link>"

bold thicket
#

I can't seem to get 3d animatons working, I'm using a lowpoly character model from unity asset store and mixamo animations. Anyone able to assist?

pliant pecan
bold thicket
#

I've set everything up according to a unity discussion post that was made, the animation in the animator tab is "running" but the animation in game scene isn't showing up.

runic lance
#

if it isn't related to code you should probably post this over #🏃┃animation
otherwise show us the code that's causing the issue

umbral bough
#

Hey, I am getting this really weird issue where my code is just not executing after a certain point even tho I see virtually no reason for that to happen o_0
Like there are no if checks, no asserts, no breaks, no returns, no errors, no nothing, and it just doesn't execute, therefore causing my program to not function properly.
Could somebody help me with this?
This is the chunk of code:

        /// Loads config values into a new Config object
        private void LoadConfig()
        {
            const string debugPrefix = "LoadConfig: ";
            
            // Reset to default to make sure all vars are set and changes no longer present in config are undone
            // Using ResetSilent because the OnChanged event will get triggered by Load() anyways
            Config.ResetSilent();
            Debug.Log(debugPrefix + "Reset to default config");
            
            // Reload the config
            JsonUtility.FromJsonOverwrite(_configText, Config);
            Config.Load();
            Debug.Log(debugPrefix + $"Loaded config from {_configPath}");
        }

It all gets executed, right up to the Config.Load() method, where it abruptly stops, and I get to output whatsoever, it can be seen in the picture I provided where I get the Debug before the json thing and then no output afterwards.
I know it's after the json thing it stops because I had additional debug logs, and the ones right after the json thing printed.
Here is that same chunk of code in my github repo so you can get a wider context of the code, it's a bit messy but shouldn't be the worst code you've seen:
https://github.com/nnra6864/Nisualizer/blob/e95df38c38ad80ab7998ff225d118b47dce70b01/Nisualizer/Assets/Scripts/Config/ConfigScript.cs#L88

burnt vapor
#

Are you certain that the code is compiled?

#

Wtf is FromJsonOverwrite

umbral bough
#

If you mean, am i sure that Unity reloaded scripts etc., yes, this is not the first save

burnt vapor
#

I suggest you use Newtonsoft instead of JsonUtility. Would not be surprised if it just hangs for no reason

astral falcon
umbral bough
burnt vapor
#

Maybe put a log past FromJsonOverwrite to see if it's either that or the config loading

umbral bough
umbral bough
burnt vapor
#

Right

#

If I were you I'd ditch JSONUtility in general even if it doesn't end up being the issue. The tool is very bad

astral falcon
umbral bough
#

let me try the other log

umbral bough
umbral bough
umbral bough
astral falcon
umbral bough
astral falcon
umbral bough
astral falcon
#

I also created like a singleton base class for myself to easily reduce the code of all those instances doubled in all scripts, just a tip 🙂

umbral bough
#

oh, I never make script singletons if that makes sense, if that's what you are on about in the first place

#

I always have a game manager that has all the singletons on that, or a scene manager if more appropriate

#

but yeah, what you suggested is actually an excellent thing, it fixed the bug of some things being called twice, however, it didn't help the actual issue I reported :/

astral falcon
astral falcon
umbral bough
#

yeah, I'll try debugging with rider now, hopefully I get to something

#

because the thing that stops the execution is rather simple, I genuinely don't see why it'd fail :/

        public static Texture2D TexFromFile(string path)
        {
            // Replace the relative with absolute path
            path = path.Replace("~", Environment.GetFolderPath(Environment.SpecialFolder.Personal));

            // If the image file doesn't exist, return null
            if (!File.Exists(path)) return null;

            // Read image data and store it into a Texture2D
            var data = File.ReadAllBytes(path);
            Texture2D tex = new(0, 0);
            
            return !tex.LoadImage(data) ? null : tex;
        }
        
        public static Sprite Texture2DToSprite(Texture2D texture) =>
            texture == null ? null : Sprite.Create(texture, new(0, 0, texture.width, texture.height), Vector2.one * 0.5f);

        public static Sprite SpriteFromFile(string path) => Texture2DToSprite(TexFromFile(path));

astral falcon
umbral bough
#

there are no exceptions, that'd be too easy

#

I did figure som new out, it ain't even that piece of the code

astral falcon
#

There seem to be a bunch of unknown parts here 😄 at least it feels like it reading along.

umbral bough
#

It's this actually: Live Config Reloading 😭
For some reason, when I save the file(at least with neovim), it triggers both the changed and renamed event.
Why? Yeah, I wish I could tell you tbh.
But anyways, I enabled debugging w rider and found that it jumps across code like crazy, it literally starts executing the chunk of the code I sent previously, then jumps back to where the event gets triggered, then there is a race condition between 2 TexFromFile() and I think my head hurts.

#

So for now, imma try to unsubscribe from the rename event

red igloo
astral falcon
umbral bough
#

I think I'll just randomly solve this one after 2 hours of trying random stuff

#

will let you know what it was once I figure it out, thanks for dedicating your time to helping me

dire grove
#

!code

eternal falconBOT
dire grove
#

i was working on my player movements and one of the abilities i.e. "Dash" was working fine before now suddenly it's not, help appreciated
https://hastebin.com/share/remafirimu.csharp

boreal cedar
#

private void Dashability()
{
if (dashCooldownTimer < 0 && isAttacking)
{
dashCooldownTimer = dashCooldown;
dashTime = dashDuration;
}
}

#

are you supposed to dash when isAttacking is true?

dire grove
#

no attack1,2,3 when dashing or moving

boreal cedar
#

if (dashCooldownTimer < 0 && isAttacking)

this line makes sure you can only dash if your attack animation is going

dire grove
#

i forgot to add a "!" after isattacking 😭

#

idk dash still aint working

vague phoenix
#

Hi, is Unity 6 is LTS version, and recommended to use ?

hexed terrace
#

or isAttacking == false

dire grove
#

man i want no movement except jump when im using dash

#

no attack

#

or any combo

#

dash is working somehow now, but i can still attack while dashing

boreal cedar
#

do the same thing you do for attacking

#

have a gamestate saying you are dashing

hexed terrace
#

if (!dashing) { attack; }

boreal cedar
#

and do an if check

#

yea like that

mild owl
#

im making flappy bird by tutorial and now im trying to fix so that whenever the bird dies it cant earn points by going trough the pipes but a script can't seem to recognize the public bird dead bool

hexed terrace
#

because the class with the error doesn't have a bool called birdisalive. It needs a reference to the other class, and then do bird.birdisalive

mild owl
#

so private bool birdisalive?

queen adder
#

how do i make random integer in a range

hexed terrace
hexed terrace
mild owl
#

like in middle pipe but just give me a min il read the link

queen adder
hexed terrace
#

it does not say that at all

queen adder
#

random.range() isnt working for me

#

what is it

hexed terrace
#

if you've typed it exactly like that.. it won't

#

screenshot your IDE and show

queen adder
#

nope

hexed terrace
#

not the single line.. the entire screen

queen adder
#

y does it do that

hexed terrace
#

but maybe read the error

#

the error tells you why, hover your mouse over the red squiggly line..

queen adder
#

our cdn may be blocked in china

hexed terrace
#

what has that got to do with coding?

vague phoenix
#

Hi dudes, how can I make up and down idle animation into an object?

prime hinge
#

hello every one when i take an object x and y positions will it store as int or float values?

frosty hound
#

Float

#

Well, the positions are in Vector3 which are comprised of floats. Whether you choose to take the individual values as floats or ints is up to you.

prime hinge
#

what is the benefits of using vector3 ?

frosty hound
#

It can represent a point and direction?

vague phoenix
#

Is the transform.position includes the rotation too?

timber tide
#

transform.rotation

mild owl
#

ok i give up

timber tide
#

no, u cant

mild owl
#

ok i take break 👍

wintry quarry
burnt vapor
mild owl
#

ok i did the awake thing il try to research the singleton thing now

steep rose
hexed dove
timber tide
#
SetDirection(_Hit.collider.gameObject.transform.forward);```
hexed dove
#

SetDirection(_Hit.collider.gameObject.transform.forward);

#

yes

timber tide
#

Well, something is null, so in this case you've a bunch of dot operations going on. If you want to just log it out, then start from left to right.

hexed dove
#

what does left to right mean ?

languid spire
#

hit collider is null

timber tide
#

I was thinking hit is null, but they do a comparison earlier and it didn't seem to throw an error

languid spire
#

hit cannot be null it is a struct

hexed dove
#

yes it works for other colliders

tulip nimbus
#

OnHover is called every frame in Update if i look at a card, however i want it to only be called once so the Animation does not play every frame. Ive set a hover boolean to prevent this but it doesnt seem to work. What did i do wrong?

hexed dove
#

so i dont get the eror

keen dew
#

They overwrite the _Hit variable on line 74

hexed dove
keen dew
#

If all that raycast does is check if it hits anything you don't need a variable at all

hexed dove
#

it fixed the issue thank you !

timber tide
tulip nimbus
#

I thought i was getting crazy

mild owl
mild owl
#

perhaps chat gpt could help

strong wren
#
spawnedMiddle.Logic = ...```
mild owl
#

ok nothing really makes sense il just watch a few more tutorials and come back

buoyant finch
#

hello I have the hp bar fixed but I want it to display the currenthp with the maxhp with a text component how to do it

timber tide
#

plenty of tutorials around for that

polar acorn
buoyant finch
#
public void SetData(Pokemon pokemon)
{
    if (pokemon == null || nameText == null || levelText == null || hpBar == null || hpText == null)
    {
        Debug.LogError("One or more components are null!");
        return;
    }

    nameText.text = pokemon.Base.Name;
    levelText.text = ":L " + pokemon.Level;

    int currentHP = pokemon.CurrentHP;
    int maxHP = pokemon.MaxHP;

    hpText.text = currentHP + " / " + maxHP;
    hpBar.SetHP((float)currentHP / maxHP);
}

I have this code so far

#
public int MaxHp {
    get { return Mathf.FloorToInt((Base.MaxHp * Level) / 100f) + 10; }
}

and have this for calculation of hp stats but it shows a higher value than what I intend on is the formula wrong?

polar acorn
#

Check the formula by doing the math yourself. See if the value you get matches the value you expect

buoyant finch
#

I got the formula from official website

#

And also how to make it reduce the text when the filled healthbar is reduced that we did yesterday

stuck palm
#

Why isn't my code working to set the position? The red cube is the transformPoint that it's meant to be following.

void Update()
    {
        Vector3 screenPoint = cam.WorldToScreenPoint(transformPoint.position + offset);
        
        rectTransform.anchoredPosition = screenPoint;
        
    }

when i look at the position of the texts, they are way off.

polar acorn
buoyant finch
polar acorn
polar acorn
verbal dome
buoyant finch
stuck palm
buoyant finch
#

I have done that but when my HP is reduced the int value doesn't get updated

verbal dome
#

@stuck palm IIRC anchored position is like local position, maybe the UI object's parent is in the wrong place?

verbal dome
#

With the parent transform as the rect

polar acorn
verbal dome
#

So first WorldToScreenPoint, then that

buoyant finch
polar acorn
buoyant finch
polar acorn
buoyant finch
#

Yes exactly

polar acorn
#

Log the values of current HP and max HP after you set the text.

If you get the logs and they don't match the text element, either you're changing the wrong text element or something else is changing them back afterwards

buoyant finch
#

Ok thanks for the help will update you

stuck palm
# verbal dome So first WorldToScreenPoint, then that
void Update()
    {
        Vector3 screenPoint = RectTransformUtility.WorldToScreenPoint(cam, transformPoint.position); // + offset;
        
        RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, screenPoint, cam, out Vector2 localPoint);
        
        rectTransform.anchoredPosition = localPoint;
        
    }
#

just completely off the map now

timber tide
#

why not just use world text

stuck palm
#

how can i make it like

#

a billboard?

#

so it constantly looks at the camera

timber tide
#

Lookat constraint

#

or yeah make your own billboard script

stuck palm
#

i mean look at sounds easier

#

i'll just make world canvases and stuff

#

thanks! didn't even think of world text lmao

timber tide
#

shader is bestest but gotta append to the tmpro shader

#

and that's zzz

verbal dome
#

I barely use Unity UI so I don't really remember what's the right way to do it

stuck palm
stuck palm
timber tide
#

All I can think of is pivot on the UI text isn't representing it correctly

#

or margins on the text

stuck palm
#

maybe

#

anyway its too much effor now, world space ftw

rancid tinsel
#

can you not assign scriptable objects at runtime? ive got a script that holds a list of scriptable objects, and i try to grab the reference to a specific index at runtime and it just refuses

slender nymph
#

provide more information about what is actually happening, including relevant code

rancid tinsel
rich drift
#

my character is 32x64 and these tiles are 32x32 but the tiles appear twice as large as they should (using a tileset/grid). cant figure out why. the scale of each is set to 1. i double checked that the tiles actually are 32x32

slender nymph
#

this is a code channel. and you likely need to adjust the pixels per unit setting on the import setting for the texture

warm pawn
#

how do I cast a SphereCast where I want to ignore triggers but detect all Layers?

rich drift
#

gotcha sorry, to me its all code 😅

#

thanks

slender nymph
warm pawn
#

why dose it think that its a int?
Physics.SphereCast(jumpSpherecast.origin,0.5f,jumpSpherecast.direction,out RaycastHit hit,0.755f,QueryTriggerInteraction.Ignore)
(jumpSpherecast is a Ray)
error says: cannot convert from 'UnityEngine.QueryTriggerInteraction' to 'int'

#

(the error is for QueryTriggerInteraction.Ignore)

warm pawn
#

I know but I want to dettect all Layers

#

Is LayerMask required to be declared to declare QueryTriggerInteraction?

rocky canyon
# warm pawn Is LayerMask required to be declared to declare QueryTriggerInteraction?
    public QueryTriggerInteraction triggerInteraction = QueryTriggerInteraction.Ignore;

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            if (Physics.SphereCast(transform.position, radius, direction, out RaycastHit hit, distance, ~0, triggerInteraction))
            {
                Debug.Log("Hit: " + hit.collider.name);
            }
        }
    }```
you could use `~0` in place of the layermask
#

that'd be ur Default layers (all layers but the Ignore Raycast layer) iirc

zenith cypress
#

That will include all layers. If you want the actual default, use Physics.DefaultRaycastLayers

rocky canyon
#

aye this

#

i was thinking you didn't need a layermask at all.. but im guessing you do to get to the seventh parameter

rocky canyon
slender nymph
polar acorn
rocky canyon
#

cool that it includes all the layers, even the unused ones..

rocky canyon
#

always having to go and double-check lol

queen adder
#
    public void PickUpBox(InputAction.CallbackContext context) {
        if (context.performed) {
            if (Physics2D.OverlapCircle(directionPoint.position,0.2f, boxLayer)) {
                //get gameobject 
            }
        }
    }

What i want to do is, get the Gameobject that is at the directionPoint. This there a way to get this just via script of do i have to use a triggerCollider ?

warm pawn
#

thx guys

rocky canyon
#

or is that not accurate enough?

queen adder
#

sorry maybe it was unclear, i want to access the gameobject, that is on the dectionpoint, to do thing with it.

#

and store this GameObject aka the Box in a varible

steep rose
#

OverlapCircle returns a Collider2D array (I believe) so you could probably grab the object(s) from that

sharp bloom
#

I'm trying to create some sort of a simple plane flight demo.

As you may know, the force of lift is dependent on velocity ^ 2.

I use Rigidbody.velocity.magnitude to get this velocity, and use the standard formula for lift.

My trouble is, when the velocity exceeds a certain point, my simulation goes into a self-sustaining infinite loop in which the velocity and force of lift go into infinity.

#

Any idea how to prevent it?

timber tide
#

cap it

rocky canyon
#

is ur lift creating forward momentum as well?

queen adder
sharp bloom
rocky canyon
queen adder
#

okay thx, i will try this

rocky canyon
timber tide
#

otherwise add dynamic drag

rocky canyon
#

unsure why u have infinite loop tho.. if the lift is only perpendicular to the plane

steep rose
sharp bloom
#

But yes I'll cap it

keen dew
#

In practice only forward velocity generates lift. So using magnitude isn't correct. It should be rb.velocity.x

sharp bloom
#

Oh that might be it

keen dew
#

And what keeps lift from increasing to infinity in real life is drag, so you might want to model that in too

rancid tinsel
#

im so confused as to what is happening here

#

is the error in a different place or?

timber tide
#

You have two things that can be null there

rancid tinsel
#

i didnt attach the actual SoundReceiver script

delicate zinc
#

i know i shouldnt be using gameobject.find but i just wanna know why is this not finding the gameobject
i used this same script with the same setup of objects on a different scene and it worked, but its not working once i bring the prefab into a different scene
it finds the gameobjects on start

strong wren
delicate zinc
#

no its just in the scene

#

im pretty sure everything is the exact same as in the test scene but its not finding anything (im using multiple gameobject.finds)

strong wren
#

Is the script doing the searching in the same scene as the player?

#

I assume you don't have any sort of multi scene setup going

delicate zinc
strong wren
#

I assume that line is currently throwing a null ref exception?

delicate zinc
#

yeah every time it spawns

mild owl
#

it says } is expected but i already typed it

slender nymph
#

still need one to close the class

steep rose
mild owl
#

oh alright

#

OH

strong wren
mild owl
#

thanks i must have deleted it by accident

strong wren
# delicate zinc yeah every time it spawns

You could use GameObject[] rootObjects = gameObject.scene.GetRootGameObjects(); to get all root objects just before the search and log through them all in a loop to see every root object at that time.

strong wren
delicate zinc
strong wren
rocky canyon
#

is "Player/CamContainer" correct?

delicate zinc
rocky canyon
#

i didnt even know thats how that works

#

im gonna guess that it indeed is finding things.. but ur getcomponents are failing.. (maybe b/c they dont have the components)

#

ran the same code, from a prefab in Start() using same heirachy and strings.. and it worked fine

strong wren
delicate zinc
rocky canyon
#

sorry i didn't catch the line-number of the error

strong wren
slender nymph