#💻┃code-beginner

1 messages · Page 470 of 1

marble hemlock
#

are they all just friends

hollow sedge
#

thats harrasment i just want to make sure that people are able to get the help they need from this server

short hazel
#

Using the log sashok provided earlier will tell you what the ray has hit

hollow sedge
#

as i hope i will recieve

marble hemlock
timber wedge
#

gulp, I have a bad feeling....

marble hemlock
#

i have a capsule thats a physical object meant to allow me to see where the game controller is

#

kay hold on

#

yeah its the player position object

#

i dont even know what to do about that

#

i mean the quick and obvious solution feels like just deleting the object, but then i wont be able to tell where the player is

short hazel
#

You can use layers instead of tags, and pass a LayerMask to the Raycast, that will tell it to ignore everything except the layer you've selected

marble hemlock
#

so tags bad

short hazel
#

In your specific case, layers are a better solution

marble hemlock
#

okay i dont know how to handle layers for this, i'll be right back

short hazel
#

Avoid GPT for pure code generation, instead rely on online documentation.
GPTs are not intelligent, they spit out code to look like what they were trained on, and make mistakes sometimes

thorny junco
willow scroll
#

I would only recommend using ChatGPT if you know what you are doing. For example, if I have a struct and I need to quickly create a property drawer with buttons in the Inspector for it, I give a fast request to ChatGPT. But since I know how to do it, I will be able to correct the mistakes and rewrite some parts to match my style, and this way, it will be the same as without AI, but faster

thorny junco
#

also amazing

marble hemlock
#

hey should i be using fixedupdate

#

for raycast

willow scroll
# thorny junco Thank you kind and handsome friend

Only use it if you know how to implement it without it, but when writing code, which is new to you, I would definitely recommend using Stack Overflow and docs, since ChatGPT is usually not that reliable

marble hemlock
willow scroll
willow scroll
eternal needle
short hazel
#

It's a physics query applied once and where results are returned immediately, it does not need to be in FixedUpdate

marble hemlock
#

so what you're all saying is that i should go to bed and give up on this

short hazel
#

What?

marble hemlock
#

oh i have to get up in half an hour anyways damn

#

how do i define the rate for fixed update

eternal needle
#

raycasts dont need to be anywhere specific. It depends how you're using the raycast or the result of it.
Like if you want something to move in the world respecting physics then it'd make sense to use fixed update

#

you dont, its already defined to be 50 per second

short hazel
#

You don't worry about this and keep your code where you raycast in Update.

#

You just need to create a layer in Unity, a LayerMask in your code, and pass the mask to the Raycast.
And change the layer of the interact object, of course

marble hemlock
#

might be getting there

#

found problem

#

a single bracket did that

#

IT DISAPPEARED

#

THE OBJECT

#

okay its still there
i can walk into it but the moment i added the layer it turned invisible

short hazel
#

Layers do not turn objects invisible by themselves

marble hemlock
#

mine might be a lil magical

short hazel
#

Some code is doing that, maybe the SetActive() call in your script targeting the wrong object?

#

Also what layer did you choose?

marble hemlock
#

uncertain but i found a new problem i should fix

#

i chose layer 8

short hazel
#

Which is named?

marble hemlock
#

Interactable

short hazel
#

Good, on your main camera make sure this layer is rendered, it's a setting on the Camera component

marble hemlock
#

i am the fool
it worked
thank you

#

freedom...

thorny junco
marble hemlock
abstract copper
#
    public void PackagePickedUp(GameObject package)
    {
        Vector3 localPosition = spawnArea.InverseTransformPoint(package.transform.position);
        if (col.bounds.Contains(localPosition))
        {
            packagesInSpawnArea.Remove(package);
            currentPackageCount--;
            Debug.Log("Picked up in bounds");
        }

        Debug.Log("Picked up");
    }

    public void PackageDropped(GameObject package)
    {
        Vector3 localPosition = spawnArea.InverseTransformPoint(package.transform.position);
        if (col.bounds.Contains(localPosition))
        {
            packagesInSpawnArea.Add(package);
            currentPackageCount++;
            Debug.Log("Dropped in bounds");
        }

        Debug.Log("Dropped");
    }

I cant get the code in the if statements to execute, do I need to be looking in the local space or world space? I tried both but I just cant get stuff to work

marble hemlock
#

how do i apply a function to only the thing the raycast is hitting, and not all things that have that LayerMask?

eternal needle
languid spire
eternal needle
orchid kite
#

can someone help me i am making a game on unity and i want my monkey to throw bananas but its not working i made a firepoint and put it where i needed to on the attack part and i did object pooling and put like 10 bananas at that area as well where they are all hidden so im not sure whats wrong but heres the code


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

public class BananaThrow : MonoBehaviour
{
    [SerializeField] private float speed;
    private bool hit;
    private BoxCollider2D boxCollider;
    private float direction;
    private float broke;

    private void Awake()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    private void Update()
    {
        if (hit) return;
        float movementSpeed = speed * Time.deltaTime;
        transform.Translate(movementSpeed, 0, 0);

        broke += Time.deltaTime;
        if (broke > 5) gameObject.SetActive(false);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        hit = true;
        boxCollider.enabled = false;
    }

    public void SetDirection(float _direction)
    {
        broke = 0;
        direction = _direction;
        hit = false;
        boxCollider.enabled = true;
        gameObject.SetActive(true);

        float localScaleX = transform.localScale.x;

        if (Mathf.Sign(localScaleX) != direction)
            localScaleX = -localScaleX;

        transform.localScale = new Vector3(localScaleX, transform.localScale.y, transform.localScale.z);
    }

    private void Deactivate()
    {
        gameObject.SetActive(false);
    }
}

this is the banana throw code

#

and this is the monkey attack code

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

public class MonkeyAttack : MonoBehaviour
{
    [SerializeField] private float cooldown;
    [SerializeField] private Transform firePoint;
    [SerializeField] private GameObject[] bananas;
    private MonkeyScript playerMovement;
    private float cooldownTime = Mathf.Infinity;

    private void Update()
    {
        if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())
            Attack();

        cooldownTime += Time.deltaTime;
    }

    private void Attack()
    {
        cooldownTime = 0;

        bananas[FindBanana()].transform.position = firePoint.position;
        bananas[FindBanana()].GetComponent<BananaThrow>().SetDirection(Mathf.Sign(transform.localScale.x));
    }

    private int FindBanana()
    {
        for (int i = 0; i < bananas.Length; i++)
        {
            if (!bananas[i].activeInHierarchy)
                return i;
        }

        return 0;
    }
}
languid spire
#

!code

eternal falconBOT
orchid kite
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class MonkeyScript : MonoBehaviour
{
    public float speed;
    private float move;
    public float jump;
    private Rigidbody2D z;
    public bool isJumping;

    //scale values of monkey
    float zy = 0.56f;
    float zx = 0.53f;

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

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

        //movement
        move = Input.GetAxis("Horizontal");
        z.velocity = new Vector2(speed * move, z.velocity.y);

        //jump
        if (Input.GetButtonDown("Jump") && isJumping == false)
        {
            z.AddForce(new Vector2(z.velocity.x, jump));
        }

        //change directions
        if (move > 0.01f)
            transform.localScale = new Vector3(zx, zy, 0);
        else if (move < -0.01f)
            transform.localScale = new Vector3(-zx, zy, 0);
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        //ground check
        if (other.gameObject.CompareTag("Ground"))
        {
            isJumping = false;
        }
    }

    private void OnCollisionExit2D(Collision2D other)
    {
        //ground check
        if (other.gameObject.CompareTag("Ground"))
        {
            isJumping = true;
        }

    }

    //attack

    public bool canAttack()
    {
        return move == 0;
    }

}

and this is my movement code jump code and ground check and the start of the canAttack

ivory bobcat
#

How to post !code (use the large code blocks guide rather than the inline guide)

eternal falconBOT
orchid kite
#

can anyone help thanks

willow scroll
faint agate
#

