#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 541 of 1

elder raptor
#

Ohhh I seee, thanks for the information!

willow sand
sterile cairn
#

im trying to use lerp so the camera follows the player but for some reson it doesnt work properly ingame

elder raptor
sterile cairn
#

oh lol

elder raptor
#

I'll dm u the code I did which ended up working

elder raptor
sterile cairn
#

sure

copper crest
#

UpThis

elder raptor
willow sand
#

no

elder raptor
# willow sand no

Will be good if you added a muzzleEffect.GetComponent<ParticleSystem>().Stop(); too.

Try adding this to your Update

if (!isShooting && muzzleEffect.GetComponent<ParticleSystem>().isPlaying)
    {
        muzzleEffect.GetComponent<ParticleSystem>().Stop();
    }

And update the first line of FireWeapon() to this and try:

if (!muzzleEffect.GetComponent<ParticleSystem>().isPlaying)
    {
        muzzleEffect.GetComponent<ParticleSystem>().Play();
    }

Just try these and see if it works

#

It will also make your code cleaner if you accepted a ParticleSystem instead of a GameObject for muzzleEffect lmaoo

willow sand
#

it made it so that if I click it starts but when i click again it stops and in between it just keeps going

elder raptor
#

Ohhh

#

Hmm, it would be easier for me to Debug if I could replicate the project xD I guess you need to wait for someone who can debug stuff through code itself

#

But I assume it's because the Particle System State is not aligning with the isShooting state. Or the .isPlaying is not working as intended.

astral falcon
#

Why not set a global bool instead of relying on getcomponent in update (bad idea) and the isPlaying state that could lack behind

silent falcon
#

I canโ€™t wait to share this good news, it turns out that I was just overthinking it. When I moved ImageElement.cs from Assets/Editor/UI to Assets/UI, the problem was solved.๐Ÿ‘

humble forum
#

public Transform firePoint;

#

how can i set my minimage as startpoint for it?

vocal urchin
#

Is there a way to reference a prefab from a prefab's instance?

languid spire
split solar
#

aye need some help, how do i take a seed and make it into a random number?

#

let's say my seed is 9173617199 and i want it to give me a random number between 1-20, how do i go about this?

split solar
dense bridge
hexed terrace
#

If the GetComponent is getting the same component every frame, then it's pointless. Do it elsewhere so it can be called just once

burnt vapor
#

You can get away with quite a few things in an Update frame because C# is generally very performant. However, if you are going to waste it getting a component every frame instead of caching then that does add up eventually

stable quail
#

Hi, i've question for a code :

