#💻┃code-beginner

1 messages · Page 319 of 1

keen dew
#

WeaponPulledOut being called? Can't tell from this code

kindred halo
#

Should I show you all the scripts used for the swap system?

keen dew
#

At least the ones that you expect to be calling those methods

scenic saffron
#

how can I create an object at the point where my mouse curser is?

keen dew
#

Which of those should call the methods?

kindred halo
#

the invokes?
That's why I added them

keen dew
#

You asked why the weapon swapping isn't working

#

Which part is supposed to call the methods that do the weapon swapping?

maiden parcel
#

hii, im doing a school proyect and i need to print the score in the GameOver scene, but they are in two different scenes, and i dont know how to do it

rare basin
#

I think I od have some asmdef issues after importing steamworks into my project, other namespaces are no longer recognized, althought i dont have any errors in the console and can enter playmode just fine.

how can i resolve this?

kindred halo
languid spire
scenic saffron
#

im typing my code in visual studio and now i cant write in between two letters it just deletes whats Infront of it probably hit a hotkey or something, can someone tell what to press?

languid spire
#

you have switched from insert mode to overwrite mode. Hit the Insert key on your keyboard

scenic saffron
#

thx

karmic kindle
#

Hey, I have these lines of code, but I'm getting an error that the function "ClosestToEnd" doesn't exist because it's referencing the GameObject - how do I reference the "tower" itself ``` public GameObject turret, building;

public void CloseEnd()
{
        turret.ClosestToEnd();
}```
languid spire
wintry quarry
#

Why write GameObject if GameObject is not what you want

karmic kindle
languid spire
#

what? that makes no sense

karmic kindle
wintry quarry
#

Is there a script named Turret or not?

karmic kindle
wintry quarry
#

Then use that

karmic kindle
# wintry quarry Then use that

If I do that then I have to make everything static which I can't do because I need to manually set the option in the inspector

wintry quarry
#

You don't have to make anything static

#

Nobody said to make anything static

#

Where are you getting that idea from?

neon ivy
#

I'm making a rhythm game and am storing the notes that need to be spawned and clicked on in a list, I am concerned about the list being too large and it being too intensive to loop through each frame to check what notes need to be spawned next.
is there a smarter way to go about this?

karmic kindle
#

You said "then use that" which suggested to me "Turret.ClosetToEnd"

wintry quarry
#

public Turret myTurret;

#

I said stop using GameObject as the type of your field. Use your actual script class like this ^

#

Then you can write myTurret.ClosestToEnd(); or whatever your function is called

wintry quarry
#

Keep an index of the current note

#

Increment it as you move through the song

neon ivy
#

this is for something like ddr or osu mania where multiple notes can appear at the same time

wintry quarry
#

Naturally

#

Doesn't change the answer

neon ivy
#

I guess but wouldn't I lose precision by just using the index?

wintry quarry
#

You only need to peek left/right in the list long enough to cover the maximum allowable input error time

neon ivy
#

ah

wintry quarry
#

That's a max of like 5 notes to look at per frame

neon ivy
#

I guess that makes sense yea note

#

then I'll just implement an int to check x amount of list items ahead

#

thanks

karmic kindle
sullen rock
#

It's kinda pointless, you are running the getcomponent for nothing

#

If you don't need to interact with the GO directly, there is no reason to store the reference to it rather than just the script

willow scroll
karmic kindle
#

I appreciate that you don't know how the code is put together, I'm just wondering if there's a noticeable different computationally. In my case, the game is essentially paused so I'm not too concerned about that and I got an error with 'myTurret.ClosestToEnd'

willow scroll
ivory breach
#

https://gdl.space/efabiyonoq.cpp Guys, I'm trying do make an image's sprite change by calling the corresponding the ChangeItem buttons with on click events, but only the code from the start function works for some reason

#

Can anyone help me investigate this issue and help me resolve it?

willow scroll
hollow dawn
#

i want to add characters in unity and when in first person you can see your hands/body. and id its multiplayer i want others to see my character aswell. can someone tell me how or send me a video on how to do this

karmic kindle
willow scroll
timber tide
karmic kindle
#

Premise - it's a tower defence game, I have ~50 nodes and ~6 towers. I'm adapting the node options so that I can change a setting on my turret, of which, the node didn't need to know about the object specifically

willow scroll
karmic kindle
ivory breach
woven rune
#

hey guys! does collision work different in the case of prefabs? I have a simple "player" object (handles movement, has rigidbody2d) and "food" object. Both objects have BoxCollider2D. The collision is working fine (Debug.Log("Triggered with object: " + other.gameObject.name);)

but when I create instances of food scattered across the area, the collision simply ceases to work and nothing happens. Do I have to somehow alter the collision to handle all instances of my object? How do I achieve that?

timber tide
#

prefab shouldnt break colliders, no

dark hatch
timber tide
#

prefabs are just like any other gameobject without the ability to reference scene elements

woven rune
dark hatch
#

do both colliding objects have a collider and a rigidbody, plus neither of them should have istrigger on

#

make sure it's rigidbody2d rather than simply rigidbody

#

same for collider

woven rune
#

white - player
green - food
grey blobs - simply background texture)

all i want is for the white to collide and destroy the green thingies
and as I said, in the case of 2 simple game objects it works fine

but when I generate multiple instances of green, the collision ceases to work

dark hatch
#

script?

#

for the white object destroying the green ones, btw

woven rune
#

!code

eternal falconBOT
woven rune
#

w8 i have no clue how to post code sec

dark hatch
#

type inside ```

#

three top dashes

woven rune
#
using UnityEngine;

public class SquareGenerator : MonoBehaviour
{
    public GameObject squarePrefab; // The green square prefab
    public int numberOfSquares = 50; // Number of squares to generate
    public Vector2 areaSize = new Vector2(50, 50); // Area size for square spawning

    void Start()
    {
        GenerateSquares();
    }

    void GenerateSquares()
    {
        for (int i = 0; i < numberOfSquares; i++)
        {
            // Generate a random position within the specified area
            Vector3 spawnPosition = new Vector3(
                Random.Range(-areaSize.x / 2, areaSize.x / 2),
                Random.Range(-areaSize.y / 2, areaSize.y / 2),
                0); // Ensure z-position is zero for 2D

            // Instantiate the square at the generated position with no rotation and as a child of this GameObject
            Instantiate(squarePrefab, spawnPosition, Quaternion.identity, transform);
        }
    }
}

This generates the green thingies

timber tide
#

what happens if you just duplicate that one object on the scene

dark hatch
woven rune
#
using UnityEngine;

public class FoodComponent : MonoBehaviour
{
    // This is just a marker component; no need to add anything here.
}

This is what chatGPT told me to do to reference the green thingies

using UnityEngine;

public class CollisionDetection : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log("Triggered with object: " + other.gameObject.name);
    }
}

and this is supposed to handle the collision

dark hatch
#

is isTrigger on(for the white circles)?

woven rune
#

yeah, for both

dark hatch
#

oop

#

only white circles

#

remove the tick from green food

woven rune
#

😮

rare basin
dark hatch
#

triggers don't detect triggers

#

weird but yeah

timber tide
#

make sure the prefab is updated

rare basin
dark hatch
#

it would cause strange problems if triggers detected other triggers lol

timber tide
#

does it matter? I thought the only requirement is that at least 1 has a trigger collider and 1 has a rigidbody

woven rune
#

sad news

still doesn't work

dark hatch
#

can you send a screenshot of the collider and rigidbody for both the objects in question

#

and, it seems i don't really know how to white circles came to be, but make sure their z position is just like green food(0)

woven rune
#

yeah their z position is set to 0 in code

woven rune
dark hatch
#

food does not have a rigidbody?

woven rune
#

the white player pixel is just an object with sprite renderer and movement is handled by

using UnityEngine;

public class Draggable : MonoBehaviour
{
    public float smoothTime = 0.3f;  // Smoothing time, lower is faster
    private Vector3 velocity = Vector3.zero;  // Reference velocity for the smooth damping

    private void Update()
    {
        Vector3 targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        targetPosition.z = 0;  // Ensure the sprite stays on the 2D plane

        // Gradually move the position towards the target position with smoothing
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
    }
}
dark hatch
#

oh, hold on

#

remember that you are calling ontriggerenter

#

if the food is generated inside the white circles, it will not be called

#

they need to enter from outside

#

hence ontriggerenter

#

is that the case?

scenic saffron
#

