#💻┃code-beginner

1 messages · Page 98 of 1

slender nymph
#

that's not what static is for

muted wadi
#

what is static for?

slender nymph
#

it needs to be public to be accessible by other objects. static makes it not tied to an instance and is owned by the class instead

muted wadi
#

from what I understand its for variables that are read only

slender nymph
#

that is also incorrect

muted wadi
slender nymph
#

which means you need it to be public

#

that's what public is for

muted wadi
#

i see

#

from what I've been told you're meant to make things private as often as you can

#

just for the sake of good security or something

wintry quarry
#

not security, encapsulation

cosmic dagger
#

If that's the case, then why are you accessing it from the instance instead of the class?

queen adder
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class FPSController : MonoBehaviour
{
    public float sensX;
    public float sensY;

    public Controls controls;
    private InputAction OnFoot;
    public Transform orientation;

    float xRotation;
    float yRotation;
    // Start is called before the first frame update
    void onEnable(){
        
        OnFoot.Enable();
    }
    void onDisable(){
        OnFoot.Disable();
    }
    void Start()
    {
        
        controls = new Controls();
        OnFoot = controls.ActionMap.Camera;
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(OnFoot.ReadValue<Vector2>());
        float mouseX = OnFoot.ReadValue<Vector2>().x * sensX;
        float mouseY = OnFoot.ReadValue<Vector2>().y * sensY;

        yRotation += mouseX;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.rotation = Quaternion.Euler(xRotation,yRotation,0);
        orientation.rotation = Quaternion.Euler(0,yRotation,0);
    }
}

when i move my mouse, the console reads the mouse's position and returns 0,0 all the time. Why?
a little background info:
I am working on a fps esque camera system and yes, ive tried turning off Cursor.lockState = CursorLockMode.Locked; and Cursor.visible = false;.

muted wadi
slender nymph
queen adder
#

oh this is easy

muted wadi
wintry quarry
queen adder
wintry quarry
#

It does for OnEnable

#

Not onEnable

queen adder
#

ahh

#

thank you all

wintry quarry
#

Also that runs BEFORE Start

#

hence switching to Awake

queen adder
#

honestly its like a curse

#

most of my problems come from the most miniscule and easy to fix bugs

#

but i can never find the problem

slender nymph
#

make sure that your !IDE is configured to help you prevent simple spelling mistakes

eternal falconBOT
tiny hawk
#

Should I use something other than PlasticSCM? I like PlasticSCM because it doesn't upload my assets downloaded from the Unity store.

queen adder
#

sadly ive tried that

#

and its still broken!!

#

hooray!!

slender nymph
#

then fix it. it is a requirement to receive help here because nobody wants to play septic's Personal Spell Checker

queen adder
#

ive looked through almost every page on stack overflow that i could and nothing works for my vscode

#

ah

#

ok that

#

makes sense

#

sorry

slender nymph
queen adder
#

will consider

muted wadi
queen adder
#

i honestly

#

in my opinion

#

prefer arch linux + visual studio code

#

its SOOO much easier to set up libraries

#

this way

slender nymph
#

if it's easier then why is your ide unconfigured 😉

queen adder
#

bahh im a messy and lazy person

queen adder
#

thank you all

#

and THANK GOD this FPS look around works now

#

i'd like to thank my manager

slender nymph
#

oh i'd also like to recommend using cinemachine instead of coding your camera controls manually. it's typically a lot better

cosmic dagger
queen adder
rich adder
#

unity

queen adder
#

ah

#

understood

#

it does seem like visual studio 2022 is my best bet for using unity

wintry quarry
#

Highly recommend Rider

queen adder
#

CONSIDERING that C# was made by microsoft

#

Damn you capitalism!!!

#

anywho, see you later

muted wadi
#

is there a way to find an object by name

rich adder
#

yes but don't

slender nymph
#

yes, you can use GameObject.Find, however there are better ways to reference other objects

muted wadi
#

why 😭

slender nymph
#

because it is slow

muted wadi
#

is it bad even if only one of the objects exists

wintry quarry
cosmic dagger
queen adder
#

👍

tender stag
#

how do i go about this, in this screen shot the enemy can see the player

#

but in this screenshot he should technically be able to see him

#

but he doesnt because the blue line goes to the belly of the player

#

and it isnt in the angles anymore

#

but the enemy can still clearly see the head

muted wadi
#

you basically just move around the child empty where you would want it to be on the player and that should fix it

tender stag
#

but the thing is that later on im gonna have a rig on my player

#

so each body part will have a collider

#

so i was thinking of using a raycast somehow

#

inside the vision area angles

muted wadi
#

use a spherecast

tender stag
#

because i need the enemy to even see a foot

muted wadi
#

or a boxcast

tender stag
#

also i wanna use && not ||

#

i know

wintry quarry
tender stag
#

i was thinking of that

muted wadi
#

that's what I did for enemies that would attack you within a certain melee range

boreal tangle
#

should I use rigidbody for collsion or am i supposed to code it myself from scratch?

summer stump
boreal tangle
#

I mean for player movement do I just rely on colliders or do I use raycast

#

to stop the player from going through walls

summer stump
#

Well it depends on how you're moving, which I see is why you brought up rigidbodies.
Using rigidbodies will handle collisions for you for the most part.
If you move with the transform, you're gonna have to query around yourself for collisions, grounding, and anything you want like that

boreal tangle
#

ok thank you

wintry quarry
bleak pasture
boreal tangle
#

Ok

summer stump
summer stump
bleak pasture
#