How to create a procedural animation for a game character ? (i've don't know how to create this, i've searched a tutorial, but i've don't fund)

little meteor
stable quail
little meteor
#

Take a look at the two bone IK constraint example in there,

little meteor
stable quail
bitter apex
#

does OnClick() for buttons run the method given whenever it is pressed, or only the first time it is pressed?

little meteor
bitter apex
#

because right now it's only running the code the first time I click the button

stable quail
bitter apex
#

yeah nevermind I realised the problem in my code

#

cheers

little meteor
# stable quail ok and, if u explain at me ? (if u want and u can)

animation rigging is a package that lets you do lots of cool procedural animation tricks on preconfigured rigs, I would suggest you learn some about IK (inverse kinematics) which is used a lot for moving bones realistically towards a target, it lets you animate where you want the feet (procedurally or otherwise) and then the package handles moving all the other bones

stable quail
tulip nimbus
#
RoundManager roundManger;
public TMP_Text mainTableText;

void Start()
{
    roundManger = FindFirstObjectByType<RoundManager>();
}

void Update()
{
    mainTableText.SetText("Round " + roundManger.Round);
}

Why am i getting a NullRefrenceExeption even tho the code works completely fine and shows no compiler errors. It can grab any Data from mainTableText and roundManager without issues

eager spindle
tulip nimbus
eager spindle
#

I'll just say that it's RoundManager

#

RoundManager isn't actually being set

keen dew
#

Null reference exceptions aren't related to compiler errors. If the text gets updated then you have the component on more than one object, or twice on one object

eager spindle
#

In the start function, the find function returns null but doesn't give an error

#

You'll need to think of another way to get the round manager

tulip nimbus
eager spindle
#

This will change your life

#

No more findfirstobjectbytype

tulip nimbus
#

Ill look into it! Thank you!

eager spindle
#

today I learned that TMP_Text has SetText

humble forum
#

i got this and health is a slider i want to make sure to bind it to my enemy and see it in the world but can t seem to bind the image only the canvas

wooden sandal
#

ive got a question to events
lets say i have a couple of brick objects. they all have the same script running on them. random variation may occur.
if one of these bricks is destroyed, i invoke a signal

        public delegate void BrickDestroyed(BrickBase brick, int points);
        public static event BrickDestroyed OnBrickDestroyed;

 private void Hit()
 { 
     if (remainingHits <= 0 || brickState < 0)
     {
         gameObject.SetActive(false);
         OnBrickDestroyed?.Invoke(this, points);
     }
 }

but from what ive witnessed. this signal is called for all bricks on the screen and not just for the one destroyed.

private void Spawn()
      {
          collectable.GetComponent<SpriteRenderer>().sprite = collectableSprite;
          Instantiate(collectable, transform.parent.position, Quaternion.identity, transform.parent);
      }

      private void OnEnable()
      {
          BrickBase.OnBrickDestroyed += CheckForSpawn;
      }
      private void OnDisable()
      {
          Physics2D.queriesStartInColliders = true;
          BrickBase.OnBrickDestroyed -= CheckForSpawn;```

so in this example code, it would instantiate an object on all bricks on the screen. this is why i check for the brick.

but i still dont want all the bricks to fire the signal. is there a best practice way to write signals in a way, so they only get invoked from one single object?
eager spindle
#

Just parenting it won't work

humble forum
#

got this right now

#

but images don t work seems only to work on gameobject

#

so sort of need the object and the image

stable quail
#

I need bones for this to work?

cosmic dagger
wooden sandal
visual linden
little meteor
# stable quail

Yes, a rig, or a tranform heierachy will do, don't forget to add a rig builder somwhere

cosmic dagger
cosmic dagger
stable quail
stable quail
cosmic dagger
cosmic dagger
humble forum
humble forum
little meteor
cosmic dagger
little meteor
# humble forum yeah

You'll need to keep a reference to the instantiated object, and I suggest a gameobject to assign and expose the bits you want to change to make it simpler.

humble forum
#
  public void ApplyDamage(EnemyData enemy, int damage)
    {
        if (enemy == null)
        {
            Debug.LogError("Enemy is null!");
            return;
        }
        enemy.MinHealth -= damage;

       
        enemy.MinHealth = Mathf.Clamp(enemy.MinHealth, 0, enemy.MaxHealth);

        Debug.Log($"Enemy health after damage: {enemy.MinHealth}/{enemy.MaxHealth}");

      
        UpdateHealthBar(enemy);

        
        if (enemy.MinHealth <= 0)
        {
            Debug.Log("Enemy health reached 0, removing enemy...");
            if (enemy.spriteRenderer != null)
            {
                Destroy(enemy.spriteRenderer.gameObject);
            }
            if (enemy.healthBarImage != null)
            {
                Destroy(enemy.healthBarImage.transform.parent.gameObject);
            }
            temporaryEnemies.Remove(enemy);
        }
    }


    public void UpdateHealthBar(EnemyData enemy)
    {
        if (enemy.healthBarImage != null)
        {
           
            float healthPercentage = enemy.MinHealth / enemy.MaxHealth;

            Debug.Log($"Updating healthbar: {healthPercentage * 100}% health");

            // Stel de fillAmount correct in
            enemy.healthBarImage.fillAmount = healthPercentage;
        }
        else
        {
            Debug.LogError("Healthbar Image is null!");
        }
    }
}
#

all debug logs work just can get the fillamount working

wintry quarry
# humble forum got this right now

It doesn't look like you're saving a reference to the health bar anywhere when you instantiate it so how is it you are trying to update the image later?

#

Where do these references come from:

enemy.healthBarImage```
little meteor
#

yeah that ^

wintry quarry
#

You are only saving the reference in a local variable which quickly disappears

#

My guess is you are modifying the prefab instead of the actual instance you created in the scene

humble forum
wintry quarry
# humble forum

This doesn't make sense - how would this refer to the instantiated prefab then?

#

It seems like you're just referencing the prefab with these fields in the inspector

#

so it makes sense the code doesn't do anything

#

How is this assigned?

cosmic dagger
#

Where do you assign the healthBarImage?

humble forum
#

newEnemyData.healthBarImage = healthImage;

wintry quarry
#

why don't you just show the full script. And not with screenshots

#

!code

eternal falconBOT
humble forum
#

Image healthImage = healthBarObj.GetComponentInChildren<Image>();

wintry quarry
#

show full code instead of playing this game

little meteor
#

if it's all set up correctly I'd double check the Image.type is set to Image.Type.Filled

humble forum
wintry quarry
#

and also wouldn't be applicable to anyone else's game

humble forum
wintry quarry
#

I don't know anything about your teachers' plagiarism detection methods

humble forum
#

can t i just sent 2 big code blocks?

#

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

public class Enemy : MonoBehaviour
{
    [System.Serializable]
    public class EnemyData
    {
        public SpriteRenderer spriteRenderer;
        public float speed = 2f;
        public float MinHealth = 100;
        public int MaxHealth = 100;
        [HideInInspector] public int currentWaypointIndex = 0;
        public Image healthBarImage; 
    }

    public List<EnemyData> enemies = new List<EnemyData>();
    public Transform[] waypoints;
    private List<EnemyData> temporaryEnemies = new List<EnemyData>();
    public GameObject HealthBarPrefab;

    void Start()
    {
        if (enemies.Count > 0)
        {
            SetEnemy(0);
        }
    }

    void Update()
    {
        foreach (var enemy in enemies)
        {
            if (enemy.spriteRenderer != null)
            {
                MoveToWaypoint(enemy);
            }
        }
        
        for (int i = temporaryEnemies.Count - 1; i >= 0; i--)
        {
            var tempEnemy = temporaryEnemies[i];
            if (tempEnemy.spriteRenderer != null)
            {
                if (MoveToWaypoint(tempEnemy))
                {
                    Destroy(tempEnemy.spriteRenderer.gameObject);
                    temporaryEnemies.RemoveAt(i);
                }
            }
        }
    }

    public void SetEnemy(int index)
    {
        if (index < 0 || index >= enemies.Count)
        {
            Debug.LogError("Ongeldig vijand-index!");
            return;
        }
    }
#

shitt i need 3

swift crag
#

Please use a paste site.

swift crag
humble forum
swift crag
#

using a paste site will be equivalent to posting all of the code in here

humble forum
#

yeah but then it is on the web here im directly bind to it

verbal dome
tall brook
#

Yo does anyone have any links to a good intro to coding. I know โ€œhow toโ€ but the actual writing of code is confusing. Just started yesterday

swift crag
humble forum
humble forum
verbal dome
#

I don't think we do

muted pawn
#

yeah me neither tbh

wintry quarry
#

They are afraid their professor's plagiarism scanner will see the paste online and then detect their homework as plagiarism

swift crag
#

You appear to be concerned that a plagiarism detector will dig through every single paste every made on any paste site

burnt vapor
#

Plagiarism detection is not going to find random pastes

verbal dome
#

That's a real concern?

swift crag
#

I have no idea!

wintry quarry
#

Honestly I have no idea, it might be a legit concern

swift crag
#

notably, non-public pastes are very hard to randomly find..

humble forum
burnt vapor
#

There's no public list of these pastes, so I very much doubt it would matter

frosty hound
#

Change the names of variables? The spacing? Comments?

swift crag
#

is this actually grounded in reality

#

or is this just something you heard of once from A Guy

frosty hound
#

It's very hard not to have near identical code to something else online, even if you're not intending to.

swift crag
verbal dome
#

Maybe just add a comment // By timo

#

Lol

swift crag
cosmic dagger
#

regardless, without seeing any code we can't determine what/where the problem lies and how to fix it. i doubt posting code will ruin your assignment . . .

humble forum
#

maybe i should encrypt it and tell the pw in here notlikethis

swift crag
#

Just use the damn site. It doesn't have a public list of all pastes and everything gets deleted after a week

#

This is a complete non-issue

burnt vapor
humble forum
#

done

little meteor
humble forum
#

yep

little meteor
#

when you instantiate the health bar set the .fillAmount to Random.value

#

and just check to see if it's working at all

swift crag
#

you should check that you're getting the correct image. perhaps there are multiple images

#

you could do this by logging the Image you get

humble forum
swift crag
#

if so, it would be preferable to make a Healthbar component that you reference instead of a plain GameObject. It could tell you where the actual fill image is.

little meteor
#

if it works after that then you're calculating the fillammount value incorrectly

humble forum
little meteor
humble forum
#

so comment everything out?

little meteor
little meteor
vast stirrup
#

I want to be able to control the player with wasd and this is my code:

horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");

transform.Translate(Vector3.right * horizontalInput * speed * Time.deltaTime);
transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime);

Problem is when I rotate the player, its z axis changes direction and the controls are very weird then. Can anyone help me?

swift crag
#

Do you want the player to move in the same direction no matter how the player is rotated?

little meteor
swift crag
#

Translate is already working in the object's "self" space

#

It is correct to give it fixed "right" and "forward" vectors here

vast stirrup
swift crag
#

In that case, use Space.World as a second argument to Translate

little meteor
#

oh yeah it has a optional param for Space

vast stirrup
swift crag
#

This tells it to interpret that vector as a world-space direction

#

instead of a local-space direction

humble forum
#

now it doesn t wanna work anymore :/

little meteor
#

one learns something new every day UnityChanThumbsUp

rich adder
swift crag
#

you probably have a using System; at the top of your file

#

You can just write UnityEngine.Random to make it very explicit that you want unity's Random class

humble forum
swift crag
#

ah, you got the third random, haha

#

Unity.Mathematics.Random

little meteor
#

๐Ÿคฃ

swift crag
#

You can remove using Unity.Mathematics;, which will then make the IDE ask you which class you meant to use

#

or you can explicitly use UnityEngine.Random

rich adder
#

btw you can also just do using Random = UnityEngine.Random

swift crag
#

That too, yes.

#

using directives let you avoid writing out all of the namespaces for a class

#

using Foo.Bar.Baz means you can write Buz instead of Foo.Bar.Baz.Buz

humble forum
#

don t see a random value the slider works

swift crag
#

While you're at it, consider logging which Image you're actually targeting here.

Debug.Log(enemy.healthBarImage, enemy.healthBarImage);
#

the second argument is the "context". You can click on the log entry to go to that object

little meteor
humble forum
swift crag
#

While you're still in play mode, click on the log and see what you're actually getting

#

I bet you got the frame image

#

Which is why GetComponentInChildren is evil and will break your project in new and surprising ways at random!

#

I had a killer bug where GetComponentInChildren<Renderer> wound up grabbing a VisualEffect instead of a MeshRenderer. My code wound up breaking the visual effect, and I couldn't understand why it was failing to play

#

now I will retrieve my wall of text I was typing earlier!

little meteor
#

I tend to make a monobehaviour which explicitly publicly exposes the bits of the UI I care about and attach this to the prefab, assign them manually

humble forum
swift crag
#

Instead of using GetComponentInChildren, you can make a component that talks to the components for you.

public class Healthbar : MonoBehaviour {
  [SerializeField] private Image fillImage;
  
  public void SetHealth(float percentage) {
    fillImage.fillAmount = percentage;
  }
}

Make a prefab that has a Healthbar on it. Assign the correct reference.

Then, your creation method would look more like this:

Healthbar newBar = Instantiate(HealthBarPrefab, newEnemy.transform);
newBar.transform.localPosition = new Vector3(0, 0.5f, 0); 
newEnemyData.healthbar = newBar;
UpdateHealthBar(newEnemyData); 
}

You would also need to store a Healthbar instead of an Image on the enemy data.

You no longer talk directly to an Image. You just tell your Healthbar that it needs to display a certain health percentage.

rich adder
#

sadly we still don't have an argument for GetComponentInChildren / Parent to skip the root object too

swift crag
#

I only use GetComponentsInChildren

rich adder
#

true lol

#

I use parent sometimes to get a parent component from a collider only child

swift crag
#

GetComponentInParent is generally less surprising

#

just because you only have a few parents, but can have many, many children

swift crag
humble forum
swift crag
#

It gave you the first component it could find on the object

#

It's just...the wrong component

#

Which is why I try to avoid it as much as possible. Your code shouldn't care about the exact order of components on an object (or the order of its children)

humble forum
#

f i see

queen adder
#

whats the best ide for c# and python

rich adder
humble forum
#

pycharm for python

queen adder
humble forum
swift crag
#

like if you add another Image to show the previous health value

burnt vapor
rich adder
swift crag
#

Also, by doing this, you'll be able to keep all of the healthbar logic in the healthbar

queen adder
swift crag
#

If you want it to slowly drain over time, that's very easy. The game will just call SetHealth on it, and it'll decide how to change the image's fill amount over time!

humble forum
swift crag
#

I have several components that started out as "bags of references" -- no logic, just public fields -- that then got more features

swift crag
swift crag
humble forum
swift crag
#

You're already instantiating prefabs, right?

#

or are you just instantiating an object that's in the scene?

humble forum
swift crag
#

Okay, then start by actually making a prefab

#

you can just drag the healthbar template into the Project window to create a prefab

#

Then, after adding the Healthbar component, update your scripts to reference a Healthbar, not a GameObject or an Image

#

and then assign a reference to the prefab where needed

humble forum
#

will try thank you

swift crag
#

I almost never reference prefabs as a GameObject -- that implies I could use any prefab!

neat frost
#

Click-to-Move (Camera Jitter)

humble forum
swift crag
#

"tried object"?

humble forum
#

Object

#

but the heatlbar image needs image in order for the slider to work and the child thingy is a bit annoying to get rid of

swift crag
#

that's even less specific!

#

use Healthbar

#

the point is that you reference the prefab as a Healthbar

humble forum
#

super stupid but dunno what im suppose to do ๐Ÿ˜…

swift crag
#

Did you actually create a component called Healthbar?

humble forum
#

oh so you create a custom script for it in other to find it was like how is it suppose to find it ๐Ÿ˜… notlikethis

swift crag
#

Yes -- you're creating a new component called Healthbar

winged osprey
#

Hey, so apparently i've tried anything to make my animation loop, but it just doesn't work. I mean, i might know why, but don't know how to fix it.
The idle animation, which i set up as default state, exit time is off for the transitions that should be off, like moving animation and idle animation. So it should be right.

"'Player' AnimationEvent has no function specified" error shows up.
Any ideas?

humble forum
cosmic dagger
winged osprey
#

yes i did

cosmic dagger
winged osprey
#

Do the events just auto add themselves?

#

I mean as far as i know i didnt add any

cosmic dagger
#

not that i know of . . .

winged osprey
#

let me check rq

cosmic dagger
#

check the clip for an animation event. if you don't need it, remove it . . .

winged osprey
#

well, it auto added itself

#

it took me 3 hours

#

to find this

#

it wasnt it though

humble forum
winged osprey
#

The animation plays really slow, doesn't play or just stops and doesn't animate any other things.

neat frost
#

What is the appropriate wait time before reposting if I don't see a response to my help request?

winged osprey
#

It's not like everyone knows the answer to your question, but you can try at some kinda 10min-ish interval

#

ohhhh wait

#

forgot about those

#

there's like

#

999+ warnings

cosmic dagger
neat frost
cosmic dagger
#

the chat moves fast and if it's been a while, no one will know you had a question or remember . . .

winged osprey
#

Alright, basically i fixed the reason of warnings, but the animation still feels slow and stops itself after a moment. No idea why.

cosmic dagger
neat frost
#

Camera Movement (Camera Jitter)

brittle isle
#

Slope Movement Issues

cosmic dagger
winged osprey
#

im trying to fix it

#

if i wont be able to fix it imma send it here

coral fossil
#

bump

winged osprey
#

can you show me the script?

#

or the inside of a button or however you call it

#

js dm if you cant send it here imma look for it

coral fossil
#

this is the game manager script

winged osprey
#

i only started recently coding in c#, but i think the #if, #else and #endif seems interfering with the editor.

#

my exitgame looks simple

#

public void ExitGame()
{
Application.Quit();
Debug.Log("Game Closed");
}
}