how do i reference a game object that was created in one void in a different void?

dark hatch
rare basin
#

they meant function type void i believe

scenic saffron
rare basin
dark hatch
rare basin
#

in the 2nd function

dark hatch
#

as well as parameter yeah depends how it's called

cinder spruce
#

Hello everyone, i want a tool tip to appear over the inventory slot when i hover over it with mouse cursor. Tooltip appears but it constantly turns on and off as long as the cursor is on the slot. I think the issue lies with the update method where it changes the transform position of the tooltip. Here's the code

private void Update()
{
    if (tooltipBackground.activeSelf)
    {
        tooltipBackground.transform.position = Input.mousePosition + new Vector3(10, -10, 0);
    }
}
rare basin
#
void SpawnObject()
{
  var spawnedObj = Instantiate(...);
  DoSthWithobject(spawnedObj)
}

void DoSthWithobject(YourObjectType obj)
{

}
#

@scenic saffron

scenic saffron
#

ok thx

dark hatch
tawny bolt
#

can someone explain why my dash counter dosent let my dash() work

#

if (dashes < maxDashCount)
{
timer += Time.deltaTime;
if (timer > cooldownTime)
{
dashes += 1;
timer -= cooldownTime;
}

        if (Input.GetKeyDown(DashKey) && dashes > 0)
        {
            dashes -= 1;
            UpdateUI();
            Debug.Log(dashes);
            Dash();
        }
        //UWU

    }

    void UpdateUI()
    {
        for (int i = 0; i < maxDashCount; i++)
        {
            DashChance[i].SetActive(dashes >= i);
        }
    }
eternal falconBOT
cinder spruce
astral basin
#

col isnt being printed idkl why pls help

dark hatch
dark hatch
dark hatch
astral basin
dark hatch
#

collision has two s

#

use an IDE

#

!ide

eternal falconBOT
quaint anchor
#

I'm getting this error when trying to get my character's run cycle to work, it says that AnimState does not match but that's the float state I set up in the animator, im lost

astral basin
dark hatch
#

it considers the function with double s a new function you made

astral basin
#

now i get an error

dark hatch
wintry quarry
#

in both spots

astral basin
#

so without the double s

wintry quarry
#

Spell the word correctly 😉

astral basin
#

alr thank you

dark hatch
#

the onmouseover function should be on your item slots. so when mouse is over them, you can enable the tooltip, and otherwise keep it disabled using OnMouseExit()

cinder spruce
#

ok, i'll try this one too

#

thx

dark hatch
#

is it required in your case, because onMouseExit and OnMouseEnter seems simpler

quaint anchor
dark hatch
#

can you post the error in ss

quaint anchor
#

what error

true delta
#

Question, does anyone can explain the concept on how to make the player move with one of the 4 platforms? The whole Object is just 1 Element with 4 colliders that can be triggered and i simply rotate it from the origin, but sadly it's not as easy to move the player with it as having just a moving plattform going from spot A to B. (Or i'm just dumb)
Can i work something out, do i've to implement that into my PlayerMovement class or into my Rotationclass that triggers when player enters the trigger or do i have to change the whole object that rotates and structure it differently?

quaint anchor
#

this is the only error i get

#

its not stopping from compiling and running, its just not playing the animation as intended

dark hatch
#

maybe it's an int?

quaint anchor
#

wdym ?

wintry quarry
#

Why subject yourself to that?

dark hatch
quaint anchor
#

how would it be an integer

dark hatch
#

click the dropdown to create a trigger. maybe you clicked the int option instead of float.

quaint anchor
#

would i be able to check if animstate is an int ?

#

since it connects to these 4

#

im like 99% sure its a float

scenic saffron
dark hatch
quaint anchor
scenic saffron
dark hatch
quaint anchor
#

is there no setint function for the animator ?

#

to change this line

rare basin
polar acorn
# quaint anchor

Possible ideas:

  • The parameter name might have whitespace, could be named for example AnimState
  • Parameter might not be float
  • Your code might be attempting to change the parameter of a different animator than you think.

Let's start by showing your parameters panel and retyping that parameter name to make sure it's not 1 or 2

rare basin
#

you cannot call MoveBlackHole(); that function needs a paraemeter

dark hatch
#

SetInteger()

#

that's it

scenic saffron
#

whats an ide

dark hatch
polar acorn
#

Ah, I spent too long typing, looks like the problem was solved

quaint anchor
#

ah right

#

but if i set integer then that doesnt work

#

okay

dark hatch
quaint anchor
#

no just negative numbers to determine whether facing right or left

dark hatch
#

you could use mathf.round to just round it up

polar acorn
scenic saffron
#

ok

quaint anchor
#

still gives the same error

#

cannot convert float to int

dark hatch
#

i mean

polar acorn
dark hatch
#

Mathf.RoundToInt()

old heath
#

!code

eternal falconBOT
dark hatch
#

i just gave short form

wintry quarry
#

That's not the same error!

quaint anchor
#

okay let me try that

#

okay well the error is gone but the animation still isnt playing

dark hatch
#

i gtg

quaint anchor
#

alright

scenic saffron
rare basin
#

you should configure your ide

#

and do basic c#/unity course

polar acorn
old heath
#

Ok, current issues with my enemy AI script: the AI is stuck on the hunt mode, AI movement does not abide by the speed and other movement values in the Nav Mesh Agent component. Script: https://hastebin.com/share/didaheqali.csharp

wintry quarry
quaint anchor
#

Im getting this error with my animations now, i have set up the conditions for anim state to change when its equal to 40 which it does, but it only repeats the first frame of the animation

cinder spruce
wintry quarry
# cinder spruce

If you're using UI you can't use OnMouseEnter. You have to use IPointerEnterHandler/IPointerExitHandler

#

you definitely don't put colliders on UI elements.

scenic saffron
#

ohhhhhhhhh, my dumbass misspelled gameObject

cinder spruce
wintry quarry
polar acorn
polar acorn
quaint anchor
#

the idle to run

#

ah wait.

#

i fixed it

polar acorn
quaint anchor
#

yeah its because the run to idle was set to not equals 2

#

i had to update it to 40

#

do you know how id go about getting the animation to play for when im running left ?

#

currently its only when the condition is 40 which would be for moving right, but AnimState can enter -40 to indicate moving left

cinder spruce
wintry quarry
#

You showed an Update function which doesn't seem all that relevant

#

how are you showing/hiding the tooltip

#

and show the inspector(s) of the objects involved, including the tooltip UI

cinder spruce
# wintry quarry you'd have to show how everything is set up
 public void OnPointerClick(PointerEventData pointerEventData)
 {
     UseItem();
 }

 public void OnPointerEnter(PointerEventData pointerEventData)
 {
     if (!empty)
     {
         tooltipBackground.SetActive(true);
         infoText.text = type + "\n" + description;
     }
 }

 public void OnPointerExit(PointerEventData pointerEventData)
 {
     tooltipBackground.SetActive(false);
 }
#

This is the code which shows and hides the tool tip

wintry quarry
#

Right so this absolutely sounds like the tooltip is blocking the raycast

#

So can you show the inspector of your tooltip?

#

BTW the issue is that it rapidly turns the tooltip on and off, yes?

cinder spruce
#

yes

wintry quarry
#

ok and does this have any child objects?

cinder spruce
#

yes, textmeshpro

wintry quarry
#

Ok turn raycast target off on that as well

cinder spruce
#

it doesn't have a raycast box

wintry quarry
#

it does

#

check under extra settings

cinder spruce
#

So it's raycast issue huh? First time running into it

wintry quarry
#

Do you understand why that worked?

#

And why that was causing an issue?

cinder spruce
#

When raycast target box is checked, mouse cursor recognizes it as an interactable object, something like that i guess

wintry quarry
#

Yes which leads to...

When you showed the tooltip, the event system was detecting the tooltip as the thing your mouse was over. This meant your inventory slot was no longer being detected and so it was calling OnPointerExit. That turned off the tooltip which means that the slot was once again detected, and it called OnPointerEnter. And it goes back and forth like this forever.

cinder spruce
#

thx for the help and the info again

hidden sleet
#

I think I'm confusing myself with how quaternions and eulers work here, I just want the camera to rotate 90 degrees each way when the button is pressed, but at a certain point it just chooses to do a full 270 degree turn. Why is that? ```cs
public float rotationDuration;
public AnimationCurve rotateCurve;
public void RotateRight()
{
StartCoroutine(SmoothRotate(90, 0));
}