In unity5/2018 I used colliders as reference areas for trigger (like my cars had a collider around the door so the player could open ithe door when near the car) and for aggro ranges on mobs (mobs had a sphere collider preset to it's aggro ranges) and each mob/player carried several colliders as area reference

#

since I dont want to give the wrong advice I want to know since colliders were brought up if unity changed that since then

summer stump
#

Having sight/aggro ranges with colliders is very common still

#

You can also do spatial queries like OverlapSphere though

bleak pasture
#

I also used them for premade offsets like spells/particle graphics / gfx as well since an arrow would always be shot from a specific side (left/right/top/down) so I just preplaced the sprite and made it invisible. I prefered to do this rather than calculate an offset from the .transform every time

hasty spire
#

im not sure why i am not able to jump here

rich adder
hasty spire
bleak pasture
#

I saw a ping and it disappeared 😦

slender sinew
#

you only reset fJumpPressedRemember in this code

rich adder
hasty spire
hasty spire
bleak pasture
#

argh it's so difficult to go throught all the beginner training even though I havent done unity for a long time so I just relearn it since so much has probably changed 😦

#

"How did you feel when the Unity Editor first loaded? In this video, our established creators share how they felt when they opened the Editor for the first time. " - it's like my 100th time 😦 Do I listen to the video or mark as complete 😦

slender sinew
#

I just see what you are always decreasing it, so it just goes down far below 0 and never gets reset

hasty spire
slender sinew
#

where do you define how long that time should be ?

hasty spire
#

for some reason vs dosent want me to take scareenshots

summer stump
summer stump
eternal falconBOT
hasty spire
slender sinew
#

seems like that would be a value you want to keep constant

hasty spire
#

im not sure

#

im kind of lost

slender sinew
#

try thinking through what you are doing instead of just remaining confused, or if you have a specific thing you do not understand, ask a more specific question.. do you expect it to be working right now and you just don't know why?

hasty spire
queen adder
#

!ide

eternal falconBOT
queen adder
#

how can i check why my raycast is false?

#

like is there a debugger function that lets me see outside the camera

summer stump
queen adder
#

thanks :DD D DD

#

Ahhhhh

#

heres my problem

#

the layermask may or may not be broken

#

i'll fix this myself

ebon robin
#

if FixedUpdate is fixed at 50 frames, how could I make them smoother

polar acorn
#

They're designed to be smooth. 50 of them per second, no matter your framerate

ebon robin
#

what if i want 100

polar acorn
ebon robin
#

Hey I am using Unity new Input System, but if I name it public virtual void OnFire() to get different OnFire() in derived class, it wouldn't work

safe hull
#

Figured it out, the interacted object was the icosphere, which didn't have the ObjectData script on it. To fix I got the component from the parent of the icosphere

tired drift
#

hey guys i want to do something like this effect where the yellow blob will instantly snap to the player if its within certain areas but when its blocked by a collider the blob will just stay within the confines while the cursor moves out, any tips on how to start?

stark sonnet
#

This isnt in unity but im doing a course on responsive web design and its asking me to comment out the line containing the background-color property and value so i can see the effect of only styling the #menu element. What does that mean?

queen adder
fickle geyser
#

if i collaborate on github do we need to keep taking turns? can we not all develop at the same time?

tired drift
wintry quarry
fickle geyser
wintry quarry
fickle geyser
wintry quarry
#

If you both work on the same files at the same time you'll need to merge your work

fickle geyser
#

if somebody builds something

#

and the other guy like dosent build something

wintry quarry
#

"like objects" is very vague

#

Projects are made of files

#

Scene files, assets, script files etc

fickle geyser
#

so every push it will add on rather than "override" the repository??

wintry quarry
#

If you work on the same files you'll have to merge them, that's all

wintry quarry
#

All changes will be tracked and it will be up to you how to handle conflicts if any arise

fickle geyser
#

oh!!!!!

#

merging branches

#

duplicate files possible???!?!?!

worthy chasm
#

Get axis raw doesnt need to be multiplied by time.delta time correct?

ebon robin
vapid yew
#
public class WallTextureGenerator : MonoBehaviour
{
    [SerializeField] Transform walls, floor;

    [SerializeField] Material[] wWallMaterials, bWallMaterials, wFloorMaterials, bFloorMaterials;

    void Awake() {

        Renderer[] wallTiles = walls.GetComponentsInChildren<Renderer>().Where(c => c.tag == "white" || c.tag == "black").ToArray(),
                   floorTiles = floor.GetComponentsInChildren<Renderer>().Where(c => c.tag == "white" || c.tag == "black").ToArray();

        int wWallMatLength = wWallMaterials.Length,
            bWallMatLength = bWallMaterials.Length,
            wFloorMatLength = wFloorMaterials.Length,
            bFloorMatLength = bFloorMaterials.Length,
            
            wallTilesLength = wallTiles.Length - 1,
            floorTilesLength = floorTiles.Length - 1;

        for (int i = 0; i < wallTilesLength; i++) {
            wallTiles[i].material = wallTiles[i].tag == "white"
                ? wWallMaterials[Random.Range(0, wWallMatLength)]
                : bWallMaterials[Random.Range(0, bWallMatLength)];
        }

        foreach (Renderer r in floorTiles) {
            r.material = r.tag == "white"
                ? wFloorMaterials[Random.Range(0, wFloorMatLength)]
                : bFloorMaterials[Random.Range(0, bFloorMatLength)];
        }
    }
}

Can anyone tell me why I'm getting an index outside bounds of array error on line 25?

wintry quarry
#

Are you getting some kind of error? Something else? Explain.

ebon robin
# wintry quarry What do you mean by "wouldn't work" and "State"?

I am using a StateMachine that controls Player action, however, OnFire() and OnMove() are functions from Unity new Input System and they can only be executed when I put it in a script inside Player (GameObject). However, I want to, for example call OnFire() from a State of the StateMachine. How to do so?

wintry quarry
#

Those are your custom functions

ebon robin
#

yes

#

how do OnFire() exactly is called

#

I dont seem to understand this kind of new Input System

#

here is an example of the code

wintry quarry
ebon robin
#

how to call those functions from let's say another class inside the PlayerController that I have attached to the player

#

i don't understand anything about this new Input System so explaining is kinda haard

fickle geyser
#

is using raycast or collisions better for checking if the player is on the ground?

ebon robin
#

I know a temporary solution which is to add this to the PlayerController

private void OnFire()
    {
        stateMachine.currentState.OnFire();
    }
#

any better way of doing this

#

yep that solves the problem for now

#

still don't know anything about the new Input System

#

how stupid am I

ebon robin
#

you dont wanna mess with OnCollisionEnter

eternal needle
fickle geyser
#

well i have an issue

#

for some reason scenes are not uploading to github only assets

#

is that normal do i have to do something to upload the scenes along wth the assedts?

#

coould it be gitignore??

wintry quarry
#

It should be very simple for you to check if the scene file is committed or not though. Just look at the changesets. But there's nothing special to do, no

#

What makes you think they aren't being committed?

worthy chasm
fickle geyser
#

and it dosent just load

wintry quarry
wintry quarry
wintry quarry
#

That's your problem

worthy chasm
#

camera script

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

public class Look : MonoBehaviour
{
    public Transform player;
    public float sensivity = 1f;
    private float horizontal;
    private float vertical;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Cursor.lockState = CursorLockMode.Locked;
        horizontal += sensivity * Input.GetAxisRaw("Mouse X");
        vertical += sensivity * Input.GetAxisRaw("Mouse Y");
        transform.eulerAngles = new Vector3(-vertical, horizontal, 0);

        player.transform.eulerAngles = new Vector3(0, horizontal, 0);
    }
}

Player script

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

public class Player : MonoBehaviour
{
    public float speed = 1f;
    private float verticalInput;
    private float horizontalInput;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        verticalInput = Input.GetAxisRaw("Horizontal");
        horizontalInput = Input.GetAxisRaw("Vertical");

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

    }
}
wintry quarry
#

You have to move your character via Rigidbody velocity or forces if you want proper collisions

worthy chasm
worthy chasm
fickle geyser
#

theres a velocity method for rigidbodies!?!?!?

languid spire
delicate notch
#

!code

eternal falconBOT
delicate notch
#

Guys why is my object not going from and to the objects after I put it in the DDOL object?

wintry quarry
wintry quarry
fickle geyser
wintry quarry
#

Yes

#

But velocity is a property

#

We were talking about velocity

fickle geyser
#

i have a question

#

is there anyway to make something like a library

#

or a module

#

uhh basically a script that can be required that returns classes methods etc...

languid spire
#

There is asmdefs in Unity to group classes into libraries or you can make a dll project in VS which can be put into a plugins folder in Unity

fickle geyser
#

I cant see the velocity property in inspecter for rigidbodies

worthy chasm
wintry quarry
fickle geyser
#

whats info?

wintry quarry
worthy chasm
#

u can find it in debug during runtime right?

static cedar
fickle geyser
#

cant find velocity property

#

this is at run time

wintry quarry
#

It's not usual for properties to be shown in the inspector anyway

#

You can always use Debug.Log or attach a debugger

strong wren
#

It might not show up if you are viewing the inspector in debug mode

prime horizon
#

Guys I need help with my error that says: "InputManager is inaccessible due to its protection level"
I'm using Unity's new Input System package.
The line "using UnityEngine.InputSystem" is fine tho. Line 42 is causing an Error.

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems;
using TMPro;
using Ink.Runtime;

public class DialugueManager : MonoBehaviour
{
    private static DialugueManager instance;