#

but yours is kinda complicated

languid spire
winged osprey
#

and somehow mine works and his doesn't?

#

it seems off

coral fossil
#

this is just the code my prof gave me so i assume theres nothing wrong with the script itself

winged osprey
#

welp i have no idea then

languid spire
vast stirrup
#

Hi! I am working on a top down shooter\survival game but I don't know how to make the players gun face the mouse, here is my attempt at this:

    mousePosX = Input.GetAxis("Mouse X");
    transform.Rotate(0, mousePosX * sensitivity, 0);
rich adder
fervent abyss
#

i feel the lobotomy effect rn

polar acorn
#

Vector3s, in fact, cannot be changed. Changing any of them creates a new Vector3 every time

rich adder
#

yes you're fine. not something you should worry with. Vector3 is efficient its a struct with 3 floats.

fervent abyss
polar acorn
#

They're structs, they're designed to be created and disposed of freely

fervent abyss
#

i actually feel like lobotomy effect rn

vast stirrup
rocky canyon
#

Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

rich adder
vast stirrup
swift crag
#

The relationship between your screen and the world depends on where the main camera is

verbal dome
#

Like how is your world oriented

late burrow
#

i have 600 objects whats cheaper looping them all every frame to check which is closest or strap collider to each of them and do ontriggerenter

verbal dome
#

The code suggest 3D game since you tried to rotate on Y axis

late burrow
#

i assume second one

rocky canyon
rich adder
vast stirrup
verbal dome
#

Orthographic or perspective camera?

vast stirrup
#

orthographic. I wanted to make an fps game at first but when I looked up tutorials for fps camera I felt like I got brainfreeze.

coral fossil
verbal dome
#

With ortho, ScreenToWorldPoint should be fine but be mindful of the y position

#

Like if you create a direction vector with mouseWorldPos - playerPos, set the y to zero

#

At least if you use it for projectiles... If you use it just for y angle then it's probably fine

vast stirrup
rich adder
#

transform.forward = dir

green flame
#

Hello, I'm new in the unity world (from webgl) and I have a question. I hope this is the right place to ask for some advices!

I'm creating to understand unity some single pages like in the web and for that I use UI Document. To "catch" a click event on buttons in C# I do this (on my screen). But I'm not "sure" about the right way, is this OK ?