public void Rotateleft()
{
    StartCoroutine(SmoothRotate(-90, 0));
}

private IEnumerator SmoothRotate(float yangleToRotateBy, float xangleToRotateBy)
{
    
    Quaternion initialRot = transform.rotation;
    Quaternion targetRot = Quaternion.Euler(initialRot.eulerAngles + new Vector3(xangleToRotateBy, yangleToRotateBy, 0));        

    float timer = 0f;
    
    while (timer < rotationDuration)
    {
        
        timer += Time.deltaTime;        

        float t = Mathf.Clamp01(timer / rotationDuration);
        transform.rotation = Quaternion.Euler(Vector3.Lerp(initialRot.eulerAngles, targetRot.eulerAngles, rotateCurve.Evaluate(t)));
        
                    
        yield return null;
    }        
    transform.rotation = targetRot;

    
}
wintry quarry
#
Quaternion targetRot = initialRot * Quaternion.Euler(xangleToRotateBy, yangleToRotateBy, 0));```
hidden sleet
#

was just the only way I understood how they work

wintry quarry
#

And again here:

transform.rotation = Quaternion.Euler(Vector3.Lerp(initialRot.eulerAngles, targetRot.eulerAngles, rotateCurve.Evaluate(t)))```
#

You are overcomplicating this with .eulerAngles and making it not work well

#

Just do:

transform.rotation = Quaternion.Slerp(initialRot, targetRot, rotateCurve.Evaluate(t)));```
wintry quarry
hidden sleet
#

ah, i see

#

and what is slerp compared to lerp?

wintry quarry
#

Slerp is spherical interpolation

#

it's used for rotating directions

#

Lerp is for linear motion

#

A good visual explanation:

hidden sleet
#

ah okay, that's good to keep in mind

#

and yeah, the rotation is working now. I didn't really know about the multiplication aspect

wintry quarry
#

your problem was trying to do Lerp with euler angles

#

that doesn't account for things like 270 -> 0

#

It's one of the many reasons euler angles are often a bad way to deal with things

hidden sleet
#

although it's got an issue which I've tried to resolve in other projects, but haven't figured it out yet. If I press the button while it's making a rotation, it jumps there and starts the next one. What could I do considering it's a coroutine at the moment to have it start the next rotation from where it as and not make that jump?

wintry quarry
#

do you want to disable the ability to rrotate until it's done?

#

Or do you want it to continue smoothly rotating to the next one from its current position

hidden sleet
#

To the next one if possible

wintry quarry
#

You should cancel/stop the current coroutine and start the new one

hidden sleet
#

didn't know you could cancel them

#

do you have to know one is running before you do?

wintry quarry
hidden sleet
#

if one isn't running when stop is called, would that throw up an error?

wintry quarry
#

I think it's safe to pass null into StopCoroutine

#

you have to pass the coroutine into the function

summer stump
frosty lantern
#

hey can I get some help with my chess logic?

hidden sleet
#

saying that the coroutine is null when I call stop, trouble is I've got some parameters to pass in

frosty lantern
#

only my white pieces are able to capture,

and the pieces don't necessarily move when I tell them to

wintry quarry
#

there is sample code

#

example:

// start:
Coroutine c = StartCoroutine(MyCoroutine(params));
// stop:
StopCoroutine(c);```
hidden sleet
#

Yeah I looked at the example, since they are only ever going to pass in 3 seconds they can define it and stop it in update, but since the parameters will contain the angle to rotate at, wouldn't I need a separate IEnumator for each possible kind of rotation?```cs
public void RotateRight()
{
rotateCoroutine = SmoothRotate(90, 0);
StopCoroutine(rotateCoroutine);

    StartCoroutine(rotateCoroutine);
}

public void Rotateleft()
{
    rotateCoroutine = SmoothRotate(-90, 0);
    StopCoroutine(rotateCoroutine);


    StartCoroutine(rotateCoroutine);
}
wintry quarry
#

you need to stop the previous coroutine

#

not the new one

#

I would recommend using a Coroutine variable instead of an IEnumerator

#

then you can do:

public void RotateRight()
{
  StopCoroutine(rotateCoroutine);
  rotateCoroutine = StartCoroutine(SmoothRotate(90, 0));
}```
#

if you want to use IEnumerator you have to do:

public void RotateRight()
{
  StopCoroutine(rotateCoroutine); // stop the OLD one
  rotateCoroutine = SmoothRotate(90, 0);
  StartCoroutine(rotateCoroutine);
}```
rugged gulch
#

Does anyone know what I can do to prevent this? I added a few model packs to an empty unity project and tried to commit to Github, with LFS enabled and currently LFS has 0 out of 2gb used on my account, with the latest .gitignore file as well.

hidden sleet
#

had that before, but It ended up throwing up errors

wintry quarry
hidden sleet
#

Had this before, stopping the previous coroutine, then making the next one.

public void RotateRight()
    {
        StopCoroutine(rotateCoroutine);

        rotateCoroutine = SmoothRotate(90, 0);
        StartCoroutine(rotateCoroutine);
    }

    public void Rotateleft()
    {

        StopCoroutine(rotateCoroutine);    

        rotateCoroutine = SmoothRotate(-90, 0);
        StartCoroutine(rotateCoroutine);
    }