Hello, so im trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse was top left of screen on start, the first person cam will be looking top left).
https://gdl.space/etapuxitoy.cs
i tried getting rid of cursor lock but it didnt help
https://gdl.space/uxaziwezay.cs
this script is attached to the camholder and Transform cameraPosition is on the player

fickle plume
dusky tusk
#

the box here is my player, for some reason when im on the wall and hold down the key that goes to the wall(in the pic i held down a to go left to the wall) my player just gets stuck vertically, no gravity, it returns to normal when i release the key though

#
void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        if (isGrounded() && Input.GetButtonDown("Jump")) { 
            rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
        }
    }

    private void FixedUpdate() {
        rb.velocity = new Vector2(horizontal*speed, rb.velocity.y);
    }

    private void flip() {
        if (facingRight && horizontal < 0f || !facingRight && horizontal > 0f) {
            facingRight = !facingRight;
            sprite.flipX = facingRight;
        }
    }    

    private bool isGrounded()  {
        return Physics2D.OverlapCircle(groundCheck.position,0.2f,groundLayer);
    }```
#

the tilemap uses a tilemap collider and a composite collider

abstract copper
teal viper
wintry quarry
wintry quarry
#

In real life you wouldn't be able to magically push against the wall in the air like that

abstract copper
teal viper
dusky tusk
abstract copper
#

i didnt understand which values you mean

teal viper
abstract copper
#

first is the position of the object and second the col.bounds

#

maybe i pick it up too fast?

dusky tusk
tired surge
#

this isent about coding but does anyone know how to share a project with a friend i have look everywhere but have found nothing to help

teal viper
teal viper
abstract copper
#

should they be thick as the object?

#

oh i get it now

#

gonna have to rewrite the pickup because then i cant pick them up, the trigger of the area blocks it so it cant access the collider of the item

grand badger
#

you likely won't have any further issues with this specific system, but learning to deal with each issue/case will be easier once you're into the My code WILL have bugs mindset

#

of course we're going for the perfect system right off the bat, but let's face it it's not likely to happen xD
in your case the Scene view had all the necessary info regarding why the pickup doesn't work (-- you can see the "Scene" even if you're in "Play" mode).

tired surge
teal viper
tired surge
teal viper
#

I mean, it could be several GB in size. You can share it however you like. Google drive is one option.
But as I said earlier, version control system would be better.

#

I'm not sure gmail allows you to share files of such size.

teal viper
tired surge
#

it deleted the whole file when i sent it to my friend

#

he just got a gmail with nothing

teal viper
#

Well, I'm not sure if we can help you with gmail issues here, but it's probably the size limitation as I mentioned.

tired surge
#

yeah probably

#

i will try version control system

abstract copper
#

I got it to work now one time but it just wont detect it again

#

they spawn on the min y of the bounds

#

so they should be in it

mint grotto
#

someone help im kinda new at unity but how to u make the object move around smoothly

grand badger
abstract copper
#

so thats why its out of bounds

steep rose
abstract copper
#

by the time function is called its out of bounds already

mint grotto
#

what

grand badger
#

nice

steep rose
mint grotto
steep rose
#

Yeah dont do that

tired surge
steep rose
teal viper
#

Might want to provide a better explanation

steep rose
#

Also you should not be using gmail with version control

#

Dunno why you would do that

tired surge
#

when i press on for example attributes i just get an error saying "the specified repositry couldn't be found: then my project name"

steep rose
#

You moved the repository file location

#

It should say locate or something along those lines

#

If you click that you will need to go to your rep folder

tired surge
#

how i just downloaded the version control system

steep rose
#

What application are you using for git

teal viper
#

Maybe take screenshots if it's hard to explain in words.

tired surge
#

unity version control

teal viper
#

And how did you "download" it?

#

Because it's not something you just download normally

steep rose
#

If you use unity version control and not the unity engine you need the Desktop Client so no you do not need this

#

You still dont need it even if it's highly recommended from you

teal viper
#

Ok, my bad. You might need to download the client, not the version control system.
What I'm trying to say is that they should be providing more info and be more clear as to what they're doing and what problem they have.

#

Because so far it was like half guessing. Really annoying.

stark summit
#
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    public float speed = 5.0f;
    public float jumpHeight = 2.0f;
    public float gravity = -9.81f;

    private CharacterController controller;
    private Vector3 velocity;
    private bool isGrounded;

    public Transform cameraTransform;


    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
       
        isGrounded = controller.isGrounded;

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


        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 cameraForward = cameraTransform.forward;
        Vector3 cameraRight = cameraTransform.right;

        cameraForward.y = 0;
        cameraRight.y = 0;

        cameraForward.Normalize();
        cameraRight.Normalize();

        Vector3 move = (cameraForward * moveVertical + cameraRight * moveHorizontal).normalized;

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

        if (move != Vector3.zero)
        {
            transform.forward = move;
        }
        
        if
    (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
//right here AI keeps telling me that i should add (* Vector3.up) but then i get a error if added
    }
}
//code
grand badger
#

if you REALLY have to move upwards, you can do this controller.Move((velocity + Vector3.up) * Time.deltaTime);, but I'm fairly sure you don't...

sleek gazelle
#

Any idea what's wrong about my code?

    [SerializeField] new Renderer renderer;
    Texture2D originalTexture;

    // Start is called before the first frame update
    void Start()
    {
        originalTexture = (renderer.material.mainTexture as Texture2D);
        int height = originalTexture.height;
        int width = originalTexture.width;
        float x = Random.Range(0,249092);
        float y = Random.Range(0,249092);
        for (int i = 0; i < width; i ++) {
            for (int j = 0; j < height; j ++) {
                if (originalTexture.GetPixel(i,j).a == 0) {
                    originalTexture.SetPixel(i,j, new Color(0,0,0,0));
                }
                else{
                    if(Mathf.PerlinNoise(x + i,y + j) < Random.Range(0.000f,1.000f)){
                        originalTexture.SetPixel(i,j, new Color(0,0,0,0));
                    }
                }
            }
        }
        renderer.material.mainTexture = originalTexture;
    }

It makes unity freeze

grand badger
#

that aside, calling controller.Move() twice on the same frame/method is a bad practice and could bring forth issues

grand badger
#

or not, idk.. but yeah if that's the case don't do it 😛

silent vessel
#

Anyone can help me I was just working as usual and any new scripts I created dont use unity

sleek gazelle
grand badger
sleek gazelle
#

The random values are just offsets for the perlin noise

eternal falconBOT
grand badger
#

also, have you tried commenting out JUST THE START method here? and see whether it still freezes

sleek gazelle
sleek gazelle
grand badger
#

no, I said comment out

#

aka delete

sleek gazelle
#

Ah

#

Yeah, it's the thing that makes unity freeze

silent vessel
grand badger
#

well 250k operations shouldn't make it freeze, but if you have, say, 100 objects that have this, it might take a long time

meager sentinel
#

The part where it destroys the bullet is disabled

meager sentinel
#

ah yeah, and sorry for answering late, my light had went out

sleek gazelle
#

Might be because all the objects that are running this script are editing the same texture

#

How can I create an instance of a texture?

#

Looks like it is an instance already

grand badger
#
var pixels = originalTexture.GetPixels();
for (int i = 0; i < width; i ++) {
    for (int j = 0; j < height; j ++) {
        var index = i + width * j;
        var x = Random.Range(0,249092f);
        var y = Random.Range(0,249092f);

        if (pixels[index].a == 0) { pixels[index] = Color.Clear; }
        else if (Mathf.PerlinNoise(x + i, y + j) < Random.Range(0f, 1f)) { pixels[index] = Color.Clear; }
    }
}

originalTexture.SetPixels(pixels);
originalTexture.Apply();
renderer.material.mainTexture = originalTexture;
grand badger
sleek gazelle
#

That's much faster

#

But sttill no noise on my texture lol

#

I'll try to figure that out

grand badger
sleek gazelle
grand badger
grand badger
stark summit
sleek gazelle
silent vessel
grand badger
sleek gazelle
grand badger
#

np good luck

sleek gazelle
#

I found why it doesn't work:

ArgumentException: Texture2D.SetPixels: texture uses an unsupported format. (Texture 'RoadWorkSignTextureWithTransparency')
UnityEngine.Texture2D.SetPixels (System.Int32 x, System.Int32 y, System.Int32 blockWidth, System.Int32 blockHeight, UnityEngine.Color[] colors, System.Int32 miplevel) (at <2d8783c7af0442318483a199a473c55b>:0)
UnityEngine.Texture2D.SetPixels (UnityEngine.Color[] colors) (at <2d8783c7af0442318483a199a473c55b>:0)
TextureNoise.Start () (at Assets/Scripts/TextureNoise.cs:28)
sleek gazelle
stark summit
deft grail
#

you also barely learn anything

sleek gazelle
#

If I comment out the 2 conditions, it's not fixed

grand badger
sleek gazelle
#
var pixels = originalTexture.GetPixels();
originalTexture.SetPixels(pixels);

Why would this not work?
EDIT: texture format was wrong

grand badger
#

the texture needs to be marked as isReadWriteable from the import settings -- is it?

stark summit
grand badger
sleek gazelle
grand badger
#

@stark summit maybe I'm wrong though. But yeah give it a go with the standard way of google and stackoverflow imo

steep rose
summer stump
silent vessel
#

anyone know what this means

#

New compiled scripts dont work

summer stump
sleek gazelle
#

@grand badger just wanna say thank you! I fixed the last error and it looks super nice!

grand badger
#

woah that DOES look super nice 👍 yw

#

out of curiosity, what was the last error?

sleek gazelle
# grand badger out of curiosity, what was the last error?

Looks like the format of the texture was wrong, so I created another texture by script with the good format (chatGPT helped me a bit in finding why it wasn't working lol), here's the code now if you want:

        originalTexture = (renderer.material.mainTexture as Texture2D);
        Texture2D newTexture = new Texture2D(originalTexture.width, originalTexture.height, TextureFormat.RGBA32, false);
        int height = originalTexture.height;
        int width = originalTexture.width;
        float x = Random.Range(0,249092f);
        float y = Random.Range(0,249092f);

        Color[] pixels = originalTexture.GetPixels();
        for (int i = 0; i < width; i ++) {
            for (int j = 0; j < height; j ++) {
                var index = i + width * j;
                if (pixels[index].a == 0) pixels[index] = Color.clear; 
                else if (Mathf.PerlinNoise(x + (i * scale), y + (j * scale)) < Random.Range(0f,0.7f)) pixels[index] = Color.clear; 
            }
        }

        newTexture.SetPixels(pixels);
        newTexture.Apply();
        renderer.material.mainTexture = newTexture;
cosmic dagger
eternal falconBOT
silent vessel
#

yes

#

everything was fine

#

up till this happen

cosmic dagger
#

I don't use Visual Studio, but isn't MonoBehaviour supposed to be colored?

silent vessel
#

yea thats why

#

I can only sue plain c#

steep rose
silent vessel
#

not that im aware of my commits looks clean

rich adder
orchid kite
#

guys i need help

NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)

this is my error and here is the code


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

public class MonkeyAttack : MonoBehaviour
{
    [SerializeField] private float cooldown;
    [SerializeField] private Transform firePoint;
    [SerializeField] private GameObject[] bananas;
    private MonkeyScript playerMovement;
    private float cooldownTime = Mathf.Infinity;

    private void Update()
    {
        if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())

            Attack();

        cooldownTime += Time.deltaTime;
    }

    private void Attack()
    {
        cooldownTime = 0;

        bananas[FindBanana()].transform.position = firePoint.position;
        bananas[FindBanana()].GetComponent<BananaThrow>().SetDirection(Mathf.Sign(transform.localScale.x));
    }

    private int FindBanana()
    {
        for (int i = 0; i < bananas.Length; i++)
        {
            if (!bananas[i].activeInHierarchy)
                return i;
        }

        return 0;
    }
}
eternal falconBOT
steep rose
cosmic dagger
steep rose
orchid kite
#

with the backquotes

#

any help would be appreciated thanks

steep rose
#

read the bot

cosmic dagger
silent vessel
#

new projects dont work either

#

sometimes the scripts I create work fine sometimes they dont

cosmic dagger
#

Plus, we cannot accurately access which line the error is on as the code wraps around. Very hard to read on mobile . . .

steep rose
#

it may be a bug, if it is, please follow this !bug

eternal falconBOT
#

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

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

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

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

steep rose
#

then press the save in the site

#

simple

rocky canyon
#

paste -> click the 💾 save icon.. give us the new url thats generated

orchid kite
#

Ok

#

I’ll do it later cuz I just went off my pc

#

Sry guys mb

steep rose
#

or visual studio

wooden minnow
#

How would I make an object feel like it was thrown really hard?
I'm raycasting and then teleporting it to where it hits but idk how to make it feel like it was thrown there instead of teleported

(I'm trying to replicate the effect of Uzi throwing a [NULL] from murder drones)

summer stump
# silent vessel

Your ide is not configured and the issue is with the csproj file. Try clicking regenerate project files in the external tools window of unity

silent vessel
silent vessel
summer stump
silent vessel
#

yep

rocky canyon
#

delete the .csproj files manually if u have to..

summer stump
#

Try deleting all the .csproj files then do it again

rocky canyon
#

the button should work tho

silent vessel
#

just to not mess up how do u do that

faint agate
#

I’m trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse cursor was top left of screen on start, the first player will be looking top left when game starts).
https://gdl.space/ecusebusop.cs
https://gdl.space/osezedamig.cs
This script is attached to the camholder and Transform cameraPosition is on the player

I tried changing the player and cameras rotation from edit mode and in script, but I’m doing something wrong and need help.

#

any help would be appreciated

summer stump
rocky canyon
silent vessel
steep rose
#

reinstall visual studio ig (if nothing works), this problem has been going on for a while with visual studio but pretty rare

languid spire
#

You could try a Repair via the Visual Studio Installer

silent vessel
#

Ok thanks alot. I take it as not a unity problem

lethal meadow
#

is there a better way of doing an enemy that shoots back

#
    void Update()
    {
        if (player != null)
        {
            scanner.rotation = Quaternion.LookRotation(player.transform.position - scanner.position);
            if (Physics.Raycast(scanner.position, scanner.forward, out hit, 15f))
            {
                transform.LookAt(player.transform);
                if (!shooting)
                {
                    shooting = true;
                    Invoke("ShootPlayer", 1);
                }
            }
            else
            {
                transform.rotation = Quaternion.Euler(0, 180, 0);
            }
        }
    }

    void ShootPlayer()
    {
        if (player != null)
        {
            if (Physics.Raycast(scanner.position, scanner.forward, out hit, 15f))
            {
                player.GetComponent<PlayerHealth>().takeDamage(enemyDamage);

                GameObject MuzzleFlashInstance = Instantiate(muzzleFlash, endOfBarrel.transform.position, endOfBarrel.transform.rotation, transform);
                MuzzleFlashInstance.transform.rotation = Quaternion.Euler(0, 0, 0);
                Destroy(MuzzleFlashInstance, .3f);

                transform.GetComponent<ScreenShake>().TriggerShake();
                redTint.SetActive(true);
                Invoke("DisableTint", 1f);
            }

            shooting = false;
        }

    }

    void DisableTint()
    {
        redTint.SetActive(false);
    }
}
steep rose
#

i would make it lag behind a bit so its not aimbot

lethal meadow
#

how

#

i was thinking of adding spread

#

but its still instant

#

i dont know how to make actual bullets that travel

#

this is my 6th day of unity

steep rose
#

i would !learn the basics of unity

eternal falconBOT
#

:teacher: Unity Learn ↗

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

lethal meadow
#

if you know what i'd need to learn

#

i dont like just going through everything one after another

#

i prefer finding what i need then learning it and using etc

steep rose
#

if you dont know the absolute basics of unity you should not be making a project like this

lethal meadow
#

what basics

steep rose
#

i would 110% learn how to use unity

#

you can learn by clicking the link i provided

summer stump
lethal meadow
#

oh really

#

i didnt see it the first time

faint agate
#

I’m trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse cursor was top left of screen on start, the first player will be looking top left when game starts).
https://gdl.space/ecusebusop.cs
https://gdl.space/osezedamig.cs
This script is attached to the camholder and Transform cameraPosition is on the player

I tried changing the player and cameras rotation from edit mode and in script, but I’m doing something wrong and need help.
any help would be appreciated

young warren
#

you could try setting the camera's transform.forward to the direction you want

steep rose
#

why not set mouseX and mouseY on start

young warren
#

because mouseX and mouseY is a mouse input

steep rose
#

you set mouseX to 90deg and it will start there

#

its not a -1 or 1 input

#

it adds up over time

#

or decreases over time

faint agate
steep rose
faint agate
#

thank you for responding

#

i tried transform.rotation = Quaternion.Euler(0, 180, 0); on cam but that didnt work

steep rose
#

set Yrotation on start

faint agate
steep rose
#

Yrotation = //something in the start method

faint agate
#

thats what im stuck at lol

#

yRotation.rotation = Quaternion.Euler(0, 180, 0); and yRotation = Quaternion.Euler(0, 180, 0); wont work

steep rose
#

no literally just do Yrotation = //something

faint agate
#

yRotation = (0, 180, 0); this isnt working either

#

says error

steep rose
#

you dont add a vector

faint agate
#

ahhhhhh

steep rose
#

just a simple float

#

Yrotation = 90;

faint agate
#

it workeddddddddddddddd

#

thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuu

#

lol idk why I kept doin 3 instead of one

bitter monolith
eternal falconBOT
steep rose
#

you should use thier discord instead

lethal meadow
#

@upper geyser still want help?

languid spire
#

Did you read the message??

orchid kite
#

!code

eternal falconBOT
orchid kite
#

https://gdl.space/bupajokola.cs

can anyone help me this is the error i am reciving in unity this is my first time so i am not the greatest lol

NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)

thanks

languid spire
#

did you read line 15 of your code?

short hazel
#

Stacktrace guide:

at Assets/MonkeyAttack.cs:15
  |         PATH         | Line of code
wooden minnow
#

if i do

GameObject obj = new GameObject();
obj.AddComponent<myCustomComponent>();``` how can i change `obj` without deleting what it was before?
#