rich adder
#

seems correct though

#

also you should probably configure your VSC

languid spire
rocky canyon
#

i agree w/ steve here.. try to limit ur use of var

#

if u know what type it is go ahead and assign it to the correct type..

green flame
#

Ok thanks for ur advices, I'll limit the use of "var"!

sleek notch
#

Hi, can someone help me what to do with this kind of error?

rich adder
sleek notch
#

like how

#

exactly

rich adder
#

how if you haven't shown all the errors?

sleek notch
#

this is the only one

cosmic dagger
rich adder
cosmic dagger
#

are their any other errors messages in your console window?

sleek notch
#

there is no specification

#

I'll show you

#

new error apeared for no reason? What does that mean?

rich adder
sleek notch
#

no

#

I had 2 errors before I just fixed them and now ner apeared

cosmic dagger
sleek notch
#

I'm telling you the truth

cosmic dagger
#

fixed errors mean more of your script(s) compiled further until they reached another error . . .

#

keep fixing them until they all disappear . . .

sleek notch
rich adder
swift crag
#

I'm pretty sure the compiler just gives up on further analysis

#

(which can result it finding non-syntax errors, like that one)

sleek notch
swift crag
#

Ah, I know what it is, then

rich adder
swift crag
#

You've got editor code that's getting included in the game

sleek notch
swift crag
#

Editor code should go into a folder named Editor. That will put it into a different assembly that doesn't go into the build

#

When you build the game, the UnityEditor namespace is not available. Any code that tries to use that got included in the built game will fail to compile.

Importantly, you will not see this in the IDE, because it still thinks it's analyzing code for use in the editor

rich adder
sleek notch
swift crag
#

Yes. It can be a subfolder if you want, but it needs to be inside a folder named Editor

sleek notch
#

I'm desprate about this. ChatGPT won't help in this

sleek notch
#

I'm sorry it is too late for me

swift crag
sleek notch
#

oh

#

I'm idiot

#

sorry

#

did you made the Editor?

#

I can't see it xd

alpine fjord
sleek notch
#

Okay

swift crag
#

you need to create the folder if it doesn't already exist, yes

humble forum
swift crag
#

the name must be exactly Editor

sleek notch
swift crag
#

which is reasonable

#

Annoyingly, if you switch to "Assets", it won't show you the prefab you made

#

apparently it's a performance concern

#

You'll have to drag the prefab into the property in the inspector

humble forum
swift crag
#

Then your prefab doesn't have a Healthbar component on it

humble forum
swift crag
#

What script "3x"?

#

I don't understand that statement at all

humble forum
#

3 times

swift crag
#

You need to attach a Healthbar component to your prefab

#

If you don't, then there is no Healthbar to reference at all

humble forum
#

and how does enemy know that then?

swift crag
#

know what?

humble forum
swift crag
#

"the health"?

#

The enemy class has a HealthBarPrefab field on it

#

This lets you store a reference to a Healthbar

#

Drag the prefab into this property in the enemy's inspector

tawny notch
#