And then ```NullReferenceException: routine is null
UnityEngine.MonoBehaviour.StopCoroutine (System.Collections.IEnumerator routine) (at <30adf90198bc4c4b83910c6fb1877998>:0)
RotateCamera.RotateRight () (at Assets/RotateCamera.cs:17)

wintry quarry
#

Just do cs if (rotateCoroutine != null) StopCoroutine(rotateCoroutine);

hidden sleet
#

Lookin good! Although now it can end up out of those 90 degree points I want it to rotate to, i can see why, but I'll have to fix that next

wintry quarry
#

and use that as the basis for generating the next rotation

#

rather than transform.rotation

hidden sleet
#

Sort of got there, it jumps to that next point again but I can fix that

frosty lantern
#

my piece moving logic isn't stopping on my own pieces

#

white pawns are the only pieces that I coulg get to capture

hidden sleet
#

ay it works! Thanks Praetor

frosty lantern
#

and other pieces don't move

rigid valve
#

when I tap play it gets this weird view

#

anyone knows why?

deft grail
#

and what does the camera preview show

rigid valve
#

on top of capsule

#

actually when I zoom to see my capsule the terrain becomes invisible

deft grail
rigid valve
wintry quarry
wintry quarry
#

Press F or double click it in the hierarchy to zoom in

#

Just looks like your camera is underneath the ground to me

rigid valve
#

evrything fine till this point if I zoom further

#

this happens

wintry quarry
#

Yeah because that object is underneath the ground

rigid valve
wintry quarry
#

Under the ground

rigid valve
#

I seee

#

ty

whole idol
#

why does it fail to transition to the next scene

#

which is a credits scene

deft grail
whole idol
#

yes

#

it has no receiver

#

how do i give a receiver?

deep quarry
#

Trying to make a Player movement, but I'm getting stuck on the mouse rotation.
This is my CameraMovement.cs script:

    void Update()
    {
        mouseX = sensitivity * Input.GetAxisRaw("Mouse X");

        orientation.transform.eulerAngles += new Vector3(0f, mouseX, 0f);
        transform.eulerAngles = orientation.eulerAngles;
        transform.position = orientation.position;
        Debug.Log($"{orientation.eulerAngles.y} | {mouseX}");
    }

and this is my PlayerMovement.cs script:

    void Update()
    {
        MyInput();
    }

    void FixedUpdate() 
    {
        Movement();
    }

    void MyInput()
    {
        vertical = Input.GetAxisRaw("Vertical");
        horizontal = Input.GetAxisRaw("Horizontal"); 

        moveDir = transform.forward * vertical + transform.right * horizontal;
    }

    void Movement()
    {
        rb.AddForce(moveDir.normalized * moveSpeed);
        transform.eulerAngles = orientation.eulerAngles;
    }

However, when I look around it continue rotate, even though I don't move the mouse. How do I fix this?

frosty lantern
wintry quarry
frosty lantern
#

I'm having a few issues: only my pawns can move forward reliably, the knights, horses, king, bishop and rook are finnicky (they do work on occasion and not on others and I can't make heads or tails of what to debug)

I've stopped getting nullreference errors for my game manager implementation

My dark pawns like to overlap the white pawns instead of capture, even though my whit pawns capture normally.

The white long range pieces are ignoring the pieces around them in the checks for valid moves and I don't know how to fix that

  • BitBoard

https://gdl.space/isimasorud.cpp

  • BoardCoord

https://gdl.space/jedeginapu.cs

  • GameManager

https://gdl.space/wojuqizito.cs

  • ChessPiece

https://gdl.space/ivuluxujuq.cs

  • Piece Setup

https://gdl.space/usanovusup.cs

whole narwhal
#

Need some help. I'm trying to lock constraints (2d) in my c# code but it's unlocking my z-rotation constraints when I don't want it to

eternal falconBOT
deft grail
#

literally told you how to paste code right there

#

and if it doesnt let you use a website, then make a better picture at least

modest dust
# whole narwhal

RigidbodyConstraints2D are flags, and you're overriding them with RigidbodyConstraints2D.FreezePosition

#

If you want to add new constraints to your original ones then do rb2D.constraints = rb2D.constraints | RigidbodyConstraints2D.FreezePosition

#

If you want to remove constraints from your original ones then do rb2D.constraints = rb2D.constraints & ~RigidbodyConstraints2D.FreezePosition

#

Can be shortened to:

  1. Adding: rb2D.constraints |= RigidbodyConstraints2D.FreezePosition
  2. Removing: rb2D.constraints &= ~RigidbodyConstraints2D.FreezePosition
polar acorn
dusk minnow
#

so i wanna instantiate a ui element, but somehoiw the scale is always 8.some times the scale i want; e.g. prefab scale is 1 obj scale is 8: Transform obj = Instantiate(playerUIElement, childStartPosition.position, Quaternion.identity).transform; in the picture i set the localScale to 10

hidden sleet
#

I've been trying to work on a smooth camera rotation some more, when you press a button it rotates 90 degrees correctly, but trying to add pitch has been a pain. I had a way to track the old yaw rotation, but now that I've introduced pitch it's complicated things. Is this approach at all right?

private IEnumerator SmoothRotate(float yangleToRotateBy, BuildCameraPosState cameraState)
    {
        Quaternion lastTarget = targetRotation;

        Quaternion lastPitchTarget = pitchTargetRotation;
        Quaternion lastPitchRot = curentPitchRotation;

        Quaternion lastYawTarget = yawTargetRotation;
        Quaternion lastYawRot = curentYawRotation;
    
        Quaternion pitchTarget;
        Quaternion yawTarget;
        Quaternion lastCombinedRot = lastYawRot * lastPitchRot;
        Quaternion lastCombinedTargetRot = lastYawTarget * lastPitchTarget;
            
        switch (cameraState)
        {
            case BuildCameraPosState.SideView:
                pitchTarget = Quaternion.Euler(0, 0, 0);

                break;
            case BuildCameraPosState.TopView:
                pitchTarget = Quaternion.Euler(30, 0, 0);
                break;
            case BuildCameraPosState.LowView:
                pitchTarget = Quaternion.Euler(-20, 0, 0);
                break;
            default:
                pitchTarget = Quaternion.Euler(0, 0, 0);
                break;
        }
        pitchTargetRotation = pitchTarget;


        yawTarget = lastYawTarget * Quaternion.Euler(0, yangleToRotateBy, 0);
        yawTargetRotation = yawTarget;

        Quaternion combinedTarget = yawTarget * pitchTarget;
        targetRotation = combinedTarget;

        float timer = 0f;

        while (timer < rotationDuration)
        {

            timer += Time.deltaTime;

            float t = Mathf.Clamp01(timer / rotationDuration);

            transform.rotation = Quaternion.Slerp(lastYawRot * lastPitchRot, yawTarget * pitchTarget, rotateCurve.Evaluate(t));
            curentYawRotation = transform.rotation
            yield return null;
        }
        transform.rotation = yawTarget;

    }
``` it's all becoming rather hard to follow
dusk minnow
#

!code

eternal falconBOT
polar acorn
polar acorn
flint temple
#

Hey yall, what is the external link for posting large amounts of code for people to see? i forgot

willow scroll
eternal falconBOT
willow scroll
#

Oh, it wasn't supposed to be sent. I thought it doesn't work with inline code blocks.

bitter walrus
#

No error, just doesn’t work

frosty lantern
cosmic dagger
# bitter walrus

make sure both objects are set up correctly to trigger the collision . . .

bitter walrus
#

Yes

bitter walrus
cosmic dagger
#

nope, the trigger object should have the script on it . . .

#

and at least one GameObject must have a rigidbody . . .

#

you can simply place a log in the trigger method instead of calling another method with a log . . .

bitter walrus
cosmic dagger
#

don't think what is?

bitter walrus
#

Still doesn’t work

bitter walrus
cosmic dagger
#

show how both objects are setup . . .

polar acorn
bitter walrus
polar acorn
# bitter walrus

The Three Commandments of OnTriggerEnter:

  1. Thou Shalt have a 3D Collider on each object
  2. Thou Shalt tick isTrigger on at least one of them
  3. Thou Shalt have a 3D Rigidbody on at least one of them
bitter walrus
#

I cant use it to send screenshots

cosmic dagger
bitter walrus
#

I over complicated it lol

cosmic dagger
bitter walrus
#

Shit is still not working

cosmic dagger
# bitter walrus

you need to look at the method name carefully. you misspelled it . . .

bitter walrus
#

Yup

cosmic dagger
#

stop rushing and take your time. every line and word is important . . .

trail chasm
#

hello i have got a wierd behaviour when i run my game on the editor the game run normaly but whene i build it it give me error at runtime why ? error : CollisionMeshData couldn't be created because the mesh has been marked as non-accessible. Mesh asset path "" Mesh name "Cube"

bitter walrus
#

On a rush

summer stump
cosmic dagger
# bitter walrus On a rush

and making these small errors will only impede you from completing, such as the 3d/2d debacle and this current, simple spelling error . . .

summer stump
bitter walrus
#

Found it

#

Still doesn’t work

bitter walrus
#

There code is exactly the same as mine

#

Their

summer stump
trail chasm
#

hello i have got a wierd behaviour when i run my game on the editor the game run normaly but whene i build it it give me error at runtime why ? error : CollisionMeshData couldn't be created because the mesh has been marked as non-accessible. Mesh asset path "" Mesh name "Cube"

bitter walrus
#

Hiw do I know my “type”

#

How

frosty lantern
hollow dawn
#

I need help. so I'm making a mobile game and I have added a joystick with some coding I found on YouTube. this error keeps popping up and I don't know how to fix it can someone help me. im a beginner btw

hidden sleet
#

I've got a bit of an issue with the camera rotation script again, i've made a separate object that will have methods to rotate it up and down, with it's parent handling yaw. The yaw has a method that will rotate it around to move to 4 different spots around the centre, which works. ```cs
private IEnumerator SmoothYawRotate(float yangleToRotateBy)
{
Quaternion lastTarget = yawTargetRotation;
Quaternion lastRot = curentYawRotation;

    Quaternion targetRot = lastTarget * Quaternion.Euler(0, yangleToRotateBy, 0);
    yawTargetRotation = targetRot;

    float timer = 0f;

    while (timer < rotationDuration)
    {

        timer += Time.deltaTime;

        float t = Mathf.Clamp01(timer / rotationDuration);

        transform.rotation = Quaternion.Slerp(lastRot, targetRot, rotateCurve.Evaluate(t));
        curentYawRotation = transform.rotation;
        yield return null;
    }
    transform.rotation = targetRot;


}

But the pitch one is acting up a bit. if I rotate one to the right, the yaw game object has it's rotation changed properly. but I press right then down soon enough after each other, it teleports and the pitch gains the yaw of the parent, which isn't intentional as I want them both separated.cs