idrk how to explain it

polar acorn
#

That's really the most I can answer with the info given

wooden minnow
wooden minnow
#

but im not really sure how i would do that

polar acorn
#

The code you've done will do that

wooden minnow
polar acorn
wooden minnow
#

obj = new GameObject();

#

again

polar acorn
#

That changes which object obj holds

#

that doesn't delete anything

wooden minnow
#

alright ty

rocky canyon
#
    {
        Program program = new Program(0, "Test Message");
        program.GetMethod(program.dotCount).Invoke(program.message); // just recently learned I could do things like Grabbing a Method via a string
        program.CallMethod(program.dotCount, program.message); // this is more of what i'm used to
    }

    Action<string> GetMethod(int index)
    {
        switch (index % 3)
        {
            case 0: return A;
            case 1: return B;
            case 2: return C;
            default: return DefaultError;
        }
    }

    void CallMethod(int index, string message)
    {
        switch (index % 3)
        {
            case 0: A(message); break;
            case 1: B(message); break;
            case 2: C(message); break;
            default: DefaultError(message); break;
        }
    }``` decisions, decisions..
short hazel
rocky canyon
#

everytime i realize something cool, its always just the tip of the iceberg 😄

languid spire
#

And did you check the 2 things it told you to check?

#

ok, so screenshot your console

carmine narwhal
#
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class BallMoveMent : MonoBehaviour
{
    private Rigidbody2D rb;
    public float startSpeed = 100f;
    public float speedIncrease = 1f;
    private Vector2 currentSpeed;
    private int collisionCount;

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

    private void StartMoveMent() 
    {
       
        float x = Random.Range(-0.5f, 1f);
        float y = Random.Range(-0.5f, 1f);
       
        Vector2 direction = new Vector2(x,y).normalized;
        rb.velocity = direction * startSpeed * Time.deltaTime;
        Debug.Log(direction);
        currentSpeed = direction * startSpeed;

    }
    public void OnCollisionEnter2D(Collision2D collision)
    {
        collisionCount++;
        if(collisionCount % 5 == 0) 
        {
            rb.velocity *= speedIncrease;
        }
       
      

    }
}
``` This script was supose to give the ball a random directions on every directinos exept for straight right or straight left. but it just gives a random direction.  What to google to get some type of answer? apperntly i dont know how to google
white forge
#