Im tryna make a script which tries to get the layer of the object it collided with. I use a LayerMask for EnemyLayer but its not working lol:

    void OnCollisionEnter2D(Collision2D collision){ //Called whenever object collides with another object
        if (collision.gameObject.layer == EnemyLayer){
            Debug.Log("Enemy Hit");
        }
        Destroy(gameObject); //Destroys bullet object
    }```
swift crag
#

the layer property is a number from 0 to 31

humble forum
#

like this?

swift crag
#

a layermask can be any integer (each bit represents a layer)

tawny notch
#

oh ok

polar acorn
swift crag
#
if (mask & (1 << whatever.layer) != 0) {

}
tawny notch
#

alright thanks

swift crag
#

This tests if the mask has the relevant bit set

polar acorn
swift crag
#

1 << 0 is the rightmost bit and 1 << 31 is the leftmost bit

#

dammit

polar acorn
#

Hey, we scooped each other

#

I got the link first, you got the answer first

humble forum
polar acorn
#

So, you've got your prefab referenced now at least

humble forum
#

oh damn that works already

#

oh no gifs :/

swift crag
#

These fields are getting filled in by your script as you spawn enemies

#

I would suggest adding [System.NonSerialized] to them so they don't even appear in the inspector

#

(and so that they don't get saved at all, ever)

#

Serialized fields are used to configure an object in the inspector, but you aren't doing that for the "Health Bar Image" field. Your code sets that field.

humble forum
#

alright thank you so much think i am almost done with the core features ๐Ÿคฉ
now need to find out why i can t see the projectiles (prob go too fast) but that is a problem for tomorrow ๐Ÿ™‚

coral fossil
#

is anyone able to help FuwaPray

swift crag
#

Try changing the size of your game view (put it on Free Aspect and resize the view, and also try different resolutions)

#

Your UI is probably not scaling properly, causing something to get in the way of the buttons

coral fossil
#

ah yup!

swift crag
#

Ideally, turn stuff off until you have one button and one other object that makes the button unclickable

#

(and the canvas, of course)

rocky canyon
#

more people need to do this when troubleshooting.. ^
i see soo many times w/ sooo much stuff going on in the background its hard to know what the problem actually is..
and ofc u got ur long compile times to wait thru to show a video clip ๐Ÿ˜„

viscid fable
#

i would be really happy if anyone would be willing to give out an helping hand. so i am working on a ready or not CQB FPS style game and ive been stuck on this issue for a week now for some reason the bullets sort of stick to the gun and pushes the other bullets out making them fly out and thats making the bullest fly slower than what they are supposed to be so what i did was that i tried to make a colliding checking system as to not make the bullets collide with eachother now the bullets just dont fire and are just stuck in the barrel ive also tried rotating and fixing the bullet spawn point but at some angles the bullets just dissapear just when they spawn. if anyone is willing to help i will be very happy.

timber tide
#

Well, for the collision problem you can just remove projectile colliding with other projectiles via collision matrix in the settings, or just exclude the layer on each bullet rigidbody

rocky canyon
#

make sure ur bullets are ignoring themselves.. (other bullets)

#

could use layer-based collision solutions..

#

very common occurance if u have a high fire rate..

timber tide
#

probably ignore guns too I guess if it's spawning inside

rocky canyon
#

could be clipping the gun's collider as well

rocky canyon
timber tide
#

honestly I would just make them kinematic too, but I guess you lose on on the collision detection interpolation

#

and collision callback I guess

swift crag
#

I would not let the physics system move my bullets at all

timber tide
#

yeah, but those collision callbacks giving to the exact point is pretty gooood

swift crag
#

I'd be doing raycasts forward to figure out what's in the way (doing very small steps)

#

certainly not updating just 50 times per second

pastel dome
#

ya most games are hitscan

#

getting actual speed out of physics bullets is a stretch

timber tide
#

even with rigidbody detection, stuff likes to clip through walls a lot for higher speed projectiles

swift crag
#

Random example -- H3VR does raycasts to move bullets forward by a bit at a time

#

(i think, at least; been a hot minute since i modded that)

timber tide
#

like if you're shooting a bullet at 100 units a second, you might as well make it hitscan cause the next frame it's probably going to hit anyway

#

unless you're doing some battlefield type game. I'm pretty sure most of that is actual projectiles

rocky canyon
#

bullet drop!

timber tide
#

the horrors

rocky canyon
# viscid fable i would be really happy if anyone would be willing to give out an helping hand. ...

worked on an Anti-Aircraft type gun earlier this year.. i had problems just like that.. bullets colliding w/ bullets.. then colliding w/ the gun barrel.. etc.. **edit: nevermind it seems i just offset the firing position well in front of the gun, not sure that would work for your situation since its personal arms.. and will probably fire at closer proximity to other things, might not be the most accurate)

i couldn't use raycasts in order to get the desired effect (with bullets creating that arc), well now that i think about it i probably could.. but i just used rigidbodies.. still need to build a pooling system for them tho..

rocky canyon
#

i havent done much of any testing tbh after getting it firing correctly.. (not sure what kind of physics issues a projectile moving 100 units / second causes)

timber tide
#

rb physics does an ok job, but at 100 I'd have 1 clipping through every so often

rocky canyon
#

true, true.. since my target is 100s of units away i dont have those issues

timber tide
#

may just want to do your own raycast checking if that happens

rocky canyon
#

the bullet has a CHUNKY collider.. and continuous dynamic i think

#

yup, thats all.. unity's physics engine does the rest ๐Ÿ’ช

#

i hate certain things like wheel colliders for example.. but i have to say. Unity's physics engine is pretty nice most of the times i deal w/ it

timber tide
#

yeah it's pretty decent. I've kinda just use the KCC for everything nowadays though

#

can't be bothered with the game physics parts like moving platforms and slopes ;)

rocky canyon
#

i have a paid variant of it.. and i can agree.. kinematics are the way to go when player characters are involved

#

i swap from that and a CC

timber tide
#

I have ecm2 as well which is identical but havent used it much

#

I'd say it's more like the continued supported version of KCC

rocky canyon
#

i think that cool capsule w/ a cap caused me to impulse purchase ๐Ÿ˜„

rocky canyon
#

or did i read that wrong

timber tide
#

looks pretty good. If I had all the money in the world to buy the 30+ cc solutions on the store I would

#

KCC is released free but unsupported now as the dev got hired by unity

#

I think he probably got paid for making it free too

rocky canyon
#

oh okay

timber tide
#

he makes the CC for entities I think

viscid fable
warm raptor
#

So I tried to understand how "singleton" works, and I still don't understand, also I tried to understand how static class work and I don't really understand etheir , so I just try to remove the "static" when I instanciate my class

//I changed this 
public static Client Instance { get; private set; }
// to this 
public Client Instance { get; private set; }

and it seam to work completly fine, and hasn't changed anything, but when I'm trying to call the "Died()" void from my Client script I still have this issues, even if nothing is static anymore (or at least I think nothing is static)

Assets\_Script\Multiplayer\Client.cs(335,29): error CS0120: An object reference is required for the non-static field, method, or property 'FPSController.Died()'
cosmic quail
#

and then call FPSController.Instance.Died()

warm raptor
cosmic quail
timber tide
#

Singleton isn't truely static... you can always renew the instance inside of it and get a whole fresh new state

#

they have some uses over static classes though which you should use if it's not just static read-only data or simple global utility methods

warm raptor
timber tide
#

puting them on a monobehaviour and throwing it on the scene will allow to serialize values right onto it too so really helpful for setting up the scene to a main manager type system

warm raptor
real grail
# warm raptor okay that's it, I'm now completely lost ๐Ÿ˜†

Here is a simple example to help you understand Singletons:

public class ScriptA : MonoBehaviour
{
    public static ScriptA Instance;
    
    private void Awake()
    {
        if(Instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            Instance = this;
        }
    }
    
    public void Die()
    {
        Debug.Log("Die");
    }
}

public class ScriptB : MonoBehaviour
{
    void Start()
    {
        ScriptA.Instance.Die();
    }
}
timber tide
warm raptor
cosmic quail
burnt vapor
reef tangle
#

hey, im new to unity and making a game for a school project. I found and learnt this code for a following camera, but i cant seem to edit it to make the camera only follow on the x axis. any help would be appreicated :).

warm raptor
timber tide
quartz anvil
#

Having trouble adding a force to a prefab instatiated from code. Im declaring a public Gameobject and assigning it in the editor to my prefab. im then running a method that instantiates the prefab how I want but wont apply a force to the Rigidbody?

warm raptor
slender nymph
#

show !code but i'd bet you're trying to apply force to the prefab rather than the instantiated object

eternal falconBOT
cosmic quail
reef tangle
warm raptor
real grail
#

So if the hole class is static that means all methods in the class are also static.
So all you need to do is

public static void DiedUI()
{
    PlayerUI.gameObject.SetActive(false);
    LeaderBoard.gameObject.SetActive(false);
    DeathUI.gameObject.SetActive(true);
}
quartz anvil
#
public class ShipCoreSpawner : MonoBehaviour
{
    
       public GameObject LaserShot;
   





public void FireCannon()
    {
        Instantiate(LaserShot);       
        Rigidbody rbS = LaserShot.GetComponent<Rigidbody>();
              
        rbS.AddForce(Vector3.Forward * 200f);
        
        
    }
void Update()
{

FireCannon();



}
}
#

this is the summerized version

slender nymph
timber tide
cosmic dagger
#

LaserShot is the prefab, not the instantiated object you created. reference the instantiated object and use that instead . . .

quartz anvil
cosmic dagger
eternal falconBOT
slender nymph
# quartz anvil whats that reference called / how is it accesed?

you access it the same way you access the returned object from any method that returns an object. assign it to a local variable. if you do not know how to use a method to return an object, perhaps start with the beginner c# courses pinned in this channel

cosmic quail
warm raptor
# real grail So if the hole class is static that means all methods in the class are also stat...

I don't know if that's what you said (and I apologize if it is), but in the script where the Died() methode is, Nothing is static.
Also I already tried to set the Died() method as static but I get this error 3 time (one for each UI):

Assets\_Script\Character\FPSController.cs(476,9): error CS0120: An object reference is required for the non-static field, method, or property 'FPSController.PlayerUI'
reef tangle
timber tide
#

It sets the whole vector, but you want to make a new vector with the previous yz units but with new updated x values. Just got to expand it out more.

cosmic quail
eternal falconBOT
#

:teacher: Unity Learn โ†—

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

warm raptor
warm raptor
real grail
cosmic quail
reef tangle
#

ohh that makes a lot more sense now how you can expand it. I will try that. Thanks everyone

warm raptor
cosmic quail
#

true

warm raptor
# cosmic quail true

I never thought that such a simple error could have taught me so many things, thank you so much for your help (on that note, I still have to find a way to display this UI ๐Ÿ˜† ).

inner pine
#

I purchased an asset with its source code provided and attempted to add new features using it. Upon reviewing the code, I discovered that most of its functionality is implemented without the virtual keyword, making it difficult to extend and use. I understand that such keywords should be used with clear intent, but there are parts where I genuinely believe inheritance is necessary.

How do you approach resolving such cases? Would it be appropriate to modify the asset's code to make it more extensible?

frosty hound
#

That would seem to be the approach, assuming there's no breaking updates to come with it.

#

You could always message the developer too?

inner pine
#

It seems I need to look for the developerโ€™s email. (It is not listed in the asset overview.)

tawny edge
#

I have a basic question, if i call this "for" function inside void Start() would the "for" run 3 times in a single frame?
Or would it complete it''s rrun in the third frame, meaning the "for" run incrementaly each frame?

    {
        for(int i = 0; i < 3; i++)
        {
            Instantiate(enemyPrefab, GenerateSpawnPos(), enemyPrefab.transform.rotation);
        }
    }```
slender nymph
#

loops do not happen "over time" like that, the entire loop is completed before the next line of code runs
if you want something to happen over a period of time, use a timer in update without a loop, or use a coroutine

inner pine
frosty hound
#

What's the asset?

zenith cypress
#

A simple example to show that it doesn't happen over time, is with a while(true){}, which will freeze your app since it never escapes it. So code afterward doesn't execute.