    [Header("Dialogue UI")]
    [SerializeField] private GameObject dialoguePanel;
    [SerializeField] private TextMeshProUGUI dialogueText;
    private Story currentStory;
    private bool dialogueIsPlaying;
    private void Awake()
    {
        if(instance != null)
        {
            Debug.LogWarning("Found more than 1 DialugueManager in the scence");
        }
        instance = this;
    }
    public static DialugueManager GetInstance()
    {
        return instance;
    }
    private void Start()
    {
        dialogueIsPlaying = false;
        dialoguePanel.SetActive(false);
    }
    private void Update()
    {
        if(dialogueIsPlaying == false)
        {
            return;
        }

        if(InputManager.GetInstance().GetSubmetPressed())
        {
            
        }
    }

    public void EnterDialogueMode(TextAsset inkJSON)
    {
        currentStory = new Story(inkJSON.text);
        dialogueIsPlaying = true;
        dialoguePanel.SetActive(true);
        ContinueStory();
    }
    private void ContinueStory()
    {
        if(currentStory.canContinue)
        {
            dialogueText.text = currentStory.Continue();
        }
        else
        {
            ExitDialogueMode();
        }
    }
    private void ExitDialogueMode()
    {
        dialogueIsPlaying = false;
        dialoguePanel.SetActive(false);
        dialogueText.text = "";
    }
}
fickle geyser
#

Wait in raycasting is the second paramater just direction or do we need to define an endpoint (direction * magnitude)

wintry quarry
prime horizon
wintry quarry
prime horizon
#

Oh

wintry quarry
#

It's not part of the input system

wintry quarry
fickle geyser
#

in this case does teh second paramater need to be direction * the distance of ray

Or just the direction??

and if so how does that even work is the ray casted to an infinite magnitude or something!!

prime horizon
fickle geyser
#

im confused onto how big the magnitude of the ray is

strong wren
fickle geyser
strong wren
#

Yeah, by filling out the parameters

fickle geyser
#

am i on the right page this is really vague

strong wren
wintry quarry
fickle geyser
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class Player : MonoBehaviour
{
    public Rigidbody rb;
    public float speed = 1f;
    private float verticalInput;
    private float horizontalInput;


    private bool OnGround;
    public float jumpPower = 10;

    RaycastHit hit;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Ray ray = new Ray(transform.position, -Vector3.up);
        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log(hit.distance);
            if (hit.distance > transform.localScale.y +0.1)
            {
                OnGround = false;
            }
            else
            {
                OnGround = true;
            }
        }
    }
    private void FixedUpdate()
    {
        verticalInput = Input.GetAxisRaw("Horizontal");
        horizontalInput = Input.GetAxisRaw("Vertical");

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

        Debug.Log(OnGround);
        if (OnGround)
        {
            if (Input.GetKey("space"))
            {
                rb.AddForce(transform.up * jumpPower);
            }
        }
    }
}

for some reason jumping near an edge flings me high up

delicate notch
#

I need some help

#

My DDOL varaibles are still resetting when changing scenes and im very confused

#

!code

eternal falconBOT
fickle geyser
#

cs??

delicate notch
#
using UnityEngine;

public class DDOLManager : MonoBehaviour
{
    // Singleton instance
    private static DDOLManager instance;

    // Variables to store
    public int score = 0;
    public int health = 100;
    public bool isLevel2 = false;

    void Awake()
    {
        SetupSingleton();
    }

    void SetupSingleton()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }
}


fickle geyser
#

isnt c# and cs same thing

timber tide
#

c-sharp

timber tide
#

Uh, looks fine to me, but how are you accessing this instance if you're making it private anyway

delicate notch
#

My other script

private DDOLManager ddolManager;

void Start()
    {
        Boundaries();
        if (ddolManager == null)
        {
            ddolManager = FindObjectOfType<DDOLManager>();
        }
    }
delicate notch
#

Pls if someone knows issue reply, ty

burnt vapor
#

Try logging that if statement at the bottom, see what it does on scene change

#

Try putting DontDestroyOnLoad(gameObject) in the else statement perhaps

#

Just see what sticks for now

verbal dome
fickle geyser
#

for some reason A and D just dosent work anymore

#

when using velocity

burnt vapor
#

Because you're replacing the first assignment of velocity

#

First you set the right axis, then you replace it with the forward axis

fickle geyser
#

?? what does that mean

burnt vapor
#

Not sure how more clear I can be

#

You're assigning the velocity, then replacinge velocity completely on the next line

fickle geyser
#

oh yea!!!

delicate notch
#

Im dumb

fickle geyser
#

btu then i cant walk diagonally anymore!!

#

gonna need a conditional for that i

#

think

burnt vapor
#

No, just combine them

burnt vapor
fickle geyser
#

combine unit vectors then multiply by magnitude??

delicate notch
#

I was displaying a different variable points cause i forgot to delete it

delicate notch
#

But i fixed both now so

verbal dome
#

Or just replace the bottom rb.velocity = with rb.velocity += so that it adds to the velocity instead of overriding it

ebon robin
#

I see this guy refering to BugPrefab directly as Bug but I can only see myself able to refer it to as GameObject. How to do it like this?

ebon robin
#

i have a prefab in the prefab folder called Slime which is a prefab of Slime monster. However, I want to make another script called SlimeSpawner and make Slime a class and not refer to it as GameObject

ebon robin
eternal needle
north kiln
ebon robin
#

oh right

#

it spawn the entire thing?

#

didn't know that

north kiln
#

Yup

delicate notch
#

Yo guys

#

To call a method from another script can you take a look at this because its not being called

#
public void LoadLevel1()
{
    SceneManager.LoadScene("GameLevel1");
    if (ddolManager != null)
    {
        // Call the method from DDOLManager
        Debug.Log("Variables Reset!!!");
        ddolManager.ResetVariables();
    }
    FindObjectOfType<GameSession>().ResetGame();
}


#

Also whats this error?

ebon robin
#

the script seems normal can you screen shot the error

delicate notch
#

I dont get error

#

Idk what this one is though ^^

#

does not say where the error is

ebon robin
#

have you tried reimporting everything in the asset drop down

delicate notch
#

Wait i have an idea

eternal needle
delicate notch
#

Ok so the script Level 1 is being loaded but the other one is not

ebon robin
#

just reimport things. I guess it is something corrupted

delicate notch
#

Strange since its a DDOL

#

Could it be Null maybe?

#

somehow

eternal needle
delicate notch
#

I got another idea!!!!!

#

Il try putting the reset variables imediatly in the level 1 script

#

nvm im braindead that dont work

#

the pain

eternal needle
delicate notch
#

THe reset variables isnt running

split dragon
#

Hi. I made a counter of how many objects the player collects that have a script: "Note". There is a problem that 1 such object can be added to the counter infinitely times (1 object gives more than once). I tried to think of a way to fix it, and all attempts failed. How can I fix this?

ivory bobcat
ivory bobcat
#

Then maybe you ought to register acquired items in some sort of collection, such as a hash set.

split dragon
north trout
#

Hi

#

I want to write my own shader, I have an idea for it. But i'd like to start with a basic one which already implements texture mapping. Do you know where I could find that to start off with?

dusk minnow
#

Just a quick Qestion i have two objects one is null . Can i switch them so obj1 = something obj2=null;

#

by doing obj1=obj2 and obj2=obj1

#

ofc with extra var

languid spire
#

?

if (obj2 != null) { obj1 = obj2; obj2 = null; }
dusk minnow
#

GameObject tempItem = currentActiveItem; currentActiveItem = backedItem; backedItem = tempItem;

#

if one of them is null

#

will it work?

#

works xD

languid spire
#

define 'work'
it wont throw an exception but you still wont know which one is null

dusk minnow
#

shouldnt do that just change

languid spire
#

it will swap the objects over, yes. But to what effect?

dusk minnow
#

for a game

#

dw haha

boreal tangle
#

Is it better to move player through addforce or changing the velocity.