you are giving it a random range

#

that is how it should work?

white forge
carmine narwhal
# white forge

yes but the inputs make it so the ball goes straight sometimes. i dont want that

white forge
#

thats how random works?

carmine narwhal
#

no

white forge
#

there will always be a chance of it going forwards no?

carmine narwhal
#

i want to restrict it

white forge
#

then you need to clamp it

steep rose
#

you would use Input.GetAxisRaw("Horizontal") or Input.GetAxis("Horizontal") for inputs

carmine narwhal
steep rose
#

not random.range

white forge
#

he isnt asking about it being controlled with a keyboard

#

i dont think?

carmine narwhal
steep rose
#

Horizontal does not need to be controlled via keyboard

#

with the new input system

summer stump
carmine narwhal
#

its a god damn pingpong game. the ball should just start moving but it needs some restrictions. but now i want to know how i should know how to google clamp?

white forge
#

he isnt asking for something controlled with input

#

read his original question

steep rose
white forge
#

ive never had this exact problem

#

can you try and explain what you want to happen, and what is happening

carmine narwhal
#

im gonna try to paint it 😛 but i paint liek a 2yr old give me a min 😄

white forge
#

ok

summer stump
carmine narwhal
#

green direction correct red not

white forge
#

they are actually trying to get help now

#

so you are getting the red

carmine narwhal
#

im getting all of them 😄

summer stump
# white forge why are you so agressive

I have seen you attack like six people today. I was trying to help them know how to google things and hopefully give them some confidence with that.
Stop attacking people

I am blocking you. I don't get why you are so hostile and angry to everyone. No one was ever hostile to you as far as I saw

carmine narwhal
steep rose
#

just get a random range between X

summer stump
steep rose
#

or Y depending on how it is orientated

carmine narwhal
short hazel
#

For Y choose between -1 and 1 (0 excluded) and build the direction vector from that

#

Make sure to normalize the vector though, that should give it a "random" Y velocity since normalizing affects both X and Y