inner pine
polar acorn
steep rose
weak isle
#

Idk if this goes here but I have my player equip a wand. When I look left and right it rotates fine but up and down makes the wand weird. How would I make it rotate the same as left and right and also not look weird to other players

hallow hound
#

Hello!! im kinda new using unity and im getting so anoyed with the camara in the editor, rigth now i cant zoom in my objects and they are in the coords 0 0 0 and the editors camera is like soooo far out but it doesnt let me zoom in, like i can zoom out but when zooming in it just stops

steep rose
steep rose
hallow hound
steep rose
#

it will move the editor camera near the object, of which you should be able to zoom in

hallow hound
#

yeees thank you, been more anyed with that camara than coding itself haha

inner pine
#

It seems that modifying the code might be the best solution. I will discuss this issue with the developer. Thank you!

hallow hound
#

hey another question, this anoying error is there almost since i started the proyect, what is it?

vocal wharf
flat sphinx
#

is there a function for "return number thats further from 0"

#

ik theres piping abs into max but i'd rather it be inplace

#

and the only way i can think of to have that is multiplying it by the var's sign after which feels yucky

#

nvm got it

zenith cypress
grizzled fulcrum
#

So I've been having two issues I don't quite know how to fix
For one, I'm trying to build a game in the same aspect ratio for a phone, but for Windows, so I tried setting the resolution on Player Settings as 1080x1920, and 720x1280, and fullscreen mode as "WIndowed", both without success, as the game launches with a wider than intended screen
Any clues how I can fix this?

vast stirrup
#

Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(worldPosition);

apparently I am doing this wrong. how do I make my character look at the mouse, but never look up or down. how?

rich adder
vast stirrup
#

how

rich adder
#

you assign the target Y pos to height you want

rich adder
#

the camera resizes with the resolution, you probably did not align everything using the same res as your window/player build

#

even with the same aspect ratio you have more pixels

grizzled fulcrum
#

Hm, I wonder if that's related with the fact the Canvas I set doesn't appear with the title of the game either

rich adder
#

you'd have to check your canvas scaling mode and whatnot

#

the resolutions you pick in game view mode are important for testing, after that they do not affect the player

grizzled fulcrum
#

The whole pixels per unit schtick?

rich adder
#

ideally you would have Scale With Screen

#

then set a reference base resolution (eg if i target 16:9 i usually start at a low HD like 1280 x 720)

grizzled fulcrum
#

I probably didn't do either of those, lemme open the project and check some stuff to see if it helps

#

I think it's the typical case of "What I see in Game Mode I presume will be there in Build"

rich adder
#

thats strictly UI btw, for sprites it gets tricky because there is no such component that does it for you

rich adder
grizzled fulcrum
rich adder
grizzled fulcrum
#

I think the Game worked because I specifically set it to be ran on a 9:16 ratio, while also keeping the camera to the same size

#

As for the Canvas, eh... red circle is where the sprites and stuff for the game are. I should probably screenshot the Canvas itself, no?

#

Yeah, I probably found the issue

#

One second

hallow hound
vocal wharf
#

also does it keep coming back if you delete the error?

polar acorn
dense bridge
polar acorn
dense bridge
hallow hound
vocal wharf
hallow hound
hallow hound
#

literally this all i have

#

i mean what im doing still works but just wanted to get rid of that error

steep rose
dense bridge
#

can you search for the script in the project, select it and show the inspector please ?

steep rose
#

yes, if you do not need or want it you should not have it as it may cause issues like this.

hallow hound
#

Ohh

rich adder
#

new blank templates are borked

hallow hound
#

where do i delete that?

steep rose
#

you should be able to do so via package manager

#

just get rid of the version control package

rich adder
#

give unity a restart too mayb

hallow hound
#

thank you guys!

grizzled fulcrum
#

Huh, now it's way too big

#

I just redid the Canvas as a whole and adjusted it with Scale with Screen, dunno what went wrong this time

rich adder
grizzled fulcrum
rich adder
#

if its a bigger pixel area it has to compensate

grizzled fulcrum
#

Oh right. Currently it's 720x1280, that's prolly the issue

#

Lemme increase back to 1080p

grizzled fulcrum
rich adder
grizzled fulcrum
grizzled fulcrum
rich adder
#

also are you making a clean build each time ? and new folder?

grizzled fulcrum
#

Yup

#

I'll give it another shot in a different folder

#

Is it because it tries to emulate the big screen but my computer screen is not as big to fit it perhaps?

rich adder
# grizzled fulcrum Egh

you have to anchor/resize things accordingly. Espcially the top logo
also you can tell the P and e Letters are pretty much the same distance from edges like you see them in game view.

grizzled fulcrum
grizzled fulcrum
rich adder
#

see link ๐Ÿ‘†

grizzled fulcrum
#

Yea, I was gonna ask about it as soon as you sent it lol

#

Mmm, I wish I could just see how big the thing actually is when I make the game, so I don't need to rebuild it all the time

rich adder
grizzled fulcrum
#

Well yeah, albeit when building it becomes different it's a little bit concerning

rich adder
#

thats again, not proper layout / anchoring with UI will do that

#

for sprites, its a similar concept but there is no built component for sprite renderers
(canvas resizing i mean)

warm raptor
#

Hi! Is it possible to have an error in the unity console that isn't actually an error?
I was looking for a solution for 2 days to my error in my C# script, I left for about 1 hour to do other things, and miraculously when I came back my script was recompiled and no more errors appeared, even though I hadn't changed anything.

slender nymph
late burrow
#

wait do chars actually have 65k number capacity?

warm raptor
polar acorn
slender nymph
warm raptor
late burrow
#

thats a lot of space inside single char i could mash in many data into string and extract char by char

real grail
slender nymph
polar acorn
late burrow
#

it never worked well with strings

#

i will have to base64 it each time i want to hold it

polar acorn
#

It works fine, as long as you don't care about your string actually containing anything readable

warm raptor
polar acorn
warm raptor
slender nymph
#

i guarantee that is not the line the error you just posted was referring to

polar acorn
#

This line doesn't

#

so you probably changed more in the code which changed which line this was

warm raptor
slender nymph
#

i don't need you to explain the whole problem. the error was referring to something else and you've fixed it if the error is no longer appearing

polar acorn
#

It looks like you tried to access a non-static variable called PlayerUI using the class name

#

when you'd need to tell it which FPSController you wanted to access PlayerUI from

warm raptor
#

so basically I have a script "client" that handle my websocket connection, and with this script I was trying to call a void in an other script that basically show a certain UI when the player die, and the issues was that my script was using a static class, and the void Died() wasn't static, so it gave me an issue, so I decided to make my "client" script non static, but it was still telling me that I couldn't call the Died() void because it wasn't static, so I tried to make it static and this gave me the error that I've mantionned earlier. then I decided to remove the static atribute from my Died() void and left unity with an error, then when I came back 1hour later, the script compile again for no reason, and the script was fix . (I hope I've explained it well and that my English isn't too bad. ๐Ÿ˜… )

polar acorn
#

If a function is static, you call it with ClassName.Function(). If the function is not static, you have to call it on an instance of that class

warm raptor
slender nymph
late burrow
#

ok but what stops me from turning id into char no matter how i edit it i cant make it char

polar acorn
#

Strings are many chars

late burrow
#

yes im trying make it char instead

#

i want make string from multiple chars

#

storing multi digit int in single char is great for coding

polar acorn
late burrow
#

i want everything to be char

polar acorn
#

A string is many chars

late burrow
#

yes

warm raptor
polar acorn
#

Which char do you want from id.ToString("D2")

late burrow
#

so why it errors out if i try make id char instead

#

(char)id

polar acorn
late burrow
#