keen dew
#

If you don't have a particular reason to set the velocity directly then use addforce

boreal tangle
#

Would it make sense to use it for snappy movement or is that something you can do with addforce

keen dew
#

Either works

boreal tangle
#

Ok ty

fickle geyser
#

i saw a guide where someone is storing the orientation of the player (capsulate) in a empty game object. This here confuses me. Why not just grab the orientation directly from the player himself??

another thing is he made a cameraholder object for the player. Why not just directly make the camera follow the player?? These things confuse me

nimble blaze
#

hello good morning do you guys know anyway of killing all animations to go straight to my dying animation when the character dies right now to activate in on any state but for the most part it works fine but the death animation kinda gets messed when in middle of a jump or just started walking

#

its like a bug

rare basin
#

animator.CrossFade() perhaps

autumn tusk
#

ok so im creating an aiming system for my game, and i need the firepoint to switch position when the gun sprite flips

#

only issue is that this runs every frame, when i want this to only run once per flip

#

how would i get the commented code to only run once per flip

verbal dome
#

If yes, run the code that changes the firepoint's position

kind cave
#

Why my animation curve doesn't have fixed time 0 1?

frosty hound
#

You tell us? Drag the end point where you want it to be?

kind cave
worthy chasm
#

https://medal.tv/games/requested/clips/1INMhX3RDRZNjJ/d1337pUrF1IM?invite=cr-MSxiQ0osMjAzNDI1NDA5LA

as soon as i go in my character goes immediately backwards, why may this be?

pastebin:
https://pastebin.com/JdYwH2k6

Medal.tv | #1 Free Clip Platform

Watch Untitled and millions of other Requested videos on Medal, the largest Game Clip Platform.

▶ Play video
rich adder
#

man pastebin sucks. mods should remove it

#

half the page taken up by nonesense..

rich adder
#

cause your speed is > 0 so
put debug.log inside VelocityLimiter too, see how many times thats called.

shut mango
#

Hello everyone, I've just begun my first 2D game project, and I'm still a beginner. I wanted to ask: can anyone advise me on how to start creating movement for my 2D character?

summer stump
rich adder
#

topdown , sideview etc

#

4 direction , 8 direction, 2 direction

#

grid movement

worthy chasm
#

@rich adder whenever i remove statehandler, the thing is fixed

#

why is that

shut mango
rare basin
worthy chasm
buoyant knot
rich adder
rich adder
#

otherwise im not sure how anything x 0 would be anything but 0

buoyant knot
#

i would start by deciding if you want your object to be kinematic or dynamic. This is probably the biggest factor in how complicated it will be

worthy chasm
rich adder
#

unless its speed which would probably not be important if AddForce includes moveDirection (assuming its 0 with no inputs)
Debug.Log(moveDirection)

buoyant knot
#

dynamic rigidbodies are at the mercy of the physics engine. they automatically collide with walls etc, and are affected by gravity and forces etc. But programming extremely basic forced motions is difficult (eg making a dynamic RB move along a floor of changing slope), because you have to fight the physics system.

worthy chasm
# rich adder ok well it doesn't seem statehandler does anything but set states that aren't us...

https://youtu.be/xCxSjgYTw9c im following this video if that helps

SLOPE MOVEMENT, SPRINTING & CROUCHING - Unity Tutorial

In this video, I'm going to show you how to further improve my previous player movement controller by adding slope movement, sprinting and crouching. (You can also use your own player controller if you want to)

If this tutorial has helped you in any way, I would really appreciate it if you...

▶ Play video
rich adder
worthy chasm
rich adder
worthy chasm
#

after that it broke

rich adder
#

those enums dont do anything right now though

#

also you should not be grabbing inputs inside FixedUpdate

#

verticalInput = Input.GetAxisRaw("Horizontal");

worthy chasm
#

yep

#

ill fix that

rich adder
#

Debug.Log(moveDirection)

worthy chasm
#

alr one sec

rich adder
#

i still think it could be VelocityLimiter

worthy chasm
#

do you want me to debug.log velocity limiter too?

rich adder
worthy chasm
#

what the heck

#

i restarted unity and now it works 💀

rich adder
#

i think your inputs was stuck

#

or maybe you had a controller plugged in?

worthy chasm
#

yeah some software side stuck

worthy chasm
#

i do have

#

xbox controller

#

but rn its doing nothing

#

it doesnt have stick drift or anything

#

and its still plugged in

rich adder
#