carmine narwhal
# short hazel For Y choose between -1 and 1 (0 excluded) and build the direction vector from t...
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class BallMoveMent : MonoBehaviour
{
    private Rigidbody2D rb;
    public float startSpeed = 100f;
    public float speedIncrease = 1f;
    private Vector2 currentSpeed;
    private int collisionCount;

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

    private void StartMoveMent() 
    {
       
        float x = Random.Range(-0.5f, 1f);
        float y = Random.Range(-1f, 1f);
       
        Vector2 direction = new Vector2(x,y).normalized;
        rb.velocity = direction * startSpeed * Time.deltaTime;
        Debug.Log(direction);
        currentSpeed = direction * startSpeed;

    }
    public void OnCollisionEnter2D(Collision2D collision)
    {
        collisionCount++;
        if(collisionCount % 5 == 0) 
        {
            rb.velocity *= speedIncrease;
        }
       
      

    }
}
``` like this?  seems to be working, but i do not understand why 😛 Thanks though
steep rose
#

you changed values in the range

summer stump
#

Might wanna make those values variables, but that is not super important now
Like xMin, xMax, yMin, yMax

short hazel
#

For Y it will still have a chance to return 0, although with a low probability

summer stump
carmine narwhal
summer stump
carmine narwhal
#

or my next problem..... now the stupid ball stops bouncing and goes in a single direction after the bounce 😦

steep rose
#

you need to flip the velocity when you hit a wall

summer stump
polar marsh
#

Can someone help me with this, I've got a sorting algorithm where if the player is at a higher checkpoint than the other, their position moves up the list

#

But it's being sorted the other way, the ones with a lower position are coming first

carmine narwhal
polar marsh
steep rose
#

thats a hint

willow scroll
polar marsh
carmine narwhal
# steep rose thats a hint

thanks for the hint. i will check that. not totaly sure what you mean by that but but 😄 need to sleep soon

polar marsh
willow scroll
magic panther
#

This is a global class that I use for collectible storage, changing scenes and all that (at least that's my intent), and found something weird. LoadScene works fine, but RestartScene says that Instance is not defined. I don't know how to approach this. Any ideas?

Script -> https://gdl.space/hiburisosi.cs

polar marsh
willow scroll
magic panther
#

oh, I didn't think of that xd

willow scroll
#

Are there also supposed to be other players? Since I don't see why you need a List for 2 items

polar marsh
#

Yeah, it's a network game i'm just testing with 2 clients right now

#

Difficult to test with more

willow scroll
#

I would use OrderBy

polar marsh
#

Okay I'll have a look ty

willow scroll
carmine narwhal
polar marsh
#

Calls the sort function each frame

#

Really inefficient but i'm just trying to get something working right now

#

Does orderby still support selection like i've done above? I'd rather not call the distance function unless two are the same

willow scroll
#

You haven't answered my previous question

polar marsh
#

Sorry i'm not really sure what you mean

willow scroll
polar marsh
#

It's a bubble sort algorithm,

#

First it checks if the otherplayers lap is lower, then it swaps if it is

#

If theyre the same, it does the same for the checkpoint number

#

If the checkpoint numbers are the same, then it checks the distance of the two players from the next checkpoint

#

Then if the other player is further it swaps them

carmine narwhal
#

after a few bounces this happends ``` using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class BallMoveMent : MonoBehaviour
{
private Rigidbody2D rb;
public float startSpeed = 100f;
public float speedIncrease = 1f;
private Vector2 currentSpeed;
private int collisionCount;
private float bouncOffset = 0.1f;
private float minX = -0.5f;
private float minY = -1f;
private int maxX = 1;
private int maxY = -1;

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

private void StartMoveMent() 
{
   
    float x = Random.Range(minX, maxX);
    float y = Random.Range(minY, maxY);
   
    Vector2 direction = new Vector2(x,y).normalized;
    rb.velocity = direction * startSpeed * Time.deltaTime;
    Debug.Log(direction);
    currentSpeed = direction * startSpeed;

}
public void OnCollisionEnter2D(Collision2D collision)
{
    
    collisionCount++;
    if(collisionCount % 5 == 0) 
    {
        rb.velocity *= speedIncrease * bouncOffset;
    }
   
  

}

}

summer stump
grand laurel
#

I dont know how advanced this is but I feel like its relativity beginner so im going to ask help in here

Im currently working on my FPS game with a lock on system similar to Metroid Prime/Dark Souls. I have made it so a raycast is shot out from the player camera and returns a vector 3 of a targetable object. After that, the player can push a button to make the camera LookAt the the targetable objects postion. However after the player is no longer holds the input required for the camera to target the object the camera goes flying off into a different direction.

    {
        CheckTarget();
        if(inputHandler.TargetTriggered) 
        {
            Debug.Log("Is Targeting");
            transform.LookAt(TargetsPostion);
            orientation.transform.LookAt(TargetsPostion);
        }
        
    }

    private void CheckTarget() 
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, targetLayer))
        {
            Debug.Log("Object Hit");
            TargetsPostion = hit.point;
        }
    }```
Below I also provided a video of my issue
carmine narwhal
willow scroll
#

Since I've only heard about 2 now

polar marsh
#

And they're all separate objects

willow scroll
polar marsh
#

Perfect ty

#

Then i just do a check for ones that are the same? and then do the distance check from before

polar marsh
#

If two players both have the same next checkpoint

willow scroll
#

You have to check till the point you are sure the player's ranks are not the same

willow scroll
polar marsh
willow scroll
#

OrderByDescending and ThenByDescending exist

polar marsh
#

No but i havent calculated the distance already

#

I only want to do it if more than one player has the same checkpoint number

#

Because its an expensive algorithm to call each frame

#

And once you get 16 players running it for each of them will wreck performance

magic panther
rocky canyon
#

use cs float sqrDistance = (pointA.position - pointB.position).sqrMagnitude; float sqrThreshold = distanceThreshold * distanceThreshold;

polar marsh
#

Ignore that haha

#

Ty ill try that

willow scroll
polar marsh
#

Oh i see

#

I thought it ran it on all the players

rocky canyon
willow scroll
#

If OrderBy has left an Enumeable with the same values, ThenBy orders the same values once more

polar marsh
#

Ahh that makes sense

#

Sorry i thought it was just like running orderby again

orchid kite
#

https://gdl.space/bupajokola.cs

can anyone help me this is the error i am reciving in unity this is my first time so i am not the greatest lol

NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)

thanks

willow scroll
polar marsh
#

Okay ty thats a lot easier

steel mauve
orchid kite
#

But I thought that I initialized playerMovment as monkey script which is my movement code and ground check

steel mauve
#

Sorry, I'm super new to Unity (just got here), but lots of experience in C#. Maybe the answer is obvious to someone else, but I don't see anywhere in your script where you set playerMovement = anything

verbal dome
orchid kite
#

Oh I didn’t know that lol

verbal dome
#

You only told what type it is and its name, but didnt assign a value

orchid kite
#

So I just gotta write

playerMovement = some value

verbal dome
#

You can serialize that field and drag it in

#

Or use getcomponent if necessary

queen adder
#

i want that lizardman kills pigman but pigman dont want to die can someone help me

verbal dome
orchid kite
#

Ok well I will just assign it to 0 cuz I don’t want it to be moving while attacking thanks and also thanks @steel mauve

queen adder
queen adder
#

wich

summer stump
summer stump
queen adder
#

ofcourse not

verbal dome
#

Troll detected

queen adder
#

im not

summer stump
#

If you cannot show what you need help with, we cannot help you of course

queen adder
#

this is my player

#

he is okay

#

but i dont know how to kill pigman

rich adder
#

you still havent explained the problem

queen adder
#

like sometimes he flys away

#

sometimes i fly away

rich adder
summer stump
#

Nothing here even has anything to do with attacking

queen adder
#

sometimes we both fly away

summer stump
#

It just animates and scales

queen adder
rich adder
# queen adder

that doesnt explain what this represents in your game?

queen adder
#

VS

#

yes

#

it is pigman vs lizardman

willow scroll
#

Wow, that's epic

rich adder
#

yes you said that

queen adder
#

but the pig wont die

rich adder
#

bu you havent explained the mechanics of the game..

queen adder
#

its a 2d game

#

u can walk left and right

#

and jump and hit someone

rich adder
#

ok slowly getting somewhere useful..

#

maybe create a complete paragraph and explain the problem further..

queen adder
#

i have a weapon in my hand called

#

Hitbox33

#

pigs animations are ready

rich adder
#

did you put a script on it ?

queen adder
#

how do i manage to kill pigman now with my weapon

#

no ?

#

why

rich adder
#

put the collider , set it to Trigger. Use OnTriggerEnter to inflict damage on the Pigs health script

queen adder
#

health script?

rich adder
#

yea do you know what a script is?

queen adder
#

yes

#

its the logic

rich adder
#

so whats the confusion, create a health script

queen adder
#

how does the pc now that my weapon is my weapon

#

(Hitbox33)

rich adder
#

You create yet another script

queen adder
rich adder
#

yes if you want to make anything useful , you will need scripts..lots of them..

queen adder
#

true

#

ill tell u when i made the health script

rich adder
#

its fairly simple setup, use a Trigger on one script and health on the other. They both interact

#

you just cant put the script on a disabled object or it wont work

willow scroll
rich adder
#

manbearpig

queen adder
#

HAHAHAH

willow scroll
#

Yeah, that's some epic shit

queen adder
#

right

rich adder
#

needs some screenshake goodness

queen adder
#

oh hell yeaaa

steep rose
#

im getting mixed signals

queen adder
#

iTS FUCKIN AWESOME DUDE

#

you dont even know where ill go with this shit

#

it will not be a fighting game

#

it will be a whole show

willow scroll
#

The only thing left is to improve pigman's fighting spirit

queen adder
#

yap

#

stands there like a pig

#

i need blood splattering across the black wall

#

aswell

safe spear
#

Hi this is the first time ive used a switch inside a for loop, im trying to get the amount of items inside a list and put those values into specific array indexes; i always remains a 0, the console says IndexOutOfRangeException: Index was outside the bounds of the array. test.Update () (at Assets/test.cs:20)and the Debug.Log in the switch statements never gets called.

waxen adder
#

List.Count is one more than the maximum index of a list/array, which is why you're probably getting that exception

safe spear
#

oh my gosh i just rezlied the ammoun of coppy paste errors

rocky canyon
#
 public int[] AmmountsInTheLists = {0,0,0,};```