ok so

#

(char)index + (char)id + (char)rot.x + (char)rot.y + (char)rot.z
why this wont work

slender nymph
late burrow
#

because for networking i need 3 copies of same var and storing everything in single var is much less code

polar acorn
late burrow
#

cannot convert int to string

polar acorn
slender nymph
slender nymph
late burrow
#

ok so adding another () around them should stop it but it doesnt

polar acorn
late burrow
#

string

polar acorn
#

You're going to get a char as the result

#

Char is not string

#

You'd need to store it in a char

late burrow
#

i want mash chars together

polar acorn
#

Then you wouldn't be adding them

late burrow
#

oh you mean that cursed char[] thing

#

and i need convert it to string then

polar acorn
#

Don't use a string as a ghetto byte[] for networking because you are scared of the data type

slender nymph
#

what do you think is the result of this operation: 'a' + 'b'

late burrow
#

i expected it wont autoconvert them to ints while in char format

polar acorn
#

chars are numbers

#

when you add two numbers, it gives you a number

late burrow
#

ok so solution is starting addition with ""

polar acorn
#

Solution: Stop doing whatever the fuck you're doing

void thicket
late burrow
#

i know i can pack it tighter by storing it as bytes but then it will be pain to reuse into code

grizzled fulcrum
#

@rich adder
Thanks a bunch for the help, I managed to fix what I needed

late burrow
#

single char is very nice in every aspect

polar acorn
slender nymph
late burrow
#

no i can do something like
transform.position = new vector3(string[2], string[3], string[4])

#

its super simplified

slender nymph
#

what's going to be even worse is attempting to store a shit load of data in single chars, you cannot fit an entire integer in a char. you cannot fit an entire float in a char. that is not going to work

polar acorn
#

How is it that every fucking time you post here you're doing some absolutely wild bullshit and refuse to do the sane and simple thing that would solve your problem instantly

#

This has to be some kind of psy-op

rich adder
#

anuked secret ai

void thicket
#

Lol what

polar acorn
polar acorn
#

and literally no one ever at any point in history has ever done shit this wrong

slender nymph
rich adder
#

ai would also use bytes here ๐Ÿ˜†

rich adder
#

you missed the entire point

void thicket
#

Anyways int also does not even fit in a char

polar acorn
slender nymph
late burrow
#

im just saying about solutions that fit are quite more complicated than what im doing mostly

polar acorn
late burrow
#

since theres literally no built in method to make vector from string

slender nymph
void thicket
late burrow
#

yeah i did i only wanted know why cant i add chars

polar acorn
#

Pretty easily

#

But what you're doing isn't addition

#

you're doing what can only be described as a "thought crime"

#

You seem to be under the assumption that you're literally the only person who has ever needed to transfer a vector over the internet.

#

This assumption is false.

#

There are ways to do this. Well-trodden ways with decades of follies behind them.

#

Converting numbers into chars and packing them into strings to send over the network to unpack into bytes then back into chars then cast back into ints is not it

naive pawn
teal viper
late burrow
#

dam ppl really want extend discussion as much possible

#

here i got the solution already

teal viper
#

Yes, that's concatenation. They get converted to strings here

#

This is not "char addition" though

naive pawn
#

"A" + " " -> "A "
'A' + ' ' -> 'a'

polar acorn
#

(a.k.a. you are using 8 times as much memory as just storing the fucking vector)

naive pawn
polar acorn
naive pawn
#

if you were going to stringify this info, you would probably just interpolate the string

#

if you're trying to serialize it, then.. do that instead of.. whatever this is

void thicket
naive pawn
polar acorn
#

They assume it's "unnecessary"

naive pawn
#

which is why i gave that link

polar acorn
#

It's not the first time

#

Probably not even the hundredth

naive pawn
#

christ

spark sinew
#

hi y'all, if I want to transfer data from a sensor to a quest, for a game, how do I set up a connection between the two? I am ultra beginner. I heard from people we have to use a UDP ?

spark sinew
#

a Lidar that detect pedestrian positions (x,y)

ripe shard
#

Does that sensor have microcontroller attached to it with a WiFi, bluetooth, usb, RJ45 or other module for networking?

spark sinew
#

yes, there will be

#

WiFi

#

and we can be on the same network

ripe shard
#

Does it already send the data? How do you configure what it sends and where to?

brisk nest
#

!code

eternal falconBOT
brisk nest
#

Im having an issue where my player is constantly gaining y value and floating upward when i move for the first time. Here my movement code https://hastebin.com/share/eneloyobob.csharp
does anyone see anything wrong with it that could be causing this?

wintry quarry
#

Do you have any other scripts, and/or does your gravity happen to be set to a positive y value or something?

#

How is this code even getting invoked?

#

Nothing seems to call HandleAllMovement. Presumably you have at least one other script involved.

wheat canopy
#

Why does this not work? If slider.value = 1 then the boolean is true. Does CS not work this way?

slender nymph
#

= is the assignment operator, not the equality operator

wheat canopy
#

how did i forget this lmao

#

live, love, =

wheat canopy
slender nymph
#

there are beginner c# courses pinned in this channel if you don't know how to do basic comparisons

spark sinew
wheat canopy
slender nymph
#

like i said, there are beginner courses pinned in this channel

inland mesa
#

This is a script attatched to the player model, when I click down the debug log isn't popping up, anybody know why?

slender nymph
#

you need to start by configuring your !IDE

eternal falconBOT
pure drift
#

!code

eternal falconBOT
wintry quarry
pure drift
#

https://paste.ofcode.org/byjkvyva9tuTtmKUSaA4D5 does anybody know why my explosion spawns so far ahead of my enemy when my player colldies with the enemy i tried fixing it by resetting explosion prefab position so i assume its something to do with the code

slender nymph
#

GameObject exploPrefab = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
it spawns on this object's position

dense bridge
#

Instantiate(explosionPrefab, transform.position, Quaternion.identity); you need transform of the hit collider

pure drift
#

ohh got it thank you both

#

sorry if it maybe obvious but what would be the syntax of implementing this because i tried playing around with it but all i get is an error

wintry quarry
#

the syntax is - use the position that you want instead of the position of the obejct this script is on

pure drift
wintry quarry
#

And why would you want that anyway

#

you don't want the position of the collider

#

you want the point where the collision happened presumably

pure drift
#

oh ok right now im just researching the contact points and it seems to be what im looking for not too sure as im still kinda new to unity

remote torrent
#

how do i offset a box collider?

#

in the c#

remote torrent
#

sorry i meant 2D, would that still work?

pure drift
#

@wintry quarry i struggled for 2 hours just for the solution to be two lines of code thank you

cerulean bear
#

why are my laser beams like this?

using UnityEngine;
using static Enemy;

public class LaserBeam : MonoBehaviour
{
    public GameObject player;
    public Transform spawnLocation;
    public bool isShooting;
    public Vector3 spawnRotation = new Vector3(0, 0, 0);
    public Vector3 offSet = new Vector3(0, 2, 0);
    public float laserSpeed = 100f;

    void Start()
    {

    }


    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            isShooting = true;
        }
        else
        {
            isShooting = false;
        }
        if (isShooting)
        {
            Clone();
        }

    }
    void Clone()
    {
        Instantiate(gameObject, player.transform.position + offSet, Quaternion.Euler(spawnRotation));
        transform.Translate(Vector3.up * laserSpeed * Time.deltaTime);
        if(transform.position.y > 6)
        {
            Destroy(gameObject);
        }
    }
    void OnTriggerEnter(UnityEngine.Collider other)
    {
        if (other.CompareTag("Enemy"))
        {
            // Get the Enemy component from the collided object
            Enemy enemy = other.GetComponent<Enemy>();

            if (enemy != null) // Ensure the object has an Enemy script
            {
                enemy.TakeDamage(1); // Call the method on the instance
                Destroy(gameObject);
            }
        }
    }
}
cerulean bear
#