private IEnumerator SmoothPitchRotate(BuildCameraPosState cameraState)
{
Quaternion lastTarget = pitchTargetRotation;
Quaternion lastRot = curentPitchRotation;

    Quaternion pitchTargetRot;
    switch (cameraState)
    {
        case BuildCameraPosState.SideView:
            pitchTargetRot = Quaternion.Euler(0, 0, 0);

            break;
        case BuildCameraPosState.TopView:
            pitchTargetRot = Quaternion.Euler(30, 0, 0);
            break;
        case BuildCameraPosState.LowView:
            pitchTargetRot = Quaternion.Euler(-20, 0, 0);
            break;
        default:
            pitchTargetRot = Quaternion.Euler(0, 0, 0);
            break;
    }

    Quaternion targetRot = pitchTargetRot;        
    pitchTargetRotation = targetRot;

    float timer = 0f;

    while (timer < rotationDuration)
    {

        timer += Time.deltaTime;

        float t = Mathf.Clamp01(timer / rotationDuration);

        transform.rotation = Quaternion.Slerp(lastRot, targetRot, rotateCurve.Evaluate(t));
        curentPitchRotation = transform.rotation;
        yield return null;
    }
    transform.rotation = targetRot;
#

Not entierly sure why it suddenly takes on that value when I never reference the parent at all

hollow dawn
#

I need help. so I'm making a mobile game and I have added a joystick with some coding I found on YouTube. this error keeps popping up and I don't know how to fix it can someone help me. im a beginner btw

cosmic dagger
cosmic dagger
#

make sure you understand what is a class and how to declare variables in c# . . .

eternal falconBOT
polar acorn
#

Configure your IDE so you get auto-complete and intellisense to avoid making syntax errors

cosmic dagger
hollow dawn
#

idk what a class scope is

cosmic dagger
summer stump
#

A { } is a scope, to keep it simple

cosmic dagger
#

it's hard to help if you don't understand the help given . . .

hollow dawn
#

😦 time to learn

swift crag
#

The simplest possible class declaration is...

class MyClass { }

In this case, the class body -- { } -- is completely empty.

#

you generally want to actually put things into your class

#
class MyClass {
  public int myIntField;
  public void SomeMethod(int florp) {
    Debug.Log(florp);
  }
}
#

This declares two members inside of the class: a field and a method

swift crag
#

see what the compiler says (:

#

i see an error.

summer stump
cosmic dagger
hollow dawn
swift crag
summer stump
cinder crag
#

okay some im having a brain fart atm , rn im working on the save and load system but since i have a CharacterStats script and a PlayerStats which im just overriding some stuff from CharacterStats but i have the health and maxHealth variables only in CharacterStats script and i wanna only save the players health cause im only overriding a void from CharacterStats script and PlayerStats is a subclass of CharacterStats , how could i go on about and only save the players health and not have to get it from the CharacterStats script and well save only the players health n stuff

swift crag
#

unsurprisingly, the GPU did not understand that a member cannot have the same name as the enclosing type

cinder crag
#

they are idk maybe the same possibly

swift crag
#

that is a problem, yes, but the member declarations have been jammed between most of the class declaration and the class body

#

that is a larger issue

cinder crag
#

oh goddamn didnt saw 😭

#

and also shouldnt the CharacterController be like that greenish color

swift crag
#

the IDE was not configured, yes

#

Visual Studio will display "Miscellaneous Files" up there if it doesn't understand which assembly the file belongs to

cinder crag
#

thats a problem lol

swift crag
#

visual studio code is less obvious, although it will generally show "Projects: 0" (or nothing at all)

#

(that's a lot of assemblies...)

cinder crag
#

good lord

#

115

#

kinda obv you cant have a variable the same name as ur class name lol

cinder crag
swift crag
#

JsonUtility?

cinder crag
#

yeah thats how

swift crag
#

that should serialize the fields from the parent class just fine

#

maybe i don't understand your problem

#

oh, CharacterStats is a MonoBehaviour

#

i'll need to see the actual serialization code

cinder crag
#

from the SaveAndLoad script?

swift crag
#

yes

cinder crag
#

dont have anything atm

#

i just wanna save the players health and max health but those varibales are in CharacterStats script

#

PlayerStats is a subclass of CharacterStats

flat slate
#

its the 6th parameter from below

cinder crag
hollow dawn
#

What does this mean?

wintry quarry
#

on line 20 of joystick.cs

languid spire
flat slate
flat slate
wintry quarry
flat slate
#

okay wait

languid spire
flat slate
#

this is the whole cocde

polar acorn
wintry quarry
#

You shouldn't add "cs``" to it for no reason

#

that's only for formatting within discord itself

flat slate
#

okay

wintry quarry
#

(it's also not correct. The correct thing is:)
```cs
// code here
```

#
print("Like this");```
flat slate
#

okay

#

but do u know what the problem is?

wintry quarry
#

Your code is overcomplicated

#

so it's hard to tell exactly

#

I would recommend learning to use arrays and structs, which will make this code a lot simpler

#

also coroutines

flat slate
#

the problem is in this section i ques: (xpvisual = CurrentXP; float currentXp = Mathf.SmoothDamp(Fortschritt.value, xpvisual, ref velocity, speed * Time.deltaTime); Fortschritt.maxValue = MaxXP; Fortschritt.value = currentXp; text.text = CurrentXP + "/" + MaxXP; if (Mathf.Abs(currentXp - xpvisual) < 0.001f) { CheckLevelUP(); })

#

but the velocity goes crazy when the XPVisual is greater than MaxXP

vital bridge
#

any way to simplify this? i just need to update the y coordinate transform.position = new Vector3(transform.position.x, a.y, transform.position.z);

wintry quarry
#

that's more efficient at least

flat slate
hollow dawn
#

i copied the code from a youtube video and he didnt have any trouble

faint osprey
#

i just got my unity stuck in an infinite loop because I forgot a yield return null what do i do now

wintry quarry
#

your IDE is not configured and I can't help you until it is

hollow dawn
wintry quarry
#

!ide

eternal falconBOT
wintry quarry
#

Follow the guide^

hollow dawn
#

which one shall i click

wintry quarry
#

The one that matches your situation

#

Probably Visual Studio installed manually

faint osprey
cosmic dagger
#

if you didn't save before, then yup . . .

hollow dawn
wintry quarry
#

of course

#

why wouldn't you follow the whole thing

cosmic dagger
#

why follow half or only some of it? that would be incomplete . . .

hollow dawn
# wintry quarry Yes

in the unity documentation section I don't have unity API Reference how do I get it?

hollow dawn
#

im doing them

wintry quarry
#

oh - no you don't need this part

#

just go back to VS

#

and see if it's working now

#

See if you're getting atuocomplete and error highlighting etc

#

I thought you were asking if you needed to do the whole Getting Started part

hollow dawn
#

doesnt work

rich egret
#

how to remove it?

cinder crag
#

why would you remove it

#

its useful

wintry quarry
#

but it's very nice

hollow dawn
wintry quarry
#

IDK why you'd want to get rid of it

rich egret
wintry quarry
wintry quarry
cinder crag
#

love it

hollow dawn
#

how do i get rid of these errors?

#

when the guy on youtube did it. it was working fine for him

wintry quarry
cinder crag
wintry quarry
#

See how you're missing a reference

hollow dawn
#

do i have to assain the reference in the inspector?

cinder crag
#

lmao

wintry quarry
cinder crag
#

yes-

wintry quarry
hollow dawn
# wintry quarry What did the tutorial person do?

#fpsshooter #fpsgame #unity3d #joystick
In this beginner unity tutorial we will show how to have a Fps Touch Control with Joystick Asset in fps game
Unity Fps Touch Control are most commonly used in first-person mobile games
Create your own game in 8 minutes

Down...

▶ Play video
wintry quarry
#

Do what they did. (although it's possible they just skipped showing it, which is very annoying)

wintry quarry
#

you skipped that

#

Don't skip things

hollow dawn
#

bro i did all of this work just for the joystick not to work

summer stump
cinder crag
#

true

#

if ur following a tutorial be sure to follow it

polar acorn
hollow dawn
#

😭

languid spire
#

that's probably only one tenth of the true number, if that

polar acorn
#

These are just the ones I've been online and active to see

cinder crag
#

jesus christ

#

from 2022 as well

hollow dawn
#

now I got rid of the errors how do I get the analog working? I followed the code this time and fixed any errors but still doesn't work

flat slate
#

just completely restart i would say

hollow dawn
hushed light
#

Could someone link me in with a video I should start with on making a main menu, I watched a phew last night and worked on it a little but ran into some errors I couldn't sort out "not home atm but can post photos of said error inna phew"

lost anvil
#

Whats the point of using this in code? ive seen people use it like this.variable

polar acorn
#

For example:

private float x;
private void SomeFunction(float x){
  this.x = x;
}
sour iron
#

Hi! I'm making a game to teach about the states of water to people with intellectual disabilities as a college project. The game is very simple and has a point and click system (some things about the project are in Portuguese). There's a text saying "Clique no lugar onde o vapor está saindo" (Click on the place where the steam is coming out), and the person needs to click on the pan. After that, there will be another text saying "Clique no lugar que contém líquido" (Click on the place that contains liquid) and you need to click on the juice, and another one will appear saying "Clique no objeto sólido" (Click on the solid object) and you need to click on the ice, then an arrow will appear to take you to the next phase. But I can't make the text dissapear when you click on the pan. There was supposed to be a message on the console saying the name of the object you clicked but that doesn't appear too so I suppose the object isn't being detected

#

Also the Input Handler and PlayerInput just in case

slender nymph
#

you need to get your !IDE configured

eternal falconBOT
slender nymph
#

also i recommend using the event system interfaces like the IPointerDownHandler rather than manually raycasting against the objects on your canvas (which really shouldn't have any type of physics, even colliders)

#

also you've shown a sprite renderer that is not on a canvas in your first screenshot, but you are specifically checking if the object detected by the raycast is a child of a canvas so naturally that object would not fit that criteria

sour iron
slender nymph
#

well first you need to decide if the objects are even going to be on the canvas or not

sour iron
#

No, they're not supposed to be on the canvas

slender nymph
#

then you need to put a physics raycaster 2d on your camera, then either an EventTrigger component or some component that you write that implements the IPointerDownHandler interface

#

and that's basically all you need to do in order to detect clicks on an object in the scene (those objects will need colliders too, but you've seemingly already got that)

sour iron
sour iron
#

Should I reference the InputHandler on the object? atwhatcost

slender nymph
#

you don't need the input handler. you just need to have a component that will run whatever code you wanted to happen on click in some public method. then you just call that method from this event

sour iron
#

You mean I don't need the InputHandler on the camera or I don't need it at all?

slender nymph
#

you don't need it at all. you don't need to manually detect clicks and then raycast from that. the Event System, Physics Raycaster, and the EventTrigger do all that for you

sour iron
#

Oh, I see

slender nymph
#

all you need is the code you wanted to run in response to an object being clicked on, and that code should be called by the event

sour iron
#

Wait but the code needs to be on an object, right?

slender nymph
#

yes

sour iron
#

Then should I create just an empty object in the scene with the script?

#

Cause I don't need the PlayerInput then

#

If I got it right

slender nymph
#

it depends on what you actually want to do in response to the clicking

sour iron
#

I just want to hide the text contained in the object cliked and make another one appear

slender nymph
#

because you could give each of the clickable objects a component that does something in response to being clicked

sour iron
#

Well, you need to click on the right object so for now nothing happens if you click on the wrong one

#

If you're free, I can share my screen on a VC, I think that's easier than just explaining by text

slender nymph
#

i will not be joining voice chat or participating in any screenshare. you are free to explain what you are trying to do here

sour iron
#

I still don't get how to make it work thought

#

Sorry I asked for help in VC, you sounded really offended

summer stump
#

Just straightforward, which is a good thing imo

sour iron
craggy swift
#

Does anyone know how to help him resolve this?

cosmic dagger
craggy swift
slender nymph
#

they also haven't actually said anything about what they are specifically having trouble with

sour iron
slender nymph
#

i feel like you didn't pay any attention to anything i told you except to put the EventTrigger on the object . . .

#

and keep in mind, i wasn't planning on writing the code for you. you need to actually do it yourself

sour iron
#

I'm sorry? I just didn't understand exactly what to do? If you don't have time to explain, that's okay. I don't want to be a burden either, I just didn't get it

slender nymph
#

i already explained what you need to do

sour iron
#

Okay, if I put the object with the script in the camera what function do I call?

keen owl
#

@rich adder
Unloading the last loaded scene Assets/C# Scripts/InfiniteRun/InfiniteRunMenu.unity(build index: 2), is not supported. Please use SceneManager.LoadScene()/EditorSceneManager.OpenScene() to switch to another scene.
UnityEngine.SceneManagement.SceneManager:UnloadSceneAsync (string)
Puzzle2D.UI.Menu/<UnloadScene>d__8:MoveNext () (at Assets/C# Scripts/UI/Menu.cs:70)
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
Puzzle2D.UI.Menu:OnInfiniteRunButton () (at Assets/C# Scripts/UI/Menu.cs:41)
UnityEngine.EventSystems.EventSystem:Update ()

summer stump
slender nymph
#

yeah you gotta have at least one scene loaded and active at any given time

keen owl
#

oh i see, so basically if i toggle between scenes I can't have multiple loaded at the same time?

slender nymph
#

if you want to manually manage unloading and loading of scenes, you typically want some other temporary scene to load and activate before unloading the previous scene

slender nymph
summer stump
slender nymph
#

you just can't have no scenes loaded

#

don't crosspost

keen owl
#

StartCoroutine(UnloadScene("InfiniteRunMenu")); // Unload InfiniteRunMenu
StartCoroutine(LoadSceneAsync("InfiniteRun"));

this is in the same function that loads the scene. should i not unload it within that function?

summer stump
#

Directing others to a channel is considered cross-posting

slender nymph
#

crossposting includes posting in an unrelated channel to redirect others to the channel your question was posted in

keen owl
#

oh ight thanks lol

polar acorn
slender nymph
#

or load an intermediary, unload old scene, load new scene, then unload intermediary scene. this is how a lot of load screens work

polar acorn
hushed light
#

can ayone help me out here im somewhat new and cant seem to figure this out lol here is my errors and this is the script its reffering to using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour
{
//Load scene
public void Play()
}
SceneManager.LoadScene(SceneManager.GetActiveScene().BuildIndex + 1);
}

//Quit Game
public void Quit()
{
    Application.Quit()
    Debug.Log("Player Has Quit The Game");
}

}

rocky lichen
polar acorn
hushed light
slender nymph
eternal falconBOT
hushed light
hushed light
rocky lichen
hushed light
polar acorn
hushed light
slender nymph
#

close visual studio, regenerate project files, then open it again by double clicking a script in your project window

topaz rain
#

Oh shiet

#

srry guys

#

xD

hallow acorn
#

haha no worries can happen xd

topaz rain
#

Unreal is getting me mad

#

cant wait to return to my beloved simple and usefull unity T-T

wicked cairn
slender nymph
#

it won't stop the code. the log will still print

wicked cairn
#

Oh so it’s only for scene changing

slender nymph
#

no, even that would still work

wicked cairn
#

It won’t

slender nymph
#

it will. scene load does not begin until the end of the frame

wicked cairn
#

If you have scene change code, anything after that won’t run

slender nymph
#

incorrect

wicked cairn
#

Correct

#

Try it

slender nymph
#

i can't at the moment. but you could try it and see that i'm right

wicked cairn
#

A lot of people ask why their data won’t save and stuff, and when they show the code they put it right under the scene change line

slender nymph
polar acorn
hallow acorn
#

sorry for interrupting you guys but I was wondering bc many people said i should leave the rigidbody.addforce method and switch to velocity. but i dont want to get teleported instantly to my jump height, so how do i implement a smooth jump? should i do it with a curve like how i would write a camera follow script? so the movement gets smoothed out?

polar acorn
hallow acorn
wicked cairn
slender nymph
#

and that can easily be remedied by manually calling PlayerPrefs.Save

wicked cairn
#

attempted. works before scene change

#

I always use .Save, great for being able to load the data right after

polar acorn
hushed light
#

ok im this far do i just do as it says pretty much?

gusty dome
#

does anyone know if i can use layers in a similar way to comparetag

polar acorn
polar acorn
gusty dome
#

any idea how i could figure out a way to make this work layers instead then?

hushed light
#

would i be better off to use this SceneManager.LoadScene("In Game"); rather than this SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

polar acorn
hushed light
#

so its a main menu, this would be for the play button to move to the In Game scene witch would be playing the game, but if i added a loading screen wouldnt it just be for example SceneManager.LoadScene("Loading");if that was the name of said scene

#

this is currnetly how i have it setup and no errors so far, this would be the start/play button and the quit button

#

that worked perfectlyyyyyyy thank you all sm

rocky gale
#

does the new inputsystem mouse delta need to be multiplied by time.deltatime?

short hazel
#

No

polar acorn
rocky gale
#

ok

#

didnt wanna make tbe

#

the brackeys error

grizzled fulcrum
#

So I've been stuck on a code in which I just want to add a limitation to not make the player able to jump middair if he walks off a ledge, because it keeps my "isGrounded" value true. Any clue on how I could do this?

short hazel
#

void OnCollisionExit2D(Collision2D) is the method that gets executed when collision with another collider stops

shy ruin
short hazel
#

They already have the logic set for CollisionEnter

#

But tell it to them, not me

shy ruin
#

Both of ours work I was just saying my opinion

grizzled fulcrum
short hazel
#

Yep, basically a copy-paste + changing Enter to Exit and true to false

grizzled fulcrum
#

Man.

short hazel
#

But it would be better to use a raycast (or another physics query), the collision callbacks have some flaws, for example if you have two ground colliders aside each other, walking across from one to the other might set isGrounded to false forever if the Exit of collider 1 happens after the Enter of collider 2

#

Basically what you have for the left/right detections, but for the ground

unkempt zenith
#

Hi, how can i show my static var in the inspector ??

grizzled fulcrum
polar acorn
grizzled fulcrum
# short hazel Yup

And instead of setting the speeds on the horizontal input and stuff, I just set it for a tag comparing to enable isGrounded when it is colliding against something with the tag "Ground"?

short hazel
#

Wait 2D doesn't use out params? Consistent much
Well you'll have to do it the long way, like you have for the 2 other raycasts. My code won't work

spiral narwhal
#

Is Start, Awake, etc. executed in a unit test?

        [SetUp]
        public void SetUp()
        {
            _gameObject = new();
            _gameObject.AddComponent<GameManager>();
        }
modern smelt
#

Hello everyone , i'm watching a tuto , where the youtuber ask to do this line
"DrawCircle(Vector2.zero,1,Colour.lightBlue);

But my computer dont know what is DrawCircle

#

the method have been change to something else recently ?

#

it is the first thing that do the guy , nothing else have been done before

spiral narwhal
#

Writing it just like that means the method must exist in your script or its parent

modern smelt
#

xD

#

ok thx

spiral narwhal
#

No what I mean is

#

This will tell C#, I have a method "DrawCircle" in my class or parent

#

But if the compiler says you don't, you need to access it from somewhere else

modern smelt
#

yeah but i dont have script named like this , was thinking about this being a unity base method

spiral narwhal
#

I found this, maybe they mean that?

modern smelt
#

so its not

#

maybe the guy just skip the part where he made this function somewhere

#

yeah maybe !

spiral narwhal
#

Definitely need to access it from Gizmos I think

modern smelt
#

thanks for helping

deft grail
#

!code

eternal falconBOT
earnest goblet
#

gotchu gimme a sec

#

i also feel my code is very messy, if you have any ideas on how to maybe make it look better that would be apprechiated

deft grail
earnest goblet
deft grail
#

oh i see

earnest goblet
#

i tried a couple of ideas but they all seemed too artificial

#

characterController.move seemed like a transform rather than a launch

deft grail
#

well with a rigidbody you would AddForce which would make it nice

#

with a CC idk if there is something similar to that?

earnest goblet
#

im not really sure there is

#

the closest equivelant would probably be characterController.move()

deft grail
queen adder
#

heya, having a lot of trouble with a respawning system i made.

sometimes it works fine, the player takes damage and teleports back to the designated respawn point.

but sometimes the player teleports, takes damage, then teleports again, till they eventually teleport back to spawn

eternal falconBOT
queen adder
#

do i save it and then send?

deft grail
queen adder
#

do i then send the link?

deft grail
#

yeah

queen adder
#

the teleport is at the very end of the code

#

whats meant to happen is that when the player falls off the map, they take 1 damage and get teleported back to the start

rocky canyon
# earnest goblet the closest equivelant would probably be characterController.move()

ya, ```cs
finalVector =
(groundVector * initialSpeed) +
(airVector * playerSettings.airSpeed) +
(Vector3.up * gravitySim);

    if(jump.magnitude > playerSettings.jumpMagn)
    {
        finalVector += jump;
    }

    characterController.Move(finalVector * Time.deltaTime);```

i construct a vector before passing it into the Move() function.. for a knockback or something i'd just + knockback.. most of the time it would be 0.. so (having no effect on the move()) but if there was any value there.. it'd just be included in the finalVector..

and then i'd get rid of it.. (lerp it to zero) or set it back to zero until needed again..

#

not exactly a 1:1 comparison to AddForce.. but it can get the job done

queen adder
#

sometimes the player teleports, takes damage, then teleports again, till they eventually teleport back to spawn

#

i can capture a video of it

deft grail
rocky canyon
#

maybe you can use a coroutine.. or an extra conditional. to make sure u've teleported before u take damage

#

or vice-versa

queen adder
#

ive been doing that, ive added a timer to stop the player from taking a ton of damage in the span of like 2 frames

rocky canyon
#

but i'll wait for code to see

violet kestrel
#

Yo

rocky canyon
queen adder
queen adder
rocky canyon
#

ya, but 2 frames.. is only gonna run (2) sets of logics

queen adder
#

i have 10 for the test

violet kestrel
#

I need some tips, im very interested on learning game dev. Some years ago i saw a couple tutorials on how to game a 2d plataformer but i copied line to line so i didnt learn really. I know programming logic and c# basics. I only need a source of where i can really learn unity (YouTube, site, idc)

#

From where you guys started?

rocky canyon
# queen adder

so im guessing u have a fall detection collider down there at the bottom.. and its supposed to set the player back on top?

queen adder
#

nope, not a collider

#

in the code you should be able to see a threshold

rocky canyon
#

well a conditional.. if player.y < x

queen adder
#

ye ye

rocky canyon
#

why not
transform.position = respawnPoint.transform.position;

put this line in the update condition u have?

queen adder
#

it used to happen instantly, so you went back to spawn with like all your health gone.

but i put a timer on it so you can only take damage every 1 second, and now i can see whats happening better

rocky canyon
#

move the player
deal damage

queen adder
#

but if the move isnt working then wouldnt that not do anything?

rocky canyon
#

b/c it would already be moved.. b4 u called damage on it

#

it couldnt therfor call damage twice.. b/c its still below the threshold

#

just a thought expirement really

earnest goblet
queen adder
#

well its weird because it works fin most of the time, it just seams to be that one spot by the corner thats really bad

rocky canyon
#

say.. i also added + additionalForce... it could be 0 when i dont need it..

#

and then i could set it to a value (vector) when i do.. and it would jsut get added in w/ the movement its already making..

earnest goblet
rocky canyon
#

and then the next frame i could set it back to 0 if i didnt need it anymore.. or.. lerp it back to 0.. to smooth it back down to the original inputs/movmenet

rocky canyon
#

same way the += jump works.. thats basically simulating AddForce (transform.up * force);

true knoll
#

I have absolutely no idea why the Rb2d.AddForce isn't working

using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEditor.Experimental.GraphView;
using UnityEditor.UIElements;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public GameObject toastie;
    public Rigidbody2D toastieRb;
    public Transform toastieT;
    public GameObject projectile;
    public Transform shotPoint;
    private float timeBtwShots;
    public float startTimeBtwShots;

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

    public float offset;
    public SpriteRenderer sr;

    public float kbp;

    public float Offset = 90;
    

    // Update is called once per frame
    void Update()
    {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        Vector2 kbd = Camera.main.ScreenToWorldPoint(Input.mousePosition-toastieT.position).normalized*-1;
        float direction = math.atan2(difference.y, difference.x) * Mathf.Rad2Deg + offset;
        transform.rotation = Quaternion.Euler(0f, 0f, direction);
        
        if (direction < 0 && direction > -180)
        {
            transform.localScale = new Vector3(1,1,1);
            
        }
        else
            transform.localScale = new Vector3(-1,1,1);
            
        
        

        if (timeBtwShots <= 0)
        {
            if (Input.GetMouseButtonDown(0)) 
            {
                Instantiate(projectile, shotPoint.position, transform.rotation);
                timeBtwShots = startTimeBtwShots;
                toastieRb.AddForce(kbd*kbp, ForceMode2D.Impulse);
            }
        }
            else {
                timeBtwShots -= Time.deltaTime;
            }

        
    }
}

its supposed to give knockback after the player shoots the gun

please help im going insane

#

ignore my sister xd

true knoll
#

exactly

#

its giving zero knockback

deft grail
#

oh supposed to give knockback ok

queen adder
deft grail
rocky canyon
#

weird.. are there duplicates or anything of that script?

deft grail
#

so thats overwriting the force you give it

true knoll
#

ohhhh

queen adder
rocky canyon
#

can u add debugs to each part of the sequence to see if anything stands out as odd?

true knoll
deft grail
#

theres a way around this im pretty sure, but i forgot

rocky canyon
# queen adder dont think so

i dont see anything in the code you sent that would cause it to glitch like that. unless ur respawnPoint is positioned < than ur threshold

queen adder
#

nah its higher by quite a bit

rocky canyon
#

i added an extra boolean.. didnt notice u already had one called.. functionCalled..

but i wonder what would happen if u included it in the conditional..
if ((transform.position.y < threshold) && (timer > 1) && readyToTakeDamage)

queen adder
#

i think it might be the velocity cancel out

rocky canyon
#

then set it back to true after u move ur player

queen adder
#

so should i just copy and past the code in from that link?

rocky canyon
queen adder
#

ive been constantly changing mine to try and get it tow work ;-;

rocky canyon
#

but if the extra bool works.. u could remove the timer all together iw ould think

queen adder
#

things seam to be acting the same

rocky canyon
#

interesting..

queen adder
#

yeah that thing with the functions is the same thing i originally tried

rocky canyon
#

maybe it has something to do with it being a rigidbody

#

and setting the transform.. manually..

#

b/c the rigidbody / physics stuff runs on a different timestep

queen adder
#

like set the transform to 00

#

not the respawn point?

rocky canyon
#

the controller of the ball.. its still running as you do this teleport isn't it?

#

that culd be an issue too..

#

Most times people will deactivate their movement scripts -> then teleport the object -> then reenable the movement scripts

#

this will stop the scripts from fighting each other.. (1 script saying go this way, the other one saying, no do this)

queen adder
#

yeah i heard about that

#

how do i disable the ball?

rocky canyon
#

set a reference to the script ur controlling it with..

public MyMovementScript myScriptReference;

then it's like

myScriptReference.enabled = false;
myScriptReference.enabled = true;

#

thats the same thing as ticking/unticking the checkbox on the component

#

yup, thats my overall assessment, the ball controller is interfering with ur fall off the map controller

queen adder
#

do you want me to send my player controller?

rocky canyon
#

you can but im almost positive thats what it is.. ur using rigidbody / physics.. and it runs on a slower timestep than regular update..

#

so ur update logic.. is being triggered more than once.. before the physics timestep can actually get around to getting out of hte way..

queen adder
#

mhm

queen adder
#

or more accuratly, where

rocky canyon
#

just as it is there..
create a declaration to hold the reference..
at the top.. w/ the rest of the variables

#

TheNameOfTheMovementScript theReferenceToTheMovementScript; drag it into the slot..
and then to enable and disable.. its just
theReferenceTo... . enabled = true or false;

queen adder
#

and i put this in my player controller?

rocky canyon
#

no.. you'd need to disable and enable it from the place where ur detecting the when it falls off the map..

#

if the code is inside the player controller.. and u disable it.. u cant enable it again.. b/c the code cant be run anymore

queen adder
#

got it

rocky canyon
#

can't lift a box ur standing in

queen adder
#

lol

true knoll
queen adder
#

my script refrence, do i replace that with the name of my player controller?

deft grail
queen adder
rocky canyon
#

now that i look at ur setup more and more.. it makes sense ur having problems..
your life script is change the transform.position of itself.. and for that to work.. that also means
that your life script is on the same object.. as the other script controlling it..

so now u have 2 scripts trying to change the transform.. (at the same time)

#

if u had a reference to the controller.. u could tell it to change its own position (back to the respawn point) instead of having 2 scripts manipulating the transforms together

#

something like myController.MoveToRespawnPosition();

#

then it could stop its other logic.. to move.. and then go back to its normal operation

queen adder
#

yeah my life script is on the same object as my controller script

rocky canyon
#

which isn't necessarily a problem.. until u have both scripts trying to move the same object at the same time..

queen adder
#

the player controller isnt trying to teleport the player anywhere

#

but it is applying force

rocky canyon
#

no, buts its moving via a rigidbody..

queen adder
#

got it

rocky canyon
#

yea, thats also changing the transform.position

queen adder
#

alright so how do i fix this

true knoll
#

thanks so much!

rocky canyon
#

so you either need to disable 1 of them.. to have the other move it..
or.. you need to have only the movement in the controller itself..
and create a public function that you can call from the other script to tell it to move itself back to the respawn position..

frigid sequoia
#

I have this method that tries to generate a random position on the NavMesh, but it does have the slight issue of being kinda likely to run way more into edges than it should, cause it is generating a random position and then calculating the closest point to that position on the NavMesh, so anything outside bounds tends towards the edges. Is there a kinda simple way of preventing this or I just have to work with that? https://gdl.space/avujiponun.cs

queen adder
#

well i definitly think there is a way for me to combine both of them into one

rocky canyon
#

i'd say so.. you can probably do all of this inside the ball controller..

#

since its only detecting if its y position is lower than a threshold..

#

it could do that itself

#

should look into how scripts communicate with each other..
b/c the controller could move itself.. when it goes past that threshold. and
then tell the other script to remove the lifecount.. and set teh textmeshpro element..

#

SingleResponsibility principle

#

Controller Moves the Ball..
Life script keeps up with the amount of life left..

public functions can be called from other scripts as long as they have a reference..

#

ur ball controller could have a reference to the Life script..```
// move myself back to respawn

// then tell the life script to take the damage off
lifeScriptReference.TakeDamage(1);```

queen adder
#

im getting a couple of unity errors

#

here is the code combined

rocky canyon
#

Instead of generating a completely random position and then finding the closest point on the NavMesh you can generate a random direction within a given radius around the current position

queen adder
frigid sequoia
rocky canyon
#

then sampleposition to find a valid position on the navmesh within that radius

frigid sequoia
rocky canyon
#

i'd just sample within the radius.. to ensure points are consistently on the navmesh

deft grail
rocky canyon
#

i'd just mess w/ the radius.. soo its not soo big.. that most points are outside the navmesh area

#

maybe make it dynamic.. depending on how close u are to the edge in teh first place

true knoll
rocky canyon
#

changing to kinematic is the simpler way.. but could cause unexpected behaviours.. mess w/ other systems

#

i commonly use an extra bool to wrap my movement and/or input logic in

deft grail
deft grail
frigid sequoia
#

So if they are like purposely getting near corners to mes with their pathfinding that might be an issue

rocky canyon
#

ahh i see.. ya this is jsut basic improvements what u have is default behaviour.. how you can refine it to make it better can go lots of different ways.. but im not big into navmesh so i couldnt say what woudl be the best way to improve it

#

you could just add some extra checking... like after you get ur first point... run it thru some logic.. see if its close to the edge.. say it is.. get a new point.. if its not good.. if it still is.. try again.. maybe have a cap.. so it only tries X amount of times to find a good point

frigid sequoia
rocky canyon
#

you would get the point first.. via ur calculations.. and then ask if that point is near an edge

frigid sequoia
#

Cause I could just add a small offset away from the edge if that's the case

rocky canyon
#

.FindClosestEdge

#

and the new calculated point.. and the closest to edge point.. and a threshold to ask how close it is..

#

see, already came up with a good solution

queen adder
#

ive changed the code a lot to the point where ive basically had to start over lol

rocky canyon
#

sometimes thats a good thing, tbh

queen adder
#

still having some issues tho, now respawn doesnt work

rocky canyon
queen adder
#

oh yeah i forgot about that

#

was focused on just mashing the code together

#

so how do you transform rigidbodies?

rocky canyon
#

you should instead use rb.MovePosition(respawnPosition);

queen adder
#

oh!

#

um.. weird error

#

"Argument 1: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.Vector3'"

deft grail
#

your trying to convert 1 thing to a different thing

#

which you cannot do

queen adder
#

hm, it was working beforehand, changing the transform to a move position caused this?

summer stump
queen adder
#

here

summer stump
#

What is the line number of the error

queen adder
#

66,25

deft grail
#

your respawn point should be a position

#

its a GameObject

#

you cant move to an object

#

you have to access its .position

queen adder
#

oh, alright

deft grail
#

which is on a Transform

queen adder
#

how would i write that?

deft grail
queen adder
#

i think thats what it was befroe

deft grail
#

but its what it should be now

queen adder
#

rb.MovePosition = respawnPoint.transform.position;

is what it is how

deft grail
#

why did you change the code

#

to an =

#

MovePosition is a method

queen adder
deft grail
#

your setting ot to respawnPoint

#

which is a GameObject

#

you need to be setting it to a Vector3