```cs
 public int[] AmmountsInTheLists = new int[3]```
short hazel
short hazel
#

The rest of the code looks fine regarding the loop and the array accesses with i

#

To avoid the issue in the future always set the upper bound of the loop to the array's length, so it adapts when you resize it. for (int i = 0; i < AmmountsInTheLists.Length; i++)

rocky canyon
#

i always like to debug my results before everytime i access them for things like this..
.Count atleast

safe spear
rocky canyon
#

Utils.cs

        public static float OptimizedDistance(Vector3 a, Vector3 b)
        {
            return (a - b).sqrMagnitude;
        }

        public static bool InRange(Vector3 a, Vector3 b, float range)
        {
            float squaredRange = range * range;
            return OptimizedDistance(a, b) < squaredRange;
        }
```useless or nifty?
queen adder
#

i dont know

rocky canyon
#

Dbug and find out why

queen adder
rocky canyon
#
  • Health Exists and has Value
  • Weapon Exists and has Value
  • Weapon/Holder interacts w/ pigman
  • Value calculates w/ Value
  • End Value is Presented
rich adder
#

screenshot is is ok for inspector. Send code via links

queen adder
#

what did u just say to me

rich adder
queen adder
#

AHAHAHA

rich adder
#

i get it

rocky canyon
#

his attempt at meme'ing

queen adder
#

frustrated bro

rich adder
#

<<too old to understand Z yuth memes :\

queen adder
#

im 25

rocky canyon
short hazel
# rocky canyon `Utils.cs` ```cs public static float OptimizedDistance(Vector3 a, Vector...

With the processing power we have nowadays, I'd say not doing a square root will have a very negligible impact on performance. If you're calling this method 10k times a second sure you might see a difference! And you'd also have added the aggressive-inlining attribute on top of those methods to tell the compiler to pull the code up directly to the calling method (to avoid an expensive (?) virtual call)! Or used Burst or Jobs already, idk

rocky canyon
#

anyway.. its easy.. like i said Debug the values.. every step of the way

#

once ur debug returns something u dont expect.. u found the issue

rocky canyon
summer stump
rocky canyon
#

todays my Discovery day.. I like to start with a few stretches... and then work my way up to using System.Reflection;

rocky canyon
#

i dont need to know if its squared or not. but only if its within my range variable

#

i might keep it just for hoots

eternal needle
zenith cypress
rocky canyon
#
            float squaredRange = range * range;
            return DistanceSqrd(a, b) < squaredRange;```
short hazel
#

You technically could use extension methods to do stuff like this?

bool inRange = (vec1, vec2).DistanceLessThan(5);

I hate it, what is going on with my brain right now

rocky canyon
rocky canyon
#

i try to think like cs bool inRange = (vec1, vec2).DistanceLessThan(5); this while im writing.. so I know the final use-case will look good and be readible + simple alll of that jazz

#

but its harder to do in practice (for me atleast)

zenith cypress
#

Could do the Godot approach where they english most of their API

var inRange = vec1.DistanceTo(vec2) < 5;
rocky canyon
#

i think spr2's code is actually more friendly

short hazel
#

I like how Godot's read like plain English when you say the words out loud

rocky canyon
#

dont understand how u can just tack on a DistanceTo() function to a float

zenith cypress
#
public static float DistanceTo(this Vector3 from, Vector3 to) {
  return (to - from).magnitude;
}
rocky canyon
#

u make it look so simple

grand laurel
rocky canyon
zenith cypress
#

Has to be in a static class

rocky canyon
#

doesn't have to be in the float class or w/e or named Float

rocky canyon
short hazel
#

In a static class, and then it's accessible project-wide

rocky canyon
#

probably time to stop doing that

short hazel
#

For mine:

public static bool DistanceLessThan(this (Vector3 a, Vector3 b) pair, float distance)
{
    return (pair.b - pair.a).magnitude < distance;
}
zenith cypress
#

cursed tuple

short hazel
#

Yeah that's why I don't like it lol, it abuses tuples

rocky canyon
#
public static bool DistanceLessThan(this (Vector3 a, Vector3 b) pair, float distance) => (pair.b - pair.a).magnitude < distance;
``` dis possible?
short hazel
#

Sure!

rocky canyon
#

lol!

#

noice!

#

never looks at it again

rocky canyon
#

soo thanks for the context @zenith cypress @short hazel

cosmic dagger
rocky canyon
cosmic dagger
#

I started making ridiculous extensions just cuz. cs if (intVariable.IsLessThan(5)) { }

#
if (isReloading.IsFalse()) { }```
short hazel
#

The C# dev team actually works on better extensions right now, it won't be in the next .NET release but they did a few demos, where you can add new members (including properties!) to existing types, looks like this:

public extension SampleEx for string
{
    // length of the string, squared, because why not?
    public int LengthSquared => Length * Length;
}

// Usage
string s = "ab";
int ls = s.LengthSquared; // -> 4 | Seamless integration
#

I guess one that would be useful-ish for Unity is something like this:

transform.position.Log("label")
"debug, execution is here".Log();

Implementation exercise left to the reader...

zenith cypress
#

I'm still super uneasy about them, might be good, but also might be more confusing for onboarding when they see new properties mixed with existing one where they can be on instances and/or static. Guess we will see what it ends up doing to codebases in general when it comes out lol. Wonder if unity will be using modern net by then skull_c

rocky canyon
#

AYE! 🥳

#

figured it out lol

short hazel
#

gg

#

MORE! if ("FFFFFF".ToColor().IsWhite())

rocky canyon
#

holy crap, it took me this long to realize how extension methods really work.. and the whole this implication 🫣

rocky canyon
#

bruh.. i feel like not know that stuff has been a reeal hinderance on my learning/progressing lmao

short hazel
rocky canyon
#

i feel like i just took a big step backwards

#

(but got gifted a brand new pair of boots i guess)

zenith cypress
#

Just don't overuse it Kappa

rocky canyon
#

i wont..

#

lol

#

i used chatgpt to explain the this keyword a little more thoroughly and it was just complaining about tuples and how that original method wouldnt work

short hazel
#

Once extensions go live on Unity I will finally be able to implement transform.back, .down, and .left muahahaha

rocky canyon
#

(v, v2).DistanceLessThan(5);

#

heh, i have a .North and all the Cardinal Directions lol

#

well, an enum and switch statement actually

#

it stays zipped up in the regions

#

b/c its hideous and i feel bad

zenith cypress
rocky canyon
#

and.. im lost again

short hazel
#

We go wild when there's no activity
Maybe there are 50 people reading and asking themselves "if this is beginner code i am not ready to participate here"

rocky canyon
#
  1. extension methods not cause any extra taxing on the ide/compiler? (b/c of hte multiple ways they can be written) nvm.. i dont think so nvm
  2. are Tuples okay to use like that on extension methods? (v, v2).DistanceTo(10);
indigo hull
#

I wouldn't worry about performance on extension methods.

rocky canyon
#

im not in general.. just curious more

short hazel
#
  1. Nope, it's compiler tomfoolery like most "modern" things. Compiler just replaces your code with a standard call to the static method (hence why both the class and method must be static)
  2. Tuples are types like any other
rocky canyon
#

roger that 🫡

indigo hull
#

SPR2 gots it.

short hazel
#

Basically:```cs
"something".Extension();
// ->
MyExtensions.Extension("something");

rocky canyon
#

ahh, yea i get u now..

#

in the end its all gonna be what is gonna be

#

well mark down another strike against chatgpt.. (quite a few now)
tellin me i cant use tuples like that.

marble hemlock
#

right

#

prob better to start this with the script

indigo hull
#

Learn from documentation and your own critical thinking. ChatGPT is worse than a crutch for programmers.

zenith cypress
#

I've only found gpt good for two things, vim commands, and converting rust structs to JS versions for Tauri Kappa

cosmic dagger
scenic saffron
#

why is my animation not restarting?

#

nvm im dumb

cosmic dagger
#

I love ChatGPT for documentation. It writes all my extension method summaries . . .

rocky canyon
# indigo hull Learn from documentation and your own critical thinking. ChatGPT is worse than a...

ya, im past the beginner stage for quite a bit now.. i use chatgpt for grunt work.. documentation writing and stuff..
but i can say its useful just as u said earlier.. combine it w/ critical thinking and it can still expose u to concepts, ideas, and whatnot pretty efficiently..
like the tuple thing seemd off, asked here to clarify, got expected answer.. sent a few pointless insult its way and now im off to the next todo bullet lol

marble hemlock
#

so i was learning raycast

marble hemlock
#

rough stuff, but i think ive gotten it down
i was wondering "how do i cause a change to whatever its interacting with, and not everything with the layer the raycast is looking for?"

rocky canyon
#

but i've notice my codeium plug-in is pretty good on its own.. filling them in after i write the method signature

marble hemlock
#

like if i had a bunch of stuff on the "rock" layer or something but i had a really specific rock i wanted the player to fuck with, how would i do that?

as an example, lets say i want it to make the specific object its interacting with a child of... some other object?

#

actually thats perfect

rocky canyon
#

the layer would just be a conditional before hand to narrow down the raycast results

marble hemlock
#

im not entirely sure how id do that
so the layer wont be a problem, right?

rocky canyon
#
  void Update()
    {
        ray = new Ray(cam.transform.position,cam.transform.forward);
        if(Physics.Raycast(ray, out RaycastHit hit,distance, mask))
        {
            if(hit.collider.transform.TryGetComponent(out IInteractable interactable))
            {
                cachedInteractable = hit.collider.gameObject;
                if(Input.GetKeyDown(interactKey))
                {
                    interactable.Interact();
                    Dbug.Italic($"Interacted with {cachedInteractable.name}");
                }
            }```
marble hemlock
#

do i just go "gameobject", and then shove whatever game object fits that role in there

rocky canyon
#

soo. here its not the exact same.. but u can see where i got the hit.collider.transform

#

out RaycastHit hit this part here stores it for me when the raycast has a true-hit

marble hemlock
#

okay so id be looking for it hitting the mask, and then hitting object collider, and then trying for it to get whatever applicable script for "Interactable?"

rocky canyon
marble hemlock
#

it seems more study of raycasts is needed

rocky canyon
marble hemlock
#

see store is where you're getting me

rocky canyon
#
 ray = new Ray(cam.transform.position,cam.transform.forward);
        if(Physics.Raycast(ray, out RaycastHit hit,distance, mask))
        {
          //this will only be objects w/ layers that are in the mask
        }
marble hemlock
#

im going to try, thank you

#

i think im getting a grasp on this

marble hemlock
#

going through the docs can be rough at times

#

helpful yes, but sometimes a bit

rocky canyon
#

thats why i also linked an article

marble hemlock
#

thank you

waxen adder
#

White cubes are original navmesh path corners. Black cubes are the path corners translated to the grid. Green line is for visualizing a straight path or not. Why is it that the navmesh insists on creating two intermediary corners when there is a perfrectly straight line from start to end?

Edit: hmmm. It's tempting to just give it a metric ton of information and just, remove any redundant nodes

prime cobalt
#

If I change the string variable in InvokeRepeating to the name of another function while its running does it change which function it calls?

rocky canyon
#

nah, invoke repeating starts and then continues to call the same method until its canceled

summer stump
prime cobalt
#

What about a normal invoke? If that invoke repeats in updates for example and its value is changed will that work?

summer stump
#

no
Sorry. I see what you mean. The NEXT time it is called, yes
Generally just don't want to use invoke or invoke repeating. A delegate may be better (without knowing the use case)

prime cobalt
#

Oh ok good. I just need a way to call functions from a string with their name.

prime cobalt
#

Enemy ai brain. When the ai is doing a certain action then it sets the string to the function that corresponds with that action.

slender nymph
#

why are you using strings at all for that

static wasp
#

this line of code stopped working for no reason, even though I didn't do anything in this script

if(Input.GetKeyDown(KeyCode.Alpha1))
slender nymph
#

is that line perhaps inside of FixedUpdate?

static wasp
slender nymph
#

are you certain the code is actually running?

static wasp
#

it used to work fine, but when i added something in unity, it stopped working

zenith cypress
#

Well what did you add

slender nymph
zenith cypress
#

Did you enable the new input system?

prime cobalt
# slender nymph why are you using strings at all for that

quick way to set which function needs to be called. Like when it stands for a certain time so the standing function decides to walk and so it sets the function that is called each 0.1f seconds to the one that corresponds to walking. Having it be strings means I can call it by name and not need a big switch statement.

static wasp
polar acorn
slender nymph
static wasp
zenith cypress
#

Send over the script to see if it is a logic error. Also put a debug log before the if statement to see if the script is even running properly.

eternal needle
polar acorn
#

what have you done in order to demonstrate that

static wasp
zenith cypress
#

Also, you are pressing Alpha1 right? 1 on your top row of the keyboard (not numpad 1).

static wasp
zenith cypress
#

Just making sure 👍

polar acorn
static wasp
polar acorn
#

Ah wait, alpha1, that's the normal number, nevermind

#

Continue with posting the !code then

eternal falconBOT
static wasp
static wasp
# polar acorn Continue with posting the !code then
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour
{   
    public GameObject bulletPrefab;
    public GameObject gun;
    public GameObject player;
    private string weapon_active = "None";
    private Renderer rend;
    private GameObject bullet;
    public GameObject camera;
    public Vector3 mouse_pos;
    public bool bullet_move = false;
    void Start()
    {
        rend = GetComponent<Renderer>();
        rend.enabled = false;
    }

    void Update()
    {
        if(Camera.cursor_locked)
        {
            if(Input.GetKeyDown(KeyCode.Alpha1))
            {
                Debug.Log("works");
                if (weapon_active == "Gun")
                {
                    rend.enabled = false;
                    weapon_active = "None";
                }
                else
                {
                    rend.enabled = true;
                    weapon_active = "Gun";
                }
            }

            if (weapon_active == "Gun" && Input.GetMouseButtonDown(0) == true)
            {
                GameObject bullet = Instantiate(bulletPrefab, player.transform.position, camera.transform.rotation);
                Bullet bulletScript = bullet.GetComponent(typeof(Bullet)) as Bullet;
                bulletScript.direction = player.transform.forward;
                bullet_move = true;
            }
        }
    }
}
polar acorn
polar acorn
#

Put a log there, then show a screenshot of your console after you tried to hit the button

static wasp
#

put a log before the if statement?

zenith cypress
#

Before the alpha1 if statement, yes

static wasp
#

ok one sec

polar acorn
#

Yes, before the input statement, after the cursor statement

prime cobalt
static wasp
#

it never said that alpha1 works

#

i checked all of the messages

polar acorn
polar acorn
#

Okay, so, it would seem that Alpha1 is never pressed on a frame this object is active for. Try changing it to a different key for testing

zenith cypress
#

Also make a new Mono script and see if it works there. Just put the script on some random object in the scene

polar acorn
#

Any key. Let's say Spacebar

static wasp
#

i pressed space like 30 times

#

it doesn't say works

polar acorn
#

Okay, show a screenshot of the inspector of this object while your game is running

static wasp
#

wdym

zenith cypress
#

play game, pick up weapon, show weapon in inspector

polar acorn
#

Take a screenshot of the inspector of this object while your game is running

#

At a time you'd be expecting the button to work

static wasp
#

wait

#

i remembered that my jump button is space

#

lemme try a different button rq

#

no buttons work

#

i can't move or jump, i can only look around

#

hello?

steep rose
#

Camera.cursor_locked is probably the issue

static wasp
steep rose
#

is anything being called underneath it?

rich adder
#

also should avoid using a class named Camera

static wasp
#

yes, the if statement

steep rose
#

no i mean did you test it

polar acorn
static wasp
polar acorn
#

Save and restart

steep rose
#

did you test any code functions underneath the Camera.cursor_locked

#

using debugs?

static wasp
static wasp
rocky canyon
#

allz i saw was every frame

steep rose
# static wasp yes

did you place a debug right underneath the Camera.cursor_locked and not in any if statements?

static wasp
#

my 16 gigs of ram are suffering while re-opening unity xd

#

i re-opened unity and it worked, thanks, but any idea why it stopped working?

steep rose
#

unity being unity

#

ig

languid snow
#

hello! (top down 2d, just vampire survivors lel) I have a gun that shoots. I want that, when shooting a box, this box shoots out another bullet (just a different game object) in the same direction that it got hit. I know how to do it so it instantiates the 2nd bullet, but i have no idea how to make the second bullet have the first bullets rotation

polar acorn
#

But if something is weird, a restart is always worth trying

summer stump
static wasp
#

and my code that i was implementing worked first try, i'm so happy rn

summer stump
#

Are you using OnTriggerEnter or OnCollisionEnter? Or something else

languid snow
undone harbor
#

Hello people, I have been trying to retrieve a curve attached to the current animation that is playing using this -

rotationCurve = AnimationUtility.GetEditorCurve(_psm.playerAnimationManager.animator.GetCurrentAnimatorClipInfo(0)[0].clip, EditorCurveBinding.FloatCurve(path, typeof(Transform), "Rotation Y"));

I have made sure that "Rotation Y" curve is present and also the name is returned properly. It still returns NULL, Could it be the binding?

summer stump
languid snow
#

OnTriggerEnter2d

summer stump
#

That will be the bullet if the script is on the cube

shrewd hill
#

why doesnt this work

steep rose
#

!code

eternal falconBOT
steep rose
#

please

shrewd hill
#

sorry

summer stump
#

Describe "doesn't work"
Because that is not actionable

steep rose
#

use a bin site

shrewd hill
languid snow
shrewd hill
#

whats a bin site

steep rose
#

read the bot

#

and look at the links

#

pick one

#

i bet you rn he is missing a ;

summer stump
# shrewd hill

Missing curly brace perhaps
Likely an unconfigured !ide

steep rose
#

watch

eternal falconBOT
static wasp
#

btw how do i make it so that it fullscreens when i playtest (i used to have it but i restarted and i forgot how to do it)

steep rose
#

right to the left of the play button

shrewd hill
steep rose
#

show the code

shrewd hill
#

didnt fix it

shrewd hill
steep rose
polar acorn
shrewd hill
#

idk what an ide is

#

this is like my first time ver doing this

steep rose
#

get visual studio

static wasp
#

it only says, play maximized, play focused, and play unfocused, and when i when i choose play maximized and playtest again, it doesn't save my choice

shrewd hill
steep rose
static wasp
#

nevermind it saved after like 13 tries

#

unity is weird

polar acorn
steep rose
summer stump
shrewd hill
#

im not missing a ; i dont think

summer stump
shrewd hill
#

ive been looking at this for a good 30 mins

static wasp
summer stump
polar acorn
steep rose
polar acorn
#

Don't use notepad

shrewd hill
#

fine

steep rose
shrewd hill
#

but i dont see whats wrong with note pad

steep rose
#

its just notepad

polar acorn
shrewd hill
#

it works

steep rose
#

you are on extreme difficulty

polar acorn
#

You might as well be writing your code on a piece of paper

steep rose
#

for programming

steep rose
shrewd hill
#

its working i got wasd to work and the cam

polar acorn
steep rose
shrewd hill
#

i am

steep rose
#

notepad is not one of them

shrewd hill
#

the purple one

steep rose
#

visual studio?

shrewd hill
#

yea

summer stump
shrewd hill
#

its installing rn

steep rose
#

okay

#

please never use notepad ever for an ide

#

like never

shrewd hill
#

whats all this

summer stump
#

The guide above tells you

#

!ide

eternal falconBOT
steep rose
#

you can python in VS?

#

ive been doing it wrong

shrewd hill
#

ill tell yall when this is done

#

its done now what

summer stump
polar acorn
#

Continue following the guid for configuring your IDE, then see where your error is

shrewd hill
#

im confused bruh

#

idk what am doing

steep rose
#

what are you confused about?

shrewd hill
steep rose
#

well you need to open a script

shrewd hill
#

how

steep rose
#

via unity or from Visual studio

shrewd hill
#

hold up

summer stump
#

Same way you opened it before
If you followed the guide, it will now open in vs

steep rose
#

well

#

not the notepad way

shrewd hill
#

like the one in notepad

steep rose
#

double click a script in unity

shrewd hill
#

becuase that ones open

#

it opens in notepad

summer stump
shrewd hill
#

got it

steep rose
#

good

#

now show us the error

shrewd hill
steep rose
#

in the script

#

not cropped out either

#

ive seen people do that before

shrewd hill
steep rose
#

add another }

#

at the end of your script

#

dang man i thought it would have been a ;

#

bummer

polar acorn
#

Do the whole guide

summer stump
#

You have a semicolon after an if statement on line 74. As we said, never do that

#

But yes, this is not configured. You still did not do the guide

shrewd hill
#

THOUGHT I GOT RID OF IT MB

#

caps mb

steep rose
#

he still needs a } to fix the error

#

but yes

#

configure that ide

summer stump
#

Are you sure? There is the if, method, and one extra which is likely the class semicolon there
If all of these are in a namespace, then yeah it needs another

steep rose
#

well other than the semicolon but the error said line 81 space 1

shrewd hill
#

wheres the }

#

going

steep rose
#

and you can see the dotted line that should be there

#

connecting the script

#

but it isnt there

summer stump
#

Ahhh, I see it. It is a missing PARENTHESIS on line 77

steep rose
#

muahaha

shrewd hill
#

its on line 71 noe

#

now

summer stump
#

That is line 77

#

As I said

#

It is COLUMN 71

shrewd hill
#

didnt fix it

summer stump
steep rose
#

put a } at the end of the script as well

summer stump
#

Put it before immediately before semicolon

steep rose
summer stump
#

There is definitely not a missing curly brace

rocky canyon
#

its the ; at the end of the if conditional ()

summer stump
#

There is a BACKWARDS curly brace though

summer stump
rocky canyon
#

ahh okie 👍

steep rose
#

i bet you rn its a curly brace

#

bet

shrewd hill
#

i added the } at the end already

summer stump
#

The two errors are backwards curly on line 70 and missing parenthesis on line 77

steep rose
#

dang

#

i unbet

summer stump
#

Remove the extra curly at the end that is not it, and that will cause an extra error

shrewd hill
#

ok

summer stump
#

All of this would be easy to see if you just finished configuring your ide

And honestly, we need to stop helping until you do so

steep rose
#

oh i see what you mean now aethenosity 😅

#

mb

#

i completely missed that parentheses

shrewd hill
#

id rather use notepad

steep rose
#

please dont

#

just

#

dont