do I have to increase the speed to like 800 it's currently at 100

#

Please ping me when you reply

eager spindle
#

this should be put in update

eager spindle
# cerulean bear why are my laser beams like this? ``` using UnityEngine; using static Enemy; p...

ok so there's several things to take note here

โ€ข this script is on a LaserBeam. If this is attached to the LaserBeam game object, every time you call Clone you're calling it on every laser beam. You're doubling the number of laser beams

โ€ข you should be moving the laser beams in Update. doing it in Clone only moves it once

โ€ข in Clone, you're moving the current laser beam, not the instantiated one

โ€ข in Update, your Input.GetKeyDown code can be simplified to like 2 lines

silent falcon
#

I would like to ask why the non-null comparison is shown expensive? Then what should I do? >>>

eager spindle
#

does it do the same if you call .CompareTo

brisk nest
#

Im trying to get my player to fall on sloped terrain but the issue is they remain floating after they walk off the terrain, and the y level drops by around 0.3 a second. Any ideas? All player scripts: https://hastebin.com/share/wikebeyudu.csharp

silent falcon
eager spindle
#

There's a video on making better player controllers with tricks like these but I need to find it

eager spindle
silent falcon
#

Rider

eager spindle
#

first time seeing this but I don't think it's much of a concern

silent falcon
swift crag
#

I don't get this suggestion in Rider

#

I'm using 2024.1.6

north kiln
#

You have turned it off

#

You can turn it off via the alt-enter menus too if you want

warm mason
#

why does unity gray out and not let me edit some options in the inspector?

#

i add a cube and it doesn't let me change the surface inputs 0.o

polar acorn
#

You can't change the default material

#

Give it a material and you will be able to

warm mason
#

tank u!

fervent plover
pale vault
#

Just confirming with you guys, are Input.GetAxis("Mouse X") and Input.GetAxis("Mouse Y") framerate independent, thus not needing any multiplication with Time.deltaTime?

timber tide
pale vault
wanton stirrup
#

What would be the best way to get into C# and get enough knowledge about it, so I can start making stuff in Unity? My problem is that almost all the tutorials I found are for people who have no idea about programming, but I have coded in other programming languages before. I have also tried out C# once, but sadly I forgot almost all of it, so I want to refresh my knowledge. There are some more advanced concepts though, I donโ€™t understand yet, like static classes, private and public variables, etc.
I canโ€™t really learn by only reading the documentation :(
I appreciate any advice!

burnt vapor
#

Or look up the documentation, and try to make an application

#

If you have knowledge of programming, possible ask tiny parts to ChatGPT and try to apply those while learning how the keywords apply relative to what the documentation specifies

#

It's usually what I'd do

dense bridge
burnt vapor
#

There's a big difference between telling complete beginners to just let ChatGPT write their code and taking AI code as reference when learning a language as an experienced general programmer

dense bridge
burnt vapor
#

Considering you didn't understand why this was a bad idea to suggest, I really don't feel like having yet another discussion if that's what you're going for

dense bridge
burnt vapor
#

Beginners take AI code as it is and end up with horrible code and no idea how to debug. There have been plenty of users in this server seeking help with strictly AI code and it is a waste of time

#

Alrighty ๐Ÿ‘

eternal needle
# wanton stirrup What would be the best way to get into C# and get enough knowledge about it, so ...

i agree with what fusedqyou is saying, look into tutorials and just skip the stuff obvious to you. For c# specifically, if you have a good idea of programming in other languages you could even try problem solving sites like leetcode or whatever else is ppopular. I wouldnt call "static classes, private and public variables" advanced concepts though, I do question how much experience you have though if public/private specifically is new to you. A lot of languages still have this
As for unity specific stuff, i looked at tutorials just to find out what exists/what its used for. Then id read through the docs and experiment with it in unity

flat sphinx
#

*generate code for you

dense bridge
#

Personnaly tutorials and doc was a big no to start, but i'm no pro in programming. There is different ways to learn for different people, but i think the worst way to start is having samples by AI because a little bad prompt can lead you to terrible sample, big waste of time at least, big bad habbit to erase at worst.

wanton stirrup
naive pawn
#

you could just have chatgpt explain examples instead
still not 100%, but at least there's less oppurtunity for hallucination if you're hellbent on using it

naive pawn
wanton stirrup
dense bridge
naive pawn
#

(statics and access control are pretty fundamental for OOP for example, but advanced for say, python where OOP itself is somewhat advanced)

wanton stirrup
#

Yeah maybe I will just ask ChatGPT to explain me the basic things, and then try to put together some simpler console applications

#

Just to get the hang of C#

dense bridge
naive pawn
wanton stirrup
naive pawn
#

in that case, you may want to research that specifically?

#

OOP concepts, i mean

wanton stirrup
#

Ohh maybe I should do that, since I'm not even sure when is OOP used O_o

dense bridge
wanton stirrup
naive pawn
wanton stirrup
naive pawn
#

in, i think most non-fp/sh/asm languages, objects are built-in to the language structure, but creating your own classes is somewhat advanced in imperative languages

#

for example in python, instanceof and class are where OOP happens

dense bridge
timber tide
#

just make small games and learn from your mistakes

#

dont start off with dream game

wanton stirrup
wanton stirrup
timber tide
#

perfect idea. Flabby birb for physics

#

oh I guess pong itself does have physics right right

astral falcon
#

And now combine to flappy pong ๐Ÿ˜‰

timber tide
#

I think tetris is best learning game to make since it forces you to learn arrays, and uses the update loop so it's not fully static like checkers

dense bridge
#

arrays and for loops intricated

static ice
#

Hi guys. I have frozen rigidbody constraitrs in X and Y in my unity editor but when I play game, the tick disappears and my player body is able to rotate on X and Y. Why is this happening? I searched online and people are freezing rigidbody in code, but there would be a better way than this...

timber tide
#

you sure it's not already being changed in code? Either way, adding it in start is fine too

dense bridge
#

press ctrl+f and research "Rigidbody.constraints" in VS

burnt vapor
timber tide
#

sound pretty legit

static ice
#

yeah your right there is a rb.freeze n my script. how does one make it freeze on x and y only?

#

using code

tired slate
#

Hi, I have a problem with detection when my hero touch the tile with city in 2D game, anyone can help me? I'm new in coding and i don't know how to do this

burnt vapor
#

Explain the problem with detection and optionally share related code if it's not related to physics

tired slate
# burnt vapor Explain the problem with detection and optionally share related code if it's not...

My hero move by WASD and he "jump" tile by tile, but when he jump on city tile the message isn't send to me. tile with city and my "hero" have BoxColider
and this is a code for my hero to detected the city
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("City"))
{
// Wyล›wietl komunikat w konsoli
Debug.Log("you are in city!");
}
else
{
Debug.Log("it isn't a city!");
}
}

#

it's look like this:

#

and the brown tile is city

burnt vapor
dense bridge
tired slate
burnt vapor
little meteor
burnt vapor
#

Yeah I don't think collission is really required either, but maybe I am missing something specific

dense bridge
little meteor
little meteor
dense bridge
burnt vapor
#

I just know plenty of C#

#

But collission and things like this are some of the things I do know

dense bridge
winter aspen
dense bridge
dense bridge
tired slate
little meteor
#

how can i do this?

dense bridge
tired slate
#

yes and the position Z is the same like hero

dense bridge
tired slate
#

I only set the layers for hero and every tiles at "3: Tile"