cause only way it would b moving on its own if rb.AddForce(moveDirection.normalized moveDir was not 0

summer stump
#

I feel like the controller was definitely it

worthy chasm
#

well its fine now

rich adder
#

yeah i think it was prob giving a weird signal

worthy chasm
#

controller still connected and i did not touch it

#

only restarted unity

rich adder
#

maybe controller go to idle or something

worthy chasm
#

good thing its fixed

#

thanks for dedication to helping

#

💪

modest barn
#

Is there a way of making a variable's value invisible in the Inspector but still accessable by other scripts?

abstract flax
#

can someone help me with something i will tell in dm and in dms i will send unity file

summer stump
abstract flax
#

oh k am new here

verbal dome
#

Just ask your question in this channel

abstract flax
#

can someone hlep me i have problem with colliders player(capsule) fall down even tho theare is plane with colliders on i will send unity file in dm

frosty hound
eternal falconBOT
summer stump
#

Do both the player and plane have colliders that are NOT set to isTrigger?

near cargo
#
public class GameStateController : MonoBehaviour
{
    SolvebitController sbGameState;
    GuessbitController gbGameState;
    SeriesbitController srbGameState;
    MembitController mbGameState;

    private void Awake()
    { // omitted initialization }

    void Start()
    {
        if (GameParams.game == SelectedGame.Guessbit) gbGameState.Start();
        if (GameParams.game == SelectedGame.Solvebit) sbGameState.Start();
        if (GameParams.game == SelectedGame.Seriesbit) srbGameState.Start();
        if (GameParams.game == SelectedGame.Membit) mbGameState.Start();
    }

    void Update()
    {
        if (GameParams.game == SelectedGame.Guessbit) gbGameState.Update();
        if (GameParams.game == SelectedGame.Solvebit) sbGameState.Update();
        if (GameParams.game == SelectedGame.Seriesbit) srbGameState.Update();
        if (GameParams.game == SelectedGame.Membit) mbGameState.Update();
    }

    // omitted 2 other similar functions
}

How could I rewrite this if all of those classes are based on public abstract class GameController<T> where T: Gamemode. I tried using covariant generics but my base class is not an interface, and it has to be a class

abstract flax
#

i will check

summer stump
#

IsTrigger does not collide

#

They must have that option disabled

abstract flax
#

huh still doesnt work

summer stump
#

After that, it may be a code issue

abstract flax
#

ok sending

#

so i have player and capsule capsule is child of player

vagrant harness
#

I've been trying to clamp rotations for like an hour- how do I properly do it? right now I'm manually clamping the x y and z values of the euler angles but it only works for positive values

summer stump
abstract flax
#

i will send both

#

here all screenshots

summer stump
# abstract flax

So that capsule is a child? Does the parent also have a rigidbody?

abstract flax
#

yes

summer stump
# abstract flax yes

Remove the rigidbody from the capsule. Let the parent rigidbody use the collider

I think the parent is falling and updating the position of the child. The childs collider is "used" by its own rigidbody, and won't affect the parent

abstract flax
#

now i dont fall trough plane but before i land i go diagonaly

summer stump
#

Or just moving by itself?

abstract flax
#

moving itself

wintry quarry
summer stump
#

@abstract flax I do notice the child colliders position is not 0,0,0
So it is offset from the parent.
Probably not the issue, but it is a issue

near cargo
#

but i need the generic

wintry quarry
#

a non generic parent

near cargo
#

oh

wintry quarry
#

a generic child

near cargo
#

i get what you mean

wintry quarry
#

and then the generic concrete children

summer stump
# abstract flax moving itself

But for your issue, is it spinning weirdly, or just moving while keeping the same rotation?
That would be two different issue

If it keeps the rotation, it's gonna be a code issue

If it spins, try freezing the x and z rotations on the rigidbody

wintry quarry
#
GameController
  GameControllerT
    SolvebitController
    GuessbitController
abstract flax
#

it still countinues to spin

#

and falls trough plane

summer stump
# abstract flax and i gtg now

Oh sorry, missed ya.
A couple things to try when you can.
Set the interpolate settings on the rigidbody to interpolate (instead of none)
Set collision detection to continuous.
Freeze all rotations in the constraints

After that, post the movement code as osteel said above
#💻┃code-beginner message

abstract flax
#

ok

near cargo
abstract flax
#

i will send code rn

summer stump
# abstract flax

Ah, you're mixing a charactercontroller and rigidbody.
You gotta choose, don't have both

#

Also, configure your !ide

eternal falconBOT
abstract flax
#

ok will do that when i come back

wintry quarry
modest barn
#

Having trouble with an Index Out of Bounds error.
This is the line that the error is being caused by:

char newCh = lowerAlphabet[Array.IndexOf(lowerAlphabet, ch) + shuffle];

This is lowerAlphabet:

public static readonly char[] lowerAlphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

And ch is h, or e or l or anything else in hello world. In this case, shuffle is 6, but I also have this line to account for shuffles more than 26 (this is for a Caesar Cipher):

shuffle %= 26;

Can someone help me out? This is the exact error:

IndexOutOfRangeException: Index was outside the bounds of the array.
#

This was working before so I don't really know what changed.

wintry quarry
modest barn
#

But that can't be possible in this case

wintry quarry
#

you need to modulo that whole expression by lowerAlphabet.Length

wintry quarry
modest barn
#

Debugging shows it failed on h

#

h is index 7 in lowerAlphabet, shuffle is 6. Shouldn't fail.

#

Right?

wintry quarry
modest barn
#

Sorry, I'm not following. Why would I debug lowerAlphabet.Length? That's a fixed number.

#

So is shuffle.

wintry quarry
#

clearly one or more of your assumptions is wrong

#

else you wouldn't have a problem

modest barn
#

Ok, fair point. I shall go and try it out

wintry quarry
#

check everything, even the things you think you know are true

polar acorn
modest barn
near cargo
polar acorn
wintry quarry
modest barn
#

Ok, will do

wintry quarry
near cargo
#

right

modest barn
modest barn
wintry quarry
#

25 would be wrong anyway, no? 26 right?

modest barn
wintry quarry
#

yes

modest barn
#

Wait

wintry quarry
#

% 26 gives you a number in the range [0, 25]

modest barn
#

Oh

#

Thought I was being smart 🤦

near cargo
#

@wintry quarry thank you so much!!

#

took me like a few days to figure this out 😓

#

now it would be left to store my games in a dictionary

modest barn
#

@wintry quarry @polar acorn Thank you both for all the help, turns out my int parsing for the shuffle was wonky - debugging that helped. Thanks!

prisma blaze
#

I have an object moving on the zaxis, if it collides with an obstacle, the obstacle's oncollisionenter will be called, and that calls the gameover function of the object, which is this


        alive = false;
        animator.Play("Fall");
        rb.AddForce(new Vector3(0,0,-50));
        Invoke(nameof(Restart), 3);

however, rb.addforce is called, but there is no effect on the scene

#

does addforce not work outside fixedupdate?

slender nymph
#

you probably want that to use ForceMode.Impulse

prisma blaze
#

it works now, thanks

graceful flame
#

can somone help me for a sec...

I am trying to make a small chunk builder, and it "works" so far when I use some tricks... but in the GenerateChunkMap function, I was trying to not have to pass through my public object that I want to spawn, cause I want to spawn multible types and potentially more than I am already am. I want to define this there... essentially... so having to pass it into it is not what I want/need

the paln was to have it like my 4th image (error highlighted) but I don't exactly understand why this is a problem here... seeing that my subclass should have access to the prior public game object, shouldnt it?

#

I cant make the street_streight static though, as I pass it into my unity script... or am I missing something?

#

eg... blue-box should be my gameobject that I pass into the script...

slender nymph
#

you still need to give the class a reference to an instance of the World_Generator class

cosmic dagger
spring coral
#

is there a Debug.DrawLine equivalent for drawing on the UI?

slender nymph
graceful flame
#

or am I currently sitting on tomatos?

verbal dome
slender nymph
#

you need to tell the MapChunk object which World_Generator object you are using

spring coral
#

huh, ive never seen GL

verbal dome
spring coral
#

URP

#

looking at the GL docs it looks like something si up with URP

#

something about being unable to use OnPostRender()

graceful flame
verbal dome
slender nymph
spring coral
#

that looks right

graceful flame
#

that works...

#

looks strange... but ok

slender nymph
#

alternatively you could just pass the object you are trying to access instead of the World_Generator

graceful flame
#

I... yes... I could also just pass the list of objects...

#

head meets desk

#

thanks

celest holly
#
public class MoveCamera : MonoBehaviour
{
    [SerializeField] private Camera cam;
    private Vector3 mousePos;

    private void Start()
    {
        mousePos = Input.mousePosition;
    }
    void Update()
    {
        if (Input.mousePosition != mousePos)
        {
            moveCamera(Input.mousePosition);
        }
        mousePos = Input.mousePosition;
    }

    private void moveCamera(Vector3 mousePosition)
    {
        Vector3 translatePos = new Vector3(mousePosition.x, mousePosition.y, cam.transform.position.z) * Time.deltaTime;
        cam.transform.Translate(translatePos, Space.Self);
    }
}

Does anyone know why this code is only moving my camera up and to the right?

wintry quarry
#

Seems like you're using mouse position when what you want is the mouse delta aka the amount moved?

#

Also using cam.transform.position.z in there makes no sense either, should be 0

#

you are confusing positions with deltas (aka the amount to change by) in several places here.

celest holly
#

ohhh I see

#

ill try and figure out how to find the delta instead then

#

thank you

wintry quarry
celest holly
#

so helpful

#

thank you very much

weary moss
#
if (GameObjectExample)
{
}

will it check if the gameobject is active?

wintry quarry
weary moss
#

alright

weary moss
#

thanks

ripe wedge
wintry quarry
#

You should probably fix those, it may fix your problem.

ripe wedge
#

It’s the same error

wintry quarry
#

Also why on earth is your code shared as a pdf lol

wintry quarry
#

you should focus on that

#

Use one of the sites here to share code: !code

eternal falconBOT
ripe wedge
wintry quarry
#

You have to press "Paste It" at the bottom

#

then share that link

wintry quarry
#

Looks like you have at least two separate errors

#

both of them are in WeaponSlotManager, NOT in the PlayerInventory script

ripe wedge
wintry quarry
#

Meaning it was either never assigned, or it was assiged to null

ripe wedge
#

Which confuses me because if I remove the code for switching weapons everything works fine but when I switch from unarmed to the weaponItem the weapon object doesn’t load and when I attack it gives me an invisible weapon that makes that error

weary moss
#

what is the time frame in which Input.touchCount works? like if i touch the screen two times in the span of a second, will it count those two?

bold swallow
#

Why are physics behaving different in webgl and in windows?

polar acorn
wintry quarry
bold swallow
polar acorn
#

Physics goes in FixedUpdate

polar acorn
#

It is how many touches are currently happening right now

bold swallow
turbid roost
#

´´´cs

How do i make it so when i press e and im not grounded the camera quikcly zooms in and out???

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

public class Dash : MonoBehaviour
{
public float dashDistance = 5f;
public Camera cam;

private CharacterController controller;
private PlayerMotor playerMotor;

public float dashTime = 0.5f; // Duration of the dash
public float zoomFOV = 60f; // Adjusted FOV during dash
private float originalFOV;
private float dashTimer;

void Start()
{
    controller = GetComponent<CharacterController>();
    playerMotor = GetComponent<PlayerMotor>();
    originalFOV = cam.fieldOfView;
}

void Update()
{
    zoomFOV = cam.fieldOfView - 10f;
    if (Input.GetKeyDown(KeyCode.E) && !playerMotor.isGrounded)
    {
        Foward();
        cam.fieldOfView = Mathf.Lerp(zoomFOV, cam.fieldOfView, 10); // Smoothly restore FOV
    }



}

private void Foward()
{
    Vector3 dashDirection = cam.transform.forward;
    Vector3 dashVector = dashDirection * dashDistance
    controller.Move(dashVector);
}

}`

eternal falconBOT
wintry quarry
#

you need to fix the errors, that's what I was helping you with

ripe wedge
#

Oh right

abstract flax
#

this is my code but unity says Member modifier private must precede the member type and name am new to unity if anyone can help me

polar acorn
eternal falconBOT
ionic pike
#

does anyone know shader graph??

summer stump
abstract flax
#

i configured ide

polar acorn
wintry quarry
abstract flax
polar acorn
#

Take a look at the lines underlined in red and compare them very closely to the tutorial

abstract flax
#

i replace stuff with red code?

summer stump
#

For example, if your code doesn't have a semicolon and theirs does, then add the semicolon

abstract flax
#

am oofed i have 80 lines of red code

wintry quarry
#

likely a minor issue with brackets or semicolons or parentheses etc

abstract flax
#

ok

#

and it also generated some not red code

ripe wedge
west phoenix
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestScript : MonoBehaviour
{

   private List<IEnumerator> coroutineList = new List<IEnumerator>();
   // private int currentCoroutineIndex = 0;

    int difficulty1;
    int difficulty2;
    int difficulty3;
    bool routineRun;
    // Start is called before the first frame update

    void Start()
    {

        coroutineList.Add(Pattern1());
        coroutineList.Add(Pattern2());
        coroutineList.Add(Pattern3());
        StartCoroutine(CycleCoroutines());
       // StartCoroutine(Pattern1());

    }

    // Update is called once per frame
    void Update()
    {
        print("1: " + difficulty1);
    }

  IEnumerator CycleCoroutines()
    {
        while (true) // Infinite loop
        {
            print("looping");
            foreach (var coroutine in coroutineList)
            {
                print("for loop");
                StartCoroutine(coroutine);
                yield return new WaitForSeconds(1);
            }

           
        }
    }

    private IEnumerator Pattern1()
    {
        //routineRun = false; 
        print("reaching while loop 1");
        while(true)
        {
            print("hello");
            difficulty1++;

            yield return new WaitForSeconds(2);

            if (difficulty1 == 2)
            {
                difficulty1++;
                break;
               
            }

            print("pattern 1");
        }
       
    }

    private IEnumerator Pattern2()
    {
        while (true)
        {
           

            difficulty2++;

            yield return new WaitForSeconds(2);

            if (difficulty2 == 2)
            {
                difficulty2++;
                break;
            }

            print("pattern 2");
        }
    }

Im trying to make an infinite loop which loops through all the patterns i have in the game. Right now it just loops one then get stuck in the first loop

wintry quarry
wintry quarry
west phoenix
wintry quarry
#

oh also you can't reuse an IEnumerator

west phoenix
#

it just starts infinite looping in the CycleCoroutines() loop forever and stops printing inside any of the Patern functions

wintry quarry
west phoenix
wintry quarry
#

once you call StartCoroutine on it once, you can't do it again

wintry quarry
west phoenix
#

LMAO

wintry quarry
#

you just need to call the function again to get a new IEnumerator

west phoenix
#

So i keep recalling the Cycle function?

wintry quarry
#

no

#

instead of List<IEnumerator> you can make it a List<Func<IEnumerator>> and put the functions themselves in the list

#

and invoke them in the loop

#

like StartCoroutine(coroutine());

west phoenix
#

I see, is there a simpler way?

wintry quarry
#

this is very simple

west phoenix
#

i see

wintry quarry
#

you would need to change approximately 3-4 lines of code here only very slightly

west phoenix
#

Could u maybe potentially help me with finding out which lines?

wintry quarry
#

I already told you

wintry quarry
west phoenix
#

so i just add Func generic there and im good?

wintry quarry
wintry quarry
#

Adding the IEnumerator to the list:
coroutineList.Add(Pattern1());
Adding the function itself to the list:
coroutineList.Add(Pattern1);

west phoenix
#

i seeee

#

tysm lemmie try that

#

ill let u know how it goes

west phoenix
#

List<Func<IEnumerator>>

#

i tried adding this in

#

but it didnt work

summer stump
#

Why Func?

west phoenix
#

He said to make it so it stored the action function instead of the return

summer stump
#

Oh, I see that. You're right.
What is the error?

west phoenix
summer stump
#

What is the error?

west phoenix
#

gimmie 2 secs

#

Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'Func<>' could not be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\alltg\DF 2.0\Assets\Scripts\Enemy\TestScript.cs 8 Active

#

Holy shit my Internet died

slender nymph
#

you're missing a using directive

summer stump
west phoenix
#

Very weird

#

I get the idea but for some reason it just does let me set func

summer stump
#

Share the !code

eternal falconBOT
west phoenix
empty yoke
#

If I have a bunch of AI units spawning, and I want them to start moving somewhere, right now I pass a single "targetLocation" position for them to move towards, however, obviously this looks super bad with a mass of things all going to the same point, what's a good starting point to try and have them have a better distribution of their target location? There's gonna be ALOT of units, so I don't really want to use navmesh's for this that sounds like it would be unscaleable unless I devoted a lot of time to it.

wintry quarry
#

basically take all the units you have selected, take the destination point, and use some kind of formation logic to give each of them a slightly different destination point

#

You almost definitely will want to use NavMesh or some kind of pathfinding algorithm

#

you will need this to make sure all the destination points are valid

empty yoke
#

oh sorry to be clear, these units spawn, and individually, they have a target location and they just start moving towards that location (its enemy zombies moving towards your like...base wall, I just want them to not all move to the same point) though I see still how what you're describing could work

wintry quarry
#

I just want them to not all move to the same point
I mean that's pretty self explanatory - pick different points for them

#

or have them pick at random from a set of valid destination points

empty yoke
#

yeah so at the end of the day its still just manage a handful of nodes, I can't create a more generic...thing, okay that makes sense

zealous oxide
#

hello. if i was to use materialNameHere.SetColor(xxx,ExampleColorHere) on the same material but on different objects and within different independent scripts, will it change the color of the material on a per object basis or does changing the color of the chosen material attached to the renderer change the whole materials color so it ends up being the same on every object with that same material? sorry if I've worded this poorly, its hard to articulate

wintry quarry
#

it's not a name of a material, it's a reference to the material

#

so it really depends which references you're using and where you got them from.

zealous oxide
#

in this instance it would be: pixelOutlineMaterial = GetComponent<Renderer>().material;

zealous oxide
#

oh sweet, so I can use it as a shared material or a (non shared) material

heavy isle
#

I'm making my first game rn. It's a simple game with a cube that shoots bullets at enemies. I'm having trouble with the bullets dealing damage to the enemies, as the enemies arent losing health or being destroyed when health is 0. Here is my code:

using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class EnemyScript : MonoBehaviour
{
    // Start is called before the first frame update
    public int Health = 5;
    public int MaxHealth = 5;

    public GameObject Enemy;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.name == "bullet(Clone)")
        {
            Health = Health - 1;
            if (Health == 0)
            {
                Destroy(Enemy);
            }

        }
    }
}
swift crag
#

You should add some Debug.Log statements to the collision method.

#

This will tell you if the method is getting called at all, or if that if statement is succeeding

#

it walks you through all of the possible problems

#

The code looks OK to me, so I'm guessing your problem lies elsewhere.

slender nymph
#

also you really shouldn't rely on gameobject names for logic. i'd recommend using a tag and the CompareTag method instead

swift crag
#

yes, indeed, other than that :p

#

alternatively, the bullet should have a "Bullet" component

#

you could even make bullets that do more damage

heavy isle
swift crag
#

using names is very fragile

slender nymph
wanton crow
#

it's fine for beginners, it'll click at a certain point, i'd recommend just making a giant mess of your first project, you'll learn a lot more actually getting things to move around and interact.

ruby ember
#

anyone can help me question mark text toggle like
when i press the question mark and it appears the text for like 5 or 7 seconds and the text is gone

heavy isle
lofty lotus
#

anyone know why my instantiated bullet game object won’t move while the object sitting in my schene moves with velocity (this is for 2d using dynamic)

slender nymph
#

not without more info

swift crag
sudden adder
pearl bramble
#

Do I need to know how to code to make a game?

frosty hound
#

Yes

sudden adder
frosty hound
#

No game will require no code

pearl bramble
#

What type of code?

sudden adder
#

At least a version of coding if you include scratch

frosty hound
#

C# is what Unity uses

pearl bramble
#

Are there courses that are free or affordable?

frosty hound
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

sudden adder
# lofty lotus yeah

You gotta provide more info, show the script and show the bullet in the inspector

lofty lotus
sudden adder
#

Show the bullet in the inspector at runtime and its movement script. Also show the script instansiating it, is it instansiating the correct prefab?

lofty lotus
heavy isle
#

I revised it but it still aint working...

    {


        if (collision.gameObject.CompareTag("bullet"));
        {
            Debug.Log("ENTER");

            Destroy(Enemy);

        }
    }```
#

maybe ill try using an actual collider

slender nymph
#

put a log outside of the if statement to make sure that OnCollisionEnter2D is actually being called
oh wait, it's already outside the if statement

wintry quarry
#

Also yes your if statement is broken

#

because you put a semicolon after the condition

heavy isle
#

swapped OnCollisionEnter2D for OnTriggerEnter2D

wintry quarry
#

If you want OnTriggerEnter2D:

  • At least one has a dynamic or kinematic Rigidbody2D
  • Both need collider2ds
  • At least one collider is a trigger
summer stump
wintry quarry
#

This is 2D

#

we don't have CCs here

summer stump
#

Yeah I was just about to say I missed the 2d, sorry

heavy isle
#

I've set up OnCollisionEnter2D to the conditions

#

nothings working...

wintry quarry
normal magnet
normal magnet
polar acorn
polar acorn
small mantle
#

Hello! I'm trying to understand how to make a roof tilemap fade when the player enters a house.

#

Its TopDown 2D

normal magnet
terse osprey
#

Hello, I am making a game with some weapons I have picked up from the asset store. I have parented the weapon to the characters right hand for the animations to work properly but for one of the weapons the animations alternate where one animation requires the character to hold the weapon in the right hand while the requires to hold in the left hand. Is there any way for me to change the parent(hand) of the weapon when the different animations play?

small mantle
#

Why doesn't this code work? cs private void OnTriggerEnter2D(Collider2D collision) { if (tilemapCollider) { print("Hit"); } }

ivory bobcat
#

Is tile map collider null?

#

Is the physics event occurring?

#

Try printing outside of the if statement.

wintry quarry
queen adder
#

im staring at unity code and i keep seeing plus equals be used to poll events with the new input system. Why?

#

how does this work?

sage elm
#

Hi guys
How are you?

I was following the retro fps tutorial and I'm having a problem with my enemy's code.

He is able to see the player through the wall, I tried using raycast to solve this, but I still have the problem.

My code currently looks like this and when the player gets close to the enemy the console prints "Nothing", even though the player is in front of the enemy or behind a wall, does anyone know how to solve this?

wintry quarry
queen adder
#

delegate? whaaa

wintry quarry
queen adder
#

oh god i thought i was done with pointers

#

aghhh the ptsd

wintry quarry
wintry quarry
terse osprey
wintry quarry
#

well it is but you don't need to worry about it

#

anyway if you're doing programming you have to deal with pointers at some level full stop lol

wintry quarry
normal magnet
terse osprey
#

I am sorry I am really a beginner, when I put this script as an animation behaviour it didnt let me choose a game object at all

small mantle
plucky matrix
#

Hello I would like to learn coding, does anyone have any simple tutorials that would give a good start?

small mantle
wintry quarry
small mantle
wintry quarry
#

what are you expecting to happen?

#

What happens instead?

small mantle
#

The interaction isn't happening. When I move into the box, it doesn't print("Hit"). Nothing happens.

wintry quarry
#

BoxCollider is not a 2D collider

small mantle
#

It is a Boxcollider2D

wintry quarry
#

Ok, so show the inspector of both objects involved in this interaction

wintry quarry
#

of both objects

#

need to see more than this

#

Also explain which script has the above code

small mantle
#

The "ChangeTiles" has the script @wintry quarry

wintry quarry
#

nor a Rigidbody2D

#

If you want OnTriggerEnter2D to run, you need:

  • A Rigidbody2D on one of the objects
  • Both objects have a Collider2D
  • At least one of the colliders is a trigger
#

It's also unclear to me what the point of the "Tilemap Collider" field on the ChangeTiles script is for. Seems relatively pointless

north kiln
silver heron
#

hey. Is it better to start learning with 2d or 3d?

surreal sundial
wintry quarry
surreal sundial
silver heron
wintry quarry
eternal falconBOT
#

:teacher: Unity Learn ↗

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

silver heron
small mantle
wintry quarry
#

If you changed things, please share new screenshots

small mantle
#

Why doesn't this code work? cs private void OnTriggerEnter2D(Collider2D collision) { if (tilemapCollider) { print("Hit"); } }

#

I thought it might be something after stating the collider

wintry quarry
#

Because, as per what you shared before, you don't have all the things you need on the objects for OnTriggerEnter2D to run

wintry quarry
small mantle
wintry quarry
small mantle
ivory bobcat
normal magnet
#

@polar acorn plz later show me how i change it

small mantle
ivory bobcat
#

private void OnTriggerEnter2D(Collider2D collision)
collision would be the collider that was triggered.

queen adder
#

Hello.

#

Why is this error is coming? When I click download on any package, in Package Manager. This error comes. Help me please. I'm using Unity 2021.3 LTS.

wintry quarry
#

something's wrong with it right now

queen adder
pulsar oasis
#

fucking Unity fix your shit please

#

trying to install some stuff through package manager!!!

#

how often does this happen @wintry quarry

lapis pebble
#

Does beginner coding truly come here for starting?

wintry quarry
pulsar oasis
#

that what k8s are for tho

wintry quarry
#

Even with k8s

pulsar oasis
#

multiple clusters tho plz unity

wintry quarry
#

k8s is a double edged sword. It can actually make it super easy to screw shit up very fast 😉

pulsar oasis
#

a let down for sure, when you have time blocked out to do something

wintry quarry
#

Maybe someone needs to mean tweet them

pulsar oasis
#

.... not what I like to see

wintry quarry
#

As an additional data point I just tried to download an asset and got the same error

pulsar oasis
#

I have heard this happens like pretty frequently

#

specifcally for Unity

summer stump
lapis pebble
#

Alright, least in the right spot

#

Needing to learn coding kinda soon but effectively but I’ve ran into the issue that after trying to study a video explaining stuff, brain sorta tunes out after a while

#

And one video I was watching about first person movement but I am mainly trying to go for 3rd person movement and that

static cedar
#

Did you learn how to use c# first?

frosty hound
#

Nope

wintry quarry
#

Yes I did.

pulsar oasis
#

is there anyway to manually import packages?

#

or do I have to wait for Unity to wake up from their deep slumber

lapis halo
#

i'm attempting to make a simple top down shooter. The code for the actual firing, works but constantly fires without the press of "fire1"

wintry quarry
lapis halo
#

How do I do that again, it's been a while since i've worked on anything

wintry quarry
#

!code

eternal falconBOT
lapis halo
#
public class shoot : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;

    public float bulletforce = 20f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1")) ;
        {
            Shoot();
        }
    }
    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(firePoint.up * bulletforce, ForceMode2D.Impulse);
    }

}```
wintry quarry
#

you should be getting a warning about this in your code editor

lapis halo
#

My IDE doesn't seem to do that all the time, I have set it up with the instructions here several times with little to no change.

wintry quarry
#

You're going to have a huge amount of trouble learning this without a configured IDE.

lapis halo
#

My mistake.

pulsar oasis
#

Can someone ping me when package manager is back

#

I’m very sad

pulsar oasis
#

Any luck yet

static cedar
#

Problems don't solve that quickly.

eternal needle
static cedar
#

Is the package on GitHub?

pulsar oasis
#

@eternal needle dang didn’t know that’s a thing

#

And Fish-net

#

How do I do that

eternal needle
pulsar oasis
#

I will try! Thank you for the info

low perch
#
playerLayer = LayerMask.NameToLayer("player");

this doesn't setup the correct layer for a raycast, how would I do it correctly?

lapis pebble
#

Any coders with adhd who able to provide coding assistance? Genuinely need the aid

#

And I’m excited to get started on my project I’m motivated to get it started

wintry quarry
#

note the difference between a layer/layer index and a layer mask

low perch
#

ok and for setting the layer I still use nametolayer?

#

because layermask is only for raycasting

wintry quarry
#

If you want to set the layer index of an object, sure you can use NameToLayer

#

that's less common

low perch
#

well when I set
gameObject.layer = objectLayer
when objectLayer = LayerMask.GetMask("object");
I get A game object can only be in one layer. The layer needs to be in the range [0...31]
UnityEngine.StackTraceUtility:ExtractStackTrace ()

How else would I do it?

topaz gorge
#
private void RotateCamera()
        {
            Vector2 rotationInput = PlayerInputManager.Instance.RotateCameraInput();

            float horizontal = rotationInput.x;
            float vertical = rotationInput.y;

            Vector3 rotation = new Vector3(vertical, horizontal, 0f);
            rotation.z = 0;
            transform.Rotate(rotation);
        }

Might someone have a clue to why my camera still rotates on the Z axis, ive done this many times and first time running into this problem

wintry quarry
#

again there's a difference between masks and layers

#

if you want to set the layer, use NameToLayer

#

if you want a mask, use GetMask

eternal needle
# topaz gorge ```cs private void RotateCamera() { Vector2 rotationInput = ...

is it actually rotating on the z axis, or are you just seeing the z change in inspector? Because rotations are stored in quaternions, it has to convert to show you it as eulers in inspector. That conversion may result it in saying it has some Z rotation, there are multiple euler angles that result in the same orientation

wintry quarry
topaz gorge
#

ah so dont use euler anlges

wintry quarry
#

or at least don't rely on them for information

#

you're seeing a "z" rotation in the inspector, that doesn't mean much

topaz gorge
#

ok

#

no its actually rotating

wintry quarry
#

note that rotating on the x axis, then the y axis is equivalent to rotating on the z axis

#

maybe a better thing would be if you step back and explain what you're trying to accomplish

eternal needle
#

you can still use it here, try it with 1 axis at a time (remove either vertical or horizontal) and it should rotate correctly visually

topaz gorge
#

Im doing a third person camera, which ive done before cant really figure out why im having issues now, im just trying to rotate on the X and Y axis and Zed shouldn't be rotated on, which im coming to the result of the Z axis also rotating. Which the camera does have a pivot point set in the center of the player

wintry quarry
#

the child rotates on local X

#

the parent on Y

topaz gorge
#

Oh thats Right

#

That how i did it thanks m8t

pulsar oasis
#

why when I make a folder in my assets folder in project can i not delete it?

#

it keeps magically coming back

topaz gorge
wintry quarry
pulsar oasis
#

im so fed up with this

gaunt sandal
#

Question about rendering something in code and culling. Lets say I render a surface (in this case an ocean) as a two dimensional array of tiles. As I move around the world do I need to figure out which tiles are in the cameras field of view and only render those myself, or will URP figure that out and cull them for me?

An example:

using UnityEngine;

public class CreateOcean : MonoBehaviour
{
    public GameObject oceanPrefab;

    private static int tileSize = 10;
    private static int xMaxOcean = 100; // multiple of time size, even or odd tiles
    private static int zMaxOcean = 100; // multiple of tile size, ideally an odd number of tiles to center on start
    private float yOcean = 0f;
    private static int xDim = xMaxOcean / tileSize;
    private static int zDim = zMaxOcean / tileSize; 
    private GameObject[ , ] oceanArray = new GameObject[xDim, zDim];

    void Start()
    {
        //return;

        int i=0, j=0;
        int xOffset = 40;
        for(int x=xOffset*-1; x<xMaxOcean-xOffset; x+=tileSize) // Start line is @ x=0. Begin the ocean behind start line.
        {
            Debug.Log("Array element: [" + i + "," + j );
            for(int z=zMaxOcean/2*-1; z<zMaxOcean/2; z+=tileSize){
                Debug.Log("Loop Iteration: " + x + "," + z);
                Debug.Log("Array element: [" + i + "," + j );
                oceanArray[i,j] = Instantiate(
                        oceanPrefab,
                        new Vector3(x*-1, yOcean, z*-1),
                        Quaternion.identity,
                        transform
                    );

                oceanArray[i,j].name = "OceanTile_x:" + (x).ToString() + ",z:" + (z).ToString();
                Debug.Log("Name: " + oceanArray[i,j].name);
                j++;
            }
            i++; j=0;   
        }
    }
}```
wintry quarry
weary moss
#

How can i detect two touches on a screen in the span of like a second?

#

Instead of it being in a frame

timber tide
#

cache the last input time then compare on second touch

weary moss
#

How do i cache something?

weary moss
timber tide
#

yep

verbal cloud
#

i have some really simple code here attempting to move the y axis of an object with the y axis of a camera. for some reason it seems like the y rotation is being normalized in some weird way. does anyone know how to mitigate this

#

cam rotation changes values between these two outputs?

eternal needle
static cedar
#

cam.rotations.euler.y

#

Something like that I think.

verbal cloud
#

ah thank you very much

#

damn quaternions

static cedar
#

It's the standard, it tracks rotations better than Euler's. :p

#

I think.

verbal cloud
#

love hate relationship

split dragon
#

Hi. I want to change the tag of the "Note" object to "!Note", after pressing the "F" key. I tried to find it on the internet and try it myself, but nothing worked. How to do it?

languid spire
split dragon