#💻┃code-beginner

1 messages · Page 236 of 1

cinder crag
#

I shared 2 scripts , sliding and playermovement

queen adder
#

Can you repost those? I dont really wanna scroll up and down lol

#

Also whats ur problem Hellio?

wintry quarry
#

I only see sliding

#

Also use paste sites

queen adder
#

!code

eternal falconBOT
wanton canyon
#

using different materials for the green cap vs eggplant body, or pumpkin stem vs pumpkin body

frigid sequoia
queen adder
#

Whats ur problem Hellio?

wanton canyon
cinder crag
# queen adder Also whats ur problem Hellio?

as u can see in the vid , the player when sliding from any height like in the vid where im sliding from a ramp , the player doesnt go down the ramp and the player floats slowly down until the sliding timer runs out which doesnt look good , well if it was some sort of wizard game it would work i guess lol

frigid sequoia
grizzled zealot
#

(sorry for the delay in the answer). I'm trying to get to use events now for communicating changes and the getComponent<IHealth>() doesn't really follow that model. I think it's just about: choose one style and stick to it.

#

The beauty of storing live stats with the scripts is that you see them in the editor. E.g., the Health script can have a field which can be inspected. If I put everything into a separate object, then I would have to program all the inspection abilities.

queen adder
timber tide
#

I've not really looked into mesh colliders with submeshes, but I'd expect there's a way to combine it all, otherwise I guess you can always make two copies of the mesh (combined and separate) and just use the filter of the combined mesh.

cinder crag
queen adder
#

Sorry brother

nocturne parcel
#

I'd say because when you jump, you're setting exitingSlope to true

#

So this if never happens
if (OnSlope() && !exitingSlope)
{
rb.AddForce(GetSlopeMoveDirection(moveDirection) * moveSpeed * 20f, ForceMode.Force);

        if (rb.velocity.y > 0)
            rb.AddForce(Vector3.down * 80f, ForceMode.Force);
    }
#

Then there is no force pulling it down (except gravity)

#

I'm probably wrong, but test it out

#

Keep in mind setting velocity and using force at the same time is likely to break at some point

#

because when you change velocity directly, you override any kind of force being applied

cinder crag
noble folio
#

does anyone know why?

acoustic crow
cinder crag
#

lemme see what i can do

queen adder
queen adder
acoustic crow
#

what do you mean

noble folio
#

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

public class PlayerBallTrigger : MonoBehaviour
{

public GameManager gm;
public FindPlayersInTeamFolder fpitf;

private void OnTriggerEnter(Collider other)
{
    if(other.tag == "Ball")
    {
        Debug.Log(other);
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player1))
        {
            Debug.Log("Works1");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player2))
        {
            Debug.Log("Works2");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player3))
        {
            Debug.Log("Works3");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player4))
        {
            Debug.Log("Works4");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player5))
        {
            Debug.Log("Works5");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player6))
        {
            Debug.Log("Works6");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player7))
        {
            Debug.Log("Works7");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player8))
        {
            Debug.Log("Works8");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player9))
        {
            Debug.Log("Works9");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player10))
        {
            Debug.Log("Works10");
        }
        if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player11))
        {
            Debug.Log("Works11");
        }
    }
}

}

cinder crag
nocturne parcel
queen adder
#

JESUS

noble folio
queen adder
#

!code

eternal falconBOT
noble folio
queen adder
#

What are u trying to do forever?

acoustic crow
#

@queen adder

noble folio
queen adder
#

Also justin?

lost anvil
#

does this error matter?

acoustic crow
lost anvil
queen adder
#

How does ur rocketship know its touched the boundary?

#

How do u keep the rocket in bounds of the camera?

acoustic crow
#

ah wait

queen adder
#

@noble folio what are you trying to do really

noble folio
#

wdym

queen adder
#

Whats the point of the code?

#

Its wrong

noble folio
#

football game

#

im bad at coding

queen adder
#

I mean its okUnityChanThumbsUp

#

Noone and i mean Noone starts out coding and is just perfect at it

#

It takes time

#

So again what are you trying to do?

noble folio
#

football game

queen adder
#

With the code

#

Whats the purpose

acoustic crow
#

Player Script Infos for Boundary

private bool isTouchingBoundary = false; 


 private void FixedUpdate()
 {
     if (!isTouchingBoundary)
     {
         Move();
     }
     Rotate();
 }

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("MapBoundary"))
    {
        isTouchingBoundary = true;
    }

private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("MapBoundary"))
    {
        isTouchingBoundary = false;
    }
}

And the Boundary Script

using UnityEngine;

public class EdgeOfScreenCollision : MonoBehaviour
{
    public float colDepth = 3f;
    public GameObject Kamera;

    private Vector2 screenSize;
    private Transform topCollider, bottomCollider; //, leftCollider, rightCollider;

    private void Start()
    {
        if (Kamera == null)
        {
            Debug.LogError("Kamera nicht zugewiesen! Bitte ziehe die Kamera in die 'Kamera'-Variable im Inspector.");
            return;
        }

        InitializeColliders();
    }

    private void Update()
    {
        MoveCollidersWithCamera();
    }

    private void InitializeColliders()
    {
        Camera cam = Kamera.GetComponent<Camera>();
        screenSize.x = cam.orthographicSize * Screen.width / Screen.height;
        screenSize.y = cam.orthographicSize;

        // Erstellen der Kollisionselemente
        topCollider = CreateCollider("TopCollider");
        bottomCollider = CreateCollider("BottomCollider");
        // leftCollider = CreateCollider("LeftCollider");
        // rightCollider = CreateCollider("RightCollider");

        // Einstellen der Positionen und Skalierungen
        SetColliderPositionAndScale(topCollider, new Vector3(0, screenSize.y + colDepth * 0.5f, 0), new Vector3(screenSize.x * 2, colDepth, colDepth));
        SetColliderPositionAndScale(bottomCollider, new Vector3(0, -screenSize.y - colDepth * 0.5f, 0), new Vector3(screenSize.x * 2, colDepth, colDepth));
        // SetColliderPositionAndScale(leftCollider, new Vector3(-screenSize.x - colDepth * 0.5f, 0, 0), new Vector3(colDepth, screenSize.y * 2, colDepth));
        // SetColliderPositionAndScale(rightCollider, new Vector3(screenSize.x + colDepth * 0.5f, 0, 0), new Vector3(colDepth, screenSize.y * 2, colDepth));
    }

    private Transform CreateCollider(string name)
    {
        var colliderTransform = new GameObject(name).transform;
        colliderTransform.gameObject.AddComponent<BoxCollider2D>();
        colliderTransform.parent = transform;

        // Stelle sicher, dass der Tag "MapBoundary" im Unity-Editor existiert
        colliderTransform.gameObject.tag = "MapBoundary";

        return colliderTransform;
    }

    private void MoveCollidersWithCamera()
    {
        Vector3 cameraPosition = Kamera.transform.position;
        SetColliderPositionAndScale(topCollider, new Vector3(cameraPosition.x, cameraPosition.y + screenSize.y + colDepth * 0.5f, 0), topCollider.localScale);
        SetColliderPositionAndScale(bottomCollider, new Vector3(cameraPosition.x, cameraPosition.y - screenSize.y - colDepth * 0.5f, 0), bottomCollider.localScale);
        // SetColliderPositionAndScale(leftCollider, new Vector3(cameraPosition.x - screenSize.x - colDepth * 0.5f, cameraPosition.y, 0), leftCollider.localScale);
        // SetColliderPositionAndScale(rightCollider, new Vector3(cameraPosition.x + screenSize.x + colDepth * 0.5f, cameraPosition.y, 0), rightCollider.localScale);
    }

    private void SetColliderPositionAndScale(Transform colliderTransform, Vector3 position, Vector3 scale)
    {
        colliderTransform.position = position;
        colliderTransform.localScale = scale;
    }
}
queen adder
#

omg

#

!code

eternal falconBOT
queen adder
#

@acoustic crow

final trellis
#

so I have some code that reads from a .txt file in the assets folder, will the code still function once I make a build of the game? or is there something else I have to do

noble folio
acoustic crow
#

@queen adder you want it , you have it

queen adder
#

Id appreciate some line numbers when i read the code

#

And highlighting

nocturne parcel
#

@cinder crag i'd say put a debug.log in every line at this point lol

queen adder
#

Please use one of the websites i linked

tender stag
#

this is what happens when i dont comment it out ^

queen adder
#

I also have no Idea what the Move() does

acoustic crow
#

@queen adder Boundary Script

queen adder
acoustic crow
noble folio
queen adder
#

Are the Debug.Logs not getting called?

noble folio
#

no they arent

queen adder
#

Then its not a code issue

#

Its a Inspector issue

nocturne parcel
queen adder
#

Does the ball and the player have colliders?

#

Is it a 2D game?

noble folio
#

no 3d

#

they both have it

queen adder
#

Does one of them have a rigidbody attached

noble folio
#

but the players one is trigger

noble folio
cinder crag
#

idkidk

queen adder
#

It has a normal rigidbody and not a rigidbody2D right and make sure the colliders are the 3d versions as well

nocturne parcel
#

Yeah, just see what is getting called.

noble folio
#

yeah they are in the 3d versions

nocturne parcel
#

I mean, too big of a script for anyone here to look at. Try trim it down.

queen adder
#

Show me the entire playerScript @acoustic crow

#

I need to know how Move() works

acoustic crow
queen adder
#

Forever are you sure they are collider?

noble folio
#

yes

queen adder
#

And the Colliders Trigger bool is checked?

cinder crag
noble folio
nocturne parcel
#

Sure

queen adder
#

Who has the OnEnterTrigger Script?

nocturne parcel
#

my guess is something on the SpeedControl function

queen adder
#

Screenshot ur inspector

noble folio
queen adder
#

You mean the Player Gameobject?

#

Forever screenshot ur inspector lol not you justin

noble folio
#

on what

queen adder
#

The player gameobject

#

Justin you disable movement when the player touches the bounds

noble folio
nocturne parcel
queen adder
#

And ur football

noble folio
nocturne parcel
#

If it is in the air, no matter what, the gravity should still push it down

cinder crag
#

slowly losing it

summer stump
# noble folio

Other is the ball
Which does not have the PlayerVariables script

noble folio
#

yes

acoustic crow
queen adder
#

Not you justin

frigid sequoia
#

Ey, just a quicky here; if in a collision check I am checking if the object of collision has a component (for example TryToGetComponent<someScript>()) does it get it get the component even if it is dissabled?

queen adder
#

meaning ur if statements never run @noble folio

nocturne parcel
#

@cinder crag try the #⚛️┃physics channel too, they are full of people way smarter than me lol

cinder crag
summer stump
# noble folio yes

Just in case you missed my edit, other does not have the PlayerVariables script on it
Other is the ball.
PlayerVariables is on the player, and so is the code checking the collision

timber tide
acoustic crow
queen adder
#

Its because you set the touchingBounds bool to true and you have a if statement saying if (!touchingBounds) Move()

#

As you soon as you touch the bounds the Move() stops getting called

acoustic crow
#

i dlete this

summer stump
# noble folio ohhh

So since playervariables is on the SAME object as the one checking the collision, why do you even need to check for PlayerVariables?
Just have it assigned to begin with

acoustic crow
#

but the problem is physik

queen adder
#

Its still not working?

queen adder
#

Sorry i didnt realize that sooner Forever

acoustic crow
#

No, I think it's because of how the rocket is built because when the wings touch the boundary, the tip can go up and because I'm flying to the left, I can't control the nose so that it flies down again, but I know not how I can do that

frigid sequoia
wanton canyon
#

sooo I combined objects in blender, exported as fbx, and the mesh collider is properly on the object now... but when I go to pick up the object, it is still being weird

noble folio
#

alright everything works now tysm

tender stag
#

how can i make this work while also having the yRotation only go from 0 to 360 ```cs
if(yClampRotation)
{
float left = yMidRotation - yClampLeftAngle;
float right = yMidRotation + yClampRightAngle;

Debug.Log("Left" + left);
Debug.Log("Right" + right);

yRotation = Mathf.Clamp(yRotation, left, right);

}

yRotation = Mathf.Repeat(yRotation, 360f);```

#

the problem is that when i have the yRotation = Mathf.Repeat(yRotation, 360f);

#

this happens

modest dust
wanton canyon
frigid sequoia
#

You mean like the object origin is off or what?

wanton canyon
#

yeah the object is rotating itself

frigid flume
#

hello, do you know why is this causing a stack overflow ? ^^

errant pilot
#

Guys this works the trajectory is fine but its too slow the target moves from its place by the time it reaches and when i increase velocity its trajectory changes, any ideas please?

modest dust
frigid flume
#

Score is a public long and Timer a private float

modest dust
#

Show it.

frigid flume
#

just changed timer to public

modest dust
frigid sequoia
#

I think I know what you are refering to, but I am not sure, could you send a more descriptibe image?

frigid flume
frigid sequoia
# wanton canyon

Oh, so it is meant to be held infront the camera, that's the issue?

frigid sequoia
frigid sequoia
# wanton canyon nope

Then... change the script that manages the dragging since it is clearly not working as intended

tender stag
#

yRotation = (yRotation) % 360f;

#

i did this

#

it works

#

also yeah i dont need the brackets

old mesa
#

i made a string variable called message but whenever i try to run the code it tells me the variable is assigned but never used

short hazel
sage mirage
#

@twin ibex I highly recommend you to watch full harvard courses in Computer Science in FreeCodeCamp, also try to watch different tutorials in Game Dev in YT and you can also check courses in Udemy. You will learn a lot from there you will basically gain some useful information. After gaining that useful knowledge you will be able to work on your own projects and gain experience from there. The best practice to learn Game Dev and programming is by working on different projects on your own and getting errors to solve on your own. That's what I am trying to do as well with every resource I have available. Final and recommended it to get help here whenever you get a confusing bug to fix.

short hazel
old mesa
short hazel
#

print("... seconds off." + message)?

old mesa
short hazel
#

Especially when you've done it twice already, on the same line of code

long jacinth
#

it is only the default sprite i set it to in the editor and not Mgsprite

#

its inside a function that i made btw

languid spire
short hazel
#

It's very unlikely your random number will be exactly equal to these yep

rocky canyon
long jacinth
#

but all of them are MgSprite

tender stag
short hazel
tender stag
#

i’ve got ladders and step detection left to do

#

and then swimming in the future

rocky canyon
long jacinth
#

ohhh

tender stag
rocky canyon
ionic zephyr
#

In a card game if I have different types of cards if I have a common class "cards" but I want some cards to do something and others to perform other functions how should I develope it?

#

any ideas?

honest haven
#

why would line 313 throw null ref when im already checking its not null

rocky canyon
short hazel
# long jacinth ohhh

You need to use Range(0, 3):

  • Notice the absence of f which makes these numbers integers (of type int)
  • We go up to 3 because the integer version excludes the max value so this will return numbers from 0 to 2.
rocky canyon
#

but if i did swimming mechanic.. i could also simply also turn that into a flying mechanic

slender nymph
languid spire
long jacinth
ionic zephyr
#

In a card game if I have different types of cards if I have a common class "cards" but I want some cards to do something and others to perform other functions how should I develope it?
any ideas?

rocky canyon
ionic zephyr
#

which perform different functions

#

In terms of code, any ideas of how should I face it?

lost anvil
#

what does this error mean?

ionic zephyr
#

could someone help please?

short hazel
# ionic zephyr In terms of code, any ideas of how should I face it?

Sounds like you need inheritance. The base creature class should be abstract (so it cannot be instantiated), and each sub-category has its own class that inherits from the base creature class.
Implementing the specific behavior can be done using a method you override in the child class. Which means it should be also abstract in the base class.
So when you have a variable of type Creature and call the abstract method on it, it will select the correct subclass' method automatically

lost anvil
short hazel
#

(the error appears complex because it happens in a lambda expression () => ..., that's how C# translates their names - it's still the same troubleshooting steps as a regular NRE though)

normal vault
#

Why does this work but also don’t? Help I want to have a variable of a parent, and when i run the game, it works, but there are those errors

short hazel
#

It's raining men NREs

ionic zephyr
#

And what about if I want them to have distinctive moves?

normal vault
slender nymph
#

then something else is affecting it

short hazel
acoustic crow
#

!code

eternal falconBOT
sage mirage
#

Hey, guys! Because I am confused a little bit with the singleton pattern. Which objects do I have to make as singleton and which not and why?

slender nymph
#

you don't have to make any object a singleton

ionic zephyr
#

should I have pokemon-type moves as scriptable objects??

ionic zephyr
#

or how should I implement them

slender nymph
# sage mirage Why?

wdym why? there are no requirements to make any objects a singleton. you can make an entire game without using a single one in your project

lost anvil
sage mirage
slender nymph
slender nymph
lost anvil
ivory bobcat
slender nymph
lost anvil
slender nymph
#

you do not need to start the coroutine over and over considering you have a while loop there

#

but you first need to address your NRE

lost anvil
#

nre?

slender nymph
#

NullReferenceException

lost anvil
#

that error is part of a built in DOTween script

slender nymph
#

did you even bother looking at the stack trace

lost anvil
#

dont know what that is mate

slender nymph
#

did you even bother reading the link i sent to you that explains these thigns

lost anvil
#

it just says what the error is

slender nymph
#

did you know that you can read all of the words on a page? you are not required to stop reading at the first period you encounter

short hazel
#

They read all the page, just didn't click any links lmfao

lost anvil
#

lol alright my bad very sorry

lost anvil
short hazel
#

The link explains what it is!

slender nymph
#

my guy, the first trouble shooting step linked on that page is literally titled "i don't understand stack traces"

lost anvil
#

oh my days lad, i know and understand it i just didnt know it was called a stack trace

slender nymph
#

great! if you understand what a strack trace is, then you can look at the full stack trace for the error, find where it is ocurring in your code, and resolve it. it's a very easy fix once you know what it is

lost anvil
#

it doesnt say its occuring in my code

slender nymph
#

again, look at the full stack trace

lost anvil
slender nymph
#

the full stack trace

lost anvil
#

that is the full thing

slender nymph
#

no it isn't

lost anvil
#

above that it just says nullreference error

#

doesnt tell me where annything is

slender nymph
short hazel
#

hahha

lost anvil
#

cold

slender nymph
#

this is like that spongebob episode where patrick was trying to open the jar

lost anvil
#

🤣 ikr

honest haven
#
    {
        craftingSplash.SetActive(true);
        yield return new WaitForSeconds(4f);
      
    }``` maybe im not understanding IEumerators correctly but i assummed that when i call this the rest of the code will not execute untill the 4s are complete. but they dont. Im calling it in a onclick method
honest haven
#

i.e ```public void MakeItem()
{

    StartCoroutine(Splash());
    
    enter.gameObject.SetActive(true);
    closeSplash = true;

    ShowItems();
}``` all the underneath of Splash does not execute
wintry quarry
#

and yeah you are not understanding coroutines

honest haven
#
    {
        craftingSplash.SetActive(true);
        yield return new WaitForSeconds(4f);
        enter.gameObject.SetActive(true);
        closeSplash = true;
        Debug.Log("here is the rest");
        ShowItems();
    }``` only the first two lines work
#

sorry first line

#

no debug result

keen sorrel
#

Anyone have any ideas why this isn't working? The way i think it isnt working is that i have a debug.log for its state, and it never goes into moving to pheromone state. No errors though

    {
        ParticleSystem thisPheromone = other.GetComponent<ParticleSystem>();

        if (thisPheromone.tag == "phermoneF" || thisPheromone.tag == "phermoneS")
        {
            if (currentState == AntState.Looking_For_Food)
            {
                currentState = AntState.Moving_To_Pheromone_F;
            }
            if (currentPheromone == null)
            {
                currentPheromone = thisPheromone;
            }

            else if (currentPheromone.main.duration > thisPheromone.main.duration)
            {
                currentPheromone = thisPheromone;
            }
        }

    }```
wintry quarry
north kiln
#

Or there's an exception they're ignoring

wintry quarry
acoustic crow
#

If I set the rigidbody to Kinematic, everything works great. Initially it is set to false, and upon collision with a meteorite it is set to true, resulting in the destruction of the rocket. The problem now is that the limit no longer works because there is no rigid body that behaves as if it were dynamic. However, when I choose a dynamic rigid body, even if the gravity scale is adjusted, all the parts start to fall, or it happens that the parts do not move together. Here are all the scripts and a video.
https://gdl.space/utalucucuy.cs PlayerScript (Rocket)
https://gdl.space/xafuwozure.cs BoundaryScript
https://gdl.space/vojajuvoge.cs Rockpart (Wings,Body,Engine,Arrow have that script)

https://www.youtube.com/watch?v=jvGmYJef-Sw

keen sorrel
honest haven
wintry quarry
wintry quarry
#

or how it's relevant

keen sorrel
honest haven
#

its called after the wait for seconds. what can canel that out

keen sorrel
wintry quarry
honest haven
lean geyser
#

Hey, I need some help with sprite renderer. I have a Player2D prefab asset and a Ship prefab asset. I'd like the Player2D prefab asset to use the SpriteRenderer that comes with Ship. As it stands:

public class Player2D
{
   private SpriteRenderer spriteRenderer;
   public Ship ship;

  void Start()
  {
    spriteRenderer = ship.GetComponent<SpriteRenderer>();
  }
}

Naturally this doesn't work, as there's still a SpriteRenderer assigned to Player2D. I genuinely have no idea how to do it :^( I should probably use the spriteRenderer in some way but not sure how.

queen adder
#

Can someone give me some guidance for a second? Im pretty lost on how to fix the errors here, I have a random spawn for my enemies so i set it up to be stored in the script so it can be used in the patrolling script but it keeps being seen as an input for one, im getting errors for line 25 and 48 of the patroller code (first is patroller, second is spawner)
https://hastebin.com/share/ugeramehiw.csharp
https://hastebin.com/share/atafamugiv.csharp

honest haven
lean geyser
short hazel
lost anvil
#

is DOTween the best approach to animate a hammer taking out the individual nails on these boards

keen sorrel
#

Is there a way to turn of the physics of a collision with a particle and gameobject so they pass through eachother but still record the collision?

hexed terrace
hexed terrace
keen sorrel
dire tartan
#

is there any easy way to stop a rigid body from sticking to a wall without using a physics material

#

since i dont want my character to slide down slopes

acoustic crow
#

Give me 5minuts

#

@dire tartan can you send the script

rocky canyon
#

ive built out this scroll wheel inventory system... and im trying to brain storm a way to allow gaps in it... like only populating as u pick things up
https://www.spawncampgames.com/paste/?serve=code_960
i have zero idea about how to do this... except possibly requiring a <List> vs the Arrays im using now
any tips/pointers?

example: i still want them to stay in the correct order, but skip the ones that havent been acquired

dire tartan
#

my movement script?

acoustic crow
#

That script with the Object who have the Rigidbody

dire tartan
#

i have it on my character

rocky canyon
short hazel
dire tartan
#

yeah that works but if the player is walking into the wall it sticks

rocky canyon
#

ya, it'll be fixed.. as its just weapon pickups..

rocky canyon
acoustic crow
#
private void FixedUpdate() {
    MovePlayer();
    CheckSurfaceAngle();
}

private void CheckSurfaceAngle() {
    RaycastHit hit;
    if (Physics.Raycast(transform.position, Vector3.down, out hit, playerHeight * 0.5f + 0.3f, WhatIsGround)) {
        float slopeAngle = Vector3.Angle(hit.normal, Vector3.up);

        if (slopeAngle > 45) { // Assuming 45 degrees as the limit for walkable slopes
            // Logic for steep slopes (e.g., prevent sticking to walls)
            rb.useGravity = true; // Ensure gravity is applied
        } else {
            // Logic for walkable slopes
            rb.useGravity = false; // Optionally stop gravity to prevent sliding down slopes
            // Apply movement here or in the MovePlayer method, depending on your game's physics needs
        }
    } else {
        rb.useGravity = true; // Apply gravity if not grounded
    }
}
#

Try this @dire tartan add this

#

in your script

short hazel
acoustic crow
#

when is not working remove it , i give my best for help but im not the best

half turtle
#

Hi

rocky canyon
#

shouldnt be a performance problem as its only gonnna get called when u go to swap weapons

rocky canyon
#

if theres any problems in the code.. they'll be coming back for solutions

#

that code wouldn't work anyway.. as his problem happens WITH gravity

dire tartan
rocky canyon
#

its not a gravity problem.. its a force problem

#

yea.. taht code doesnt solve ur issue

#

but its on the right track..

dire tartan
#

how would i go about fixing my problem?

rocky canyon
#

as i mentioned earlier.. u can make a function check if ur on a slope.. if u are on a slope set the physics material to the material with friction...
if theres no slope under ur feet set teh material to one without friction

keen sorrel
#

Can anyone help me fix this error?

Code:

    private void OnTriggerEnter2D(Collider2D collision)
    {
        ParticleSystem thisPheromone;

        if (collision.gameObject.tag == "food")
        {
            if (currentState == AntState.Moving_To_Pheromone_F || currentState == AntState.Looking_For_Food)
            {
                //Debug.Log("Collision Enter FOOD");
                currentState = AntState.Moving_To_Food;
                if (currentFood == null)
                    currentFood = collision.gameObject;
            }
        }

        if (collision.gameObject.tag == "pheromoneF" || collision.gameObject.tag == "pheromoneS")
        {
            thisPheromone = GetComponentInParent<ParticleSystem>();
            Debug.Log(thisPheromone.tag); //Line 248
        }


    }

Error:

NullReferenceException: Object reference not set to an instance of an object
Ant.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Ant.cs:248)
rocky canyon
#

too many alex's

dire tartan
#

fr xd

rocky canyon
#

oooor.. maybe not..

#

what line is line 248

keen sorrel
keen sorrel
#

its the debug one

rocky canyon
#

Assets/Ant.cs:248) <-- shows u the line number

#

ahhh.. soo yea.. thisPhermone doesn't have a tag variable

hexed terrace
#

thisPheromone is null because the ParticleSystem on the line above isn't found

rocky canyon
#

if u want to check the tag.. u need to get its gameObject and check that for the tag

keen sorrel
rocky canyon
#

its b/c this is referencing the script

#

it doesn't have a .tag

hexed terrace
rocky canyon
#

is it?

keen sorrel
#

im trying to do collider checks on particles so it follows it down the gradient and particle collisions wasnt working so now im trying with an empty gameobject as the child of the particle and doing collision checks with that and its parent

rocky canyon
#

u dont have to get the gameobject first?

hexed terrace
#

it wouldn't compile if that was the case, and the docs I linked to show it as an inhereted property

south fjord
#

Can you only create xml files within the built game, and not the Editor?

lost anvil
#

because that is what i am aiming for

hexed terrace
#

that's... a screw drvier and a screw, not a hammer ;p

#

but yes, that looks tweened

lost anvil
#

yeah but i mean the animation lol alright cheers

#

couldnt be bothered getting further into the game to get the hammer xd

tender stag
#

how can i use the attribute on a enum?

short hazel
#

Use it on a field

#

Creating an enum does not make a field, it's as if you created a class in a class.
You need something like ```cs
[Space(5)]
public ClimbingStage clibmingStage;

#

(create a field of the enum type)

#
  • naming conventions: enum values should be in PascalCase: Start, Waiting, etc.
clear seal
#

um can someone help me for this script

#
IEnumerator Reload()
{
    IsReloading = true;
    Debug.Log("Reloading...");

    animator.SetBool("Reloading", true);

    yield return new WaitForSeconds(reloadTime - .25f);
    animator.SetBool("Reloading", false);
    yield return new WaitForSeconds(.25f);

    currentAmmo = maxAmmo;
    IsReloading = false;
}```
#

so basically it says that the last bracket is not found

#

how come

#

i dont see anything interfereing

short hazel
#

Maybe after the block, do you have a } to close the class?

#

If it's the end-of-file, the error cannot be reported further than the last character, your } here

clear seal
short hazel
#

Post the entire script in a paste website

clear seal
#

ok

#

!code

eternal falconBOT
clear seal
#

@short hazel i cant it says i got too much words

short hazel
#

Never heard of anyone encountering this error

#

Unless your script is 10000 lines long there should be no problem

south fjord
short hazel
lost anvil
#

what does this error mean?

clear seal
#

well i copy pasted but said the same

#

oh wait

short hazel
#

You do not need a variable to access static stuff

clear seal
lost anvil
#

alright cheers

clear seal
#

how do i send it

short hazel
#

Hit the "Save" button first, then copy-paste the URL

clear seal
short hazel
#

The class isn't ended with a }.

#

Every { must have its closing } counterpart

clear seal
short hazel
#

No

zenith cypress
#

Not in the code you gave

short hazel
#

The very last } closes IEnumerator Reload()

clear seal
zenith cypress
#

The class

short hazel
clear seal
#

OHHHH

#

fixed

#

thanks :/ 👍

tender stag
#

my movement script is 1200 lines and im like half way done

#

holy

#

should i be seperating this into different scripts?

#

like the code is easy to navigate so im not sure

low path
#

I would probably separate them into different components with individual functionality.

vale karma
#

hello, im having trouble with my ground check raycasts returning true too early. heres the raycast and the frame where it changes the state from falling to grounded. souly based on if this code returns true.

#
    {
        int hits = Physics.OverlapSphereNonAlloc(groundCheckSphere.position, capsule.radius, groundedResults, groundedLayers);
        return hits > 0;
    }```
lean geyser
#

Can someone help me? Im really lost for words now... I've been staring at this for hours and I really can't figure it out whatsoever.

public class Weapon : MonoBehaviour
{
    public GameObject bulletPrefab;
    public float fireRate = 0.5f;    // How often this weapon can fire
    private float nextFireTime = 5f; // When this weapon can fire again 

    public float bulletCount = 1;

    void Start()
    {
        nextFireTime = Time.time; // Initializes nextFireTime when the game starts
    }

    public void Fire(Transform[] spawnPositions)
    {
        // Check if it's time to fire again based on fireRate
        if (Time.time > nextFireTime)
        {
            if (bulletCount == 1)
            {
                Instantiate(bulletPrefab, spawnPositions[1].position, spawnPositions[1].rotation);
            }
            else if (bulletCount == 2)
            {
                Instantiate(bulletPrefab, spawnPositions[0].position, spawnPositions[0].rotation);
                Instantiate(bulletPrefab, spawnPositions[3].position, spawnPositions[3].rotation);
            }
            else
            {
                foreach (Transform spawnPosition in spawnPositions)
                {
                    // Instantiate bullet at the position and rotation of each spawnPosition
                    Instantiate(bulletPrefab, spawnPosition.position, spawnPosition.rotation);
                }
            }
            // Update the nextFireTime to be the current time plus the fire rate
            nextFireTime = Time.time + fireRate;
        }
    }
}```

The problem lies in index being outside the bounds of array, but the problem only started happening when I attempted to use `Ship` prefab as reference in `Player2D`.
#

Player2D

  void Start()
    {

//Set screen orientation to portrait
Screen.orientation = ScreenOrientation.Portrait;

//Set sleep time to never
Screen.sleepTimeout = SleepTimeout.NeverSleep;

missileCountCurrent = missileCountMax;
missileIsRecharging = false;

      if(ship == null)
{
          ship = Instantiate(ship, transform.position, Quaternion.identity).GetComponent<Ship>();
      }
SpriteRenderer shipSpriteRenderer = ship.GetComponent<SpriteRenderer>();

      SpriteRenderer playerSpriteRenderer = GetComponent<SpriteRenderer>();
      if (shipSpriteRenderer != null && playerSpriteRenderer != null)
      {
          playerSpriteRenderer.sprite = shipSpriteRenderer.sprite;
      }

      transform.position = new Vector3(pos.x, pos.y + 0.2f, pos.z);

  }```
#

Am I accessing the array the wrong way? Is it possible I simply just didn't reference the Ship prefab correctly?

#
public class Ship : MonoBehaviour
{
    // Ship specific properties
    public Weapon weapon; // Weapon
    public Transform[] bulletSpawnPos; // Bullet spawn positions
modest dust
#

I assume the error is in the Fire method of the Weapon class

#

You're accessing spawn pos at index 3

#

you only have 3 elements in the array on the picture

lean geyser
#

Oh yeah it did fix it, but the projectiles still won't come out

lean geyser
#

I just happened to change the variable as you specified it (there's a variable responsible for projectile count)

#

problem is... the ship is still not shooting despite everything being the same code before encapsulation

timber tide
#

ya code lacks debug.logs

#

should be plastering them if you're running into an error like oob

vale karma
#

i think i got it, i had to test the position and move it accordingly. It looks a bit weird and probably could change the radius to help, idk it works now

#

^^ debug helps so much with state machines. I only put them in enter and exit. update is too much

lean geyser
teal viper
south fjord
#

I'm trying to read a serialised binary file of an array, but when I try to deserialise it says that it "cannot implicitly convert type 'object' to type 'int[]'" and that an explicit conversion exists, and asks if I am missing a cast. How do I convert object to int[]? Never had to deal with this before...

slender nymph
#

show the relevant code

south fjord
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class BinaryArray : MonoBehaviour
{
    public UnityEngine.UI.Text textbox;
    int[] number = new int[3];
    public void Start()
    {
        number[0] = 1;
        number[1] = 2;
        number[2] = 3;
        string filename;
        FileStream myFileStream;
        filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
        myFileStream = new FileStream(filename, FileMode.Create);
        BinaryFormatter binaryformat = new BinaryFormatter();
        binaryformat.Serialize(myFileStream, number);
        myFileStream.Close();
    }
    public void FixedUpdate()
    {
        string filename;
        FileStream myFileStream;
        filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
        if (File.Exists(filename))
        {
            myFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryFormatter binaryformat = new BinaryFormatter();
/!\            number = binaryformat.Deserialize(myFileStream);
        }
        myFileStream.Close();
        else
            return;
    }
}
#

problem at /!\

slender nymph
south fjord
#

👍

#

But how could I fix it

slender nymph
#

you remove that code entirely and use a better way to serialize deserialize

south fjord
slender nymph
#

but if you don't mind potentially exposing your players to malicious code being executed on their devices, then just cast to the type you need

south fjord
#

How would I do that

south fjord
#

just (int)?

slender nymph
#

cannot implicitly convert type 'int' to type 'int[]'

south fjord
#

rolls eyes

slender nymph
#

if you want to be snarky, then just read the error

south fjord
#

¯_(ツ)_/¯

teal viper
south fjord
#

but (int[]) should work then?

#

actually it wouldn't right

slender nymph
#

have you bothered trying it

teal viper
#

Did you try?

south fjord
#

fair enough

slender nymph
#

also unrelated to the error, but deserializing in FixedUpdate is a yikes 😬

south fjord
#

lemme

south fjord
#

would update be better?

slender nymph
#

why would you do either? why would you want to read and deserialize the data every frame

south fjord
#

that is a fair point actually

grizzled zealot
#

I'm trying to create event channels through scriptable objects (like shown in the Unity devlog for Chop Chop). To simplify my life, I want to create a template channel that I can instantiate for differnet types, so I don't have to write out the code. It doesn't seem to work. Am I am doing something wrong, or is this not supported in unity?

#

Basically, upon instantiation, I want to create an SO with UnityEvent<int> or another with UnityEvent<MyScript>.

idle agate
#

im trying to get into vr dev, but when im importing the room, it appears all pink

tender stag
#

what would be the most optimal way of calculating ladderMoveDirection? (direction to add force to) cs moveDirection = orientation.forward * y + orientation.right * x; slopeMoveDirection = Vector3.ProjectOnPlane(moveDirection, slopeHit.normal); ladderMoveDirection = ; cs [Range(-1,-90)] public float upperLookLimit = -88.5f; [Range(1,90)] public float lowerLookLimit = 88.5f;

#

i also want to use the upperLookLimit and lowerLookLimit

#

i dont need the side direction - x

#

just like the way im looking between upperLookLimit and lowerLookLimit

#

im not sure

timber tide
south fjord
# south fjord ```cs using System.Collections; using System.Collections.Generic; using UnityEng...

Updated code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class BinaryArray : MonoBehaviour
{
    public GameObject textbox;
    GameObject numberOutput;
    int[] number = new int[3];
    public void Start()
    {
        number[0] = 1;
        number[1] = 2;
        number[2] = 3;
        string filename;
        FileStream myFileStream;
        filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
        myFileStream = new FileStream(filename, FileMode.Create);
        BinaryFormatter binaryformat = new BinaryFormatter();
        binaryformat.Serialize(myFileStream, number);
        filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
        FileStream myFileStream1;
        if (File.Exists(filename))
        {
            myFileStream1 = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryFormatter binaryformat1 = new BinaryFormatter();
            number = (int[])binaryformat1.Deserialize(myFileStream);
            GameObject myCanvas = GameObject.Find("Canvas");
            for (int tempNumb = 0; tempNumb < number[2]; tempNumb++)
            {
                numberOutput = Instantiate(textbox);
/!\             numberOutput = transform.SetParent(myCanvas.transform, false);
            }
        }
        else
        {
            myFileStream.Close();
            return;
        }
        myFileStream.Close();
    }
}

At /!\ it says this:

#

I got absolutely no idea why

cosmic dagger
#

The method does not return a value . . .

south fjord
#

Yeah I had just noticed too

#

Wrote it wrong

#

What ya get for coding at 3 am lol

whole idol
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaypointFollower : MonoBehaviour
{
    [SerializeField] GameObject[] waypoints;
    int currentWaypointIndex = 0;
    [SerializeField] float speed = 1f;
    void Update()
    {
        if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
        {
            currentWaypointIndex++;
            if (currentWaypointIndex >= waypoints.Length)
            {
                currentWaypointIndex = 0;
            }            
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
    }
}

clear seal
#

so i made this simple side looking code but how do i add a limit to it???

static bay
clear seal
#

i guess

whole idol
#

All objects that are moving work perfectly fine and are assigned properly

summer stump
#

Could also do an early return if waypoints has nothing in it

summer stump
teal viper
clear seal
teal viper
clear seal
whole idol
thorn holly
#

if I have DontDestroyOnLoad() enabled a GameObject, do I still need to make scene changes additive for the scene that contains the GameObject?

teal viper
summer stump
#

You add objects to it, not enable it on objects

thorn holly
summer stump
#

And no, DDOL does not get unloaded

thorn holly
#

awesome, thanks

clear seal
teal viper
clear seal
#

we just call it angle for us lol

summer stump
teal viper
#

Angles can be measured in radians too.

summer stump
#

Euler is specifically one type of angle

clear seal
summer stump
whole idol
#

Is there any way to mute all music and sounds coming from my scene while im testing my game without having to go and uncheck all Audio Sources?

summer stump
#

That SHOULD have been taught around then as well...

clear seal
#

¯_(ツ)_/¯

summer stump
lean geyser
#
    private AudioSource audioSource;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        color = GetComponent<SpriteRenderer>().color;
        audioSource = GetComponent<AudioSource>();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            Debug.Log("Coin picked up");
            audioSource.Play();
            Destroy(gameObject, audioSource.clip.length);
            Debug.Log("Coin Deleted");
        }
    }
#

No sound played on pickup? Audioclip works just fine if played on awake

idle agate
summer stump
frigid sequoia
#

Is... using this kind of "recursion" right? Cause something tells me this is so wrong for some reason...

frigid sequoia
summer stump
#

Sure, makes sense

#

But I would have a max tries

eternal needle
sudden adder
#

Recursion is fine too

frigid sequoia
eternal needle
#

yes

#

recursion is used more for solving data problems, but really recursion isnt needed unless you are doing functional programming. Iterative solutions are better and faster

sudden adder
#

I mean, she likely has a list with only a few things, unless there's tons of gameobjects calling this function itll never incur any noticable difference. Iteration is usually better in these instances tho but her solution seems to be just fine now

summer stump
frigid sequoia
#

Also, I am pretty sure the thing I am doing should be stored on a scripteable object, but not sure how to do that actually, or if it even matters that it is instead an empty object in scene that stores it

sudden adder
sudden adder
#

I thought thats what you implied, nevermind

summer stump
#

Just that the code AS IS, is not great
Gotta add something like a hard stop to end the loop

frigid sequoia
sudden adder
#

Seems fine, like he said just make sure you have something to break the loop.

frigid sequoia
#

So it probably needs to be optimized to be called with certain frequency and with some decent data to manage

sudden adder
#

If you want to change to a while loop as well that could work. I would go with whichever makes the most sense at the moment and change later if needed for scalability or performance

south matrix
#

Is there a way to prevent Unity from logging this whenever I compile?

ivory bobcat
silk night
#

if you scroll in the log, does it give you a script location that is triggering that log?

torn edge
#

Hi yall, can someone explain to me why it doesn't display the value of points properly? I update the points in two different scripts, the original one and the coin script but when I print out the value of points in the original script it shows the updated version but for some reason the updated version doesn't show up on the screen

#

The updated version includes what the coin script changed

ivory bobcat
#

Post the code to an external site and paste the saved link here !code

eternal falconBOT
south matrix
#

It looks like it was Burst debug stuff that was doing it

#

I was able to turn it off

sudden adder
#

And can you show the points script

silk night
sudden adder
#

Yea or currentScore is null

ivory bobcat
#

If the value no longer updates likely the score object is no longer available.

frigid sequoia
#

Ok, I changed the actual pool from where the powerUps are being drawed to only include availiable ones so it should be more efficient now. I am kinda worried for how I should handle stuff like, maybe in the future I want some powerUps to be avalible after some kind of achievement/unlock.... And I not sure my code can handle something like that right now

#

And I kinda want to address that now that changing it would be way less convoluted

#

Like, if a certain powerUp is avaliable is set on a bool on the powerUp itself, which makes it so... I cannot actually change it from the prefab, how shoud I manage this?

#

Should it just be stored somewhere else that I can change?

#

Cause I cannot assign a reference to a prefab to a script and modify parameters from it before it is instantiated right?

sudden adder
frigid sequoia
clear seal
#

so i want to make my charachter crouch by making it small but how do i do that without the child to be affected?

frigid sequoia
summer stump
sudden adder
summer stump
frigid sequoia
#

But I cannot find it so I guess I dream it XD

#

Sry for spreading missinformation I guess

clear seal
#

ima watch a tutorial

errant pilot
#

Guys this works the trajectory is fine but its too slow the target moves from its place by the time it reaches and when i increase velocity its trajectory changes, any ideas please?

devout flower
#

is there an obvious reason why setting velocity works, but using MovePosition doesn't work? (for rigidbody2ds)

#

or do you think it would be my other code interfering

summer stump
frigid sequoia
hot wave
#

If I want to zoom in on an item when inspecting, should there be a new camera? or just move the main camera towards xyz? but problem is, I am using a character controller that is with the camera and moving the camera might move the characters also, and how would the code look like?

#

and if it is a new camera, would i make many cameras for each item?

frosty hound
#

Cinemachine is what you would want to use

clear seal
#

not even close

#

:(

frosty hound
#

It allows you to set up virtual cameras, and then just activate/prioritize the virtual camera you want the real camera to use. Cinemachine will handle the rest.

idle agate
#

i just fixed my error with the pink parts on models

#

i was using the wrong 2020.3 version

outer wigeon
# hot wave okok c: thank you steel

I just did this the other day actually, it's as easy as changing which cinemachine is the priority camera iirc. Youll see it in the settings. It's an awesome package

#

If you have trouble you can ping me since I just wrote something for that a few days ago

opal knot
#

same thing with .GetComponent<>()

whole idol
#

Hi.. This is a movable platform that I got. Whenever my player steps on it my player remains stationary but I want his feet to stay grounded like a plant on that blue platform and move with it instead of drifting as if it's made out of ice

grizzled zealot
#

Is there a way to generate stubs for all the methods I need to implement for an InputAction map

teal viper
# whole idol

You'd need to apply the platform velocity to the character.

queen adder
#

Any name suggestion for this method? 🥺

#

my english not englishing

teal viper
#

CompareAnimation or something

#

Or IsAnimationState

vale karma
#

i tried to implement a vCam in place of my main cam and now i lost the ability to rotate my player :/

native seal
#

how can I set my imported sprites to automatically be 16 pixels reference with compression and point filter on?

night mural
#

if you want it to be fully automatic you have to do a bit more work i think

kind sentinel
#

how do I go about passing the _gameGrid reference in GameGlobalScript to the static class GameTurnManager? it needs to be accessible for AdvanceTurn and many other functions yet to be written.

[ExecuteAlways]
public class GameGlobalScript : MonoBehaviour{
    [Header("GameObjects")]
    public GameObject _gameGrid;

    void Awake(){
        GameGridManager ggm = _gameGrid.GetComponent<GameGridManager>();

        // set up game grid
        ggm.Startup();
        ggm.TestPlayerCreate();
        ggm.CreateGrid();
    } 
}

public static class GameTurnManager{
    public static Dictionary<int, Player> Players {get; set;} = new();
    public static int CurrentTurn {get; set;} = 0;
    public static Player CurrentPlayer {get; set;}

    public static void AdvanceTurn(){
        CurrentTurn += 1;
        int PlayerIndex = CurrentTurn % Players.Count;
        CurrentPlayer = Players[PlayerIndex];

        foreach(GameTile tile in _gameGrid.Tiles){

        }
    }
}
teal viper
#

Like, why is it static? Where's AdvanceTurn called from? Why does it need the grids? Too many questions and no answers...

kind sentinel
teal viper
#

"being called from a ton of other prefabs script components" doesn't sound clean at all.

kind sentinel
#

it needs the grid class because each time the turn is advanced it needs to iterate over every GameObject in a list within GameGridManager

teal viper
#

Sounds like the opposite of clean. And you're helping make it so by giving everything a global access to it.

hot wave
#

how do I implement someting where a car (or any mesh) gets rotated when I click on it and go back to its original rotation after, and assign an ID if it is a car or a broom or a carpet, if it is a car, it will be rotated 90 degrees from x, then back to the original value after clicking again, then for the broom, it will be rotate by 45 degreese in y, then back to its original value, then for carpet, rotated by 180 degrees in z, then back to its original value, the ID would be used so that i can just hook it to an object to tell how it would rotate when click, I am using this for learning purposes UnityChanOkay

teal viper
teal viper
hot wave
#

but i dont know how they would work

#

i have the idea but cant put it into code

nimble scaffold
#

how are you all guys

kind sentinel
# teal viper "being called from a ton of other prefabs script components" doesn't sound clean...

how so? if there are a lot of objects that can be interacted with each turn, and once any one of them is interacted with they just call GameTurnManager.AdvanceTurn(); thats pretty clean right?
these gameobjects are dynamically created and destroyed by the GameGridManager class

each game tile prefab has this on it (stripped out code unimportant to this example):

public class GameTile : MonoBehaviour{
    //bunch of data stored here
    }

    void OnMouseDown(){
        //code for handling how this tile has been interacted with

        GameTurnManager.AdvanceTurn();
    }
hot wave
#

I was thinking of putting something like interactableID: toggleRotation 1 = 90,y,z, 2 = x,45,z 3 = x,y,15

then maybe assign the default rotations underneath like interactableID: defaultRotation 1 = 0,y,z, 2 = x,0,z 3 = x,y,0

#

but that wont work i think

teal viper
#

In fact, I'd just make gameManager hold an instance of a turn manager class, so as to not make it static.

teal viper
kind sentinel
hot wave
# teal viper Not sure what not sure what that represents? What is the toggleRotation? Are you...

there would be a lot of cars and brooms in the game i am planning to make, I plan to assign an id to them so they know how they would rotate if they are cars, brooms, or carpets when they are interacted in the interactable code, but still not sure if this is the best approach

this is a part of the interactor code to interact with the interactable (interactable will be where i assign the default rotations and id)

        {
            if (interactable == null || interactable.ID != hit.collider.GetComponent<Interactable>().ID)
            {
                interactable = hit.collider.GetComponent<Interactable>();
                //Debug.Log("New Interactable"); //something to check debug logs
            }
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                interactable.onInteract.Invoke(); ///this is where I would replace with the transform thingy
            }
        }
    }
}
}```
teal viper
kind sentinel
teal viper
teal viper
hot wave
teal viper
#

I can help you direct in the right direction.

hot wave
#

okok, I will try UnityChanOkay

#

how can we create a dictionary? should it be on a new script, and should every item have the dictionary script? can I just put it in the interactable script

teal viper
kind sentinel
teal viper
#
//In GameGlobalScript Start or wherever you want to pass in the grid
GameTurnManager.AddGrid(someGridReferenceOrListOrArrayOfGrids?);
hot wave
teal viper
hot wave
#

thank you dilch, I will try making a code, I'll show later ok UnityChanSalute

kind sentinel
teal viper
hot wave
#

dilch, is this ok? void Start() { rotationDictionary.Add(1, new Vector3(90, 0, 0)); rotationDictionary.Add(2, new Vector3(0, 45, 0)); rotationDictionary.Add(3, new Vector3(0, 0, 180)); }

#

not sure if correct

kind sentinel
hot wave
# hot wave dilch, is this ok? ``` void Start() { rotationDictionary.Add(1, n...
    {
        rotationDictionary.Add(1, new RotationData(new Vector3(90, 0, 0), new Vector3(0, 0, 0)));
        rotationDictionary.Add(2, new RotationData(new Vector3(0, 45, 0), new Vector3(0, 0, 0)));
        rotationDictionary.Add(2, new RotationData(new Vector3(0, 0, 180), new Vector3(0, 0, 0)));
}``` is this better? i want it to go back to the original position after (i dont know if this works)
#

or is there a better way

teal viper
#

Btw, your GameGlobalScript kinda sounds like a GameManager. Would add a few changes, but overall it seems like that's it's purpose.@kind sentinel

teal viper
hot wave
#

if different rotation, will it be ok?

#

i want to experiment UnityChanOkay

teal viper
#

I guess so. But maybe you should cache that in a script belonging to a rotated object

fringe plover
#

I dont know how it works but, will it work? it wont mess up?

#

is it ok to have methods with same names?

teal viper
#
targetObject.Rotate(rotation);
///In target object
void Rotate(SomeType rotation)
{
    lastRotation = transform.Rotation;
    //Your rotation logic
}
void Unrotate()
{
    transform.rotation = lastRotation;
}
```@modu._
teal viper
fringe plover
#

oh okay thanks

hot wave
#

ah wait, I think I found a problem in my previous code

#

if I set many things with the same id

#

would that mean when i click something with similar id, everyone gets rotated?

teal viper
hot wave
#

okok, I will try

stuck jay
fringe plover
#

yup i know

stuck jay
#

But yes, method overloading is a thing and that's actually already built into some of the stuff you use (Debug.Log for example)

hot wave
#

I got stuck UnityChanDown

#

i always get confused how objects and scripts interact

lavish gate
#

Theres a few ways, theres a website that ive been linked to a few times, ill see if i can find

#

it

#

here we are

solid sail
#

If I declare a Class A a = new Class(); at the top of script. And there's function AA() return a;
The question : Will it allocate memory to store "a" when each time call the function AA to return a?

teal viper
teal viper
stuck jay
lavish gate
#

Maybe but atleast you arent using .Find() then everything is well

stuck jay
#

I always thought GetComponent would be faster

lavish gate
#

You can always test

solid sail
hot wave
queen adder
#

Can someone explain to me why my enemy won't move after hitting a collider for a wall?
https://hastebin.com/share/deriruqeza.csharp

#

I think it might have to do with my rotation but im not sure how to fix it because i've tried 3 different methods atp

hot wave
#

are there tips to learn better? if ok UnityChanOkay

teal viper
teal viper
#

Also, going over structured courses, like the one on unity !learn could be useful:

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hot wave
#

I will do my best, thank you dlich, lazy

solid sail
hot wave
#

ah, I cant put gifs UnityChanDown

static bay
#

I think it's best to pay mind to "techniques" more than explicit implementations.

#

Understand WHY someone is doing something a certain way in a tutorial.

#

As opposed to just copying.

#

That being said, some tutorials are not conducive to that type of learning.

teal viper
static bay
#

A lot of the go-to Unity tutorial channels can be... strange.

static bay
#

Blackthornprod's early videos always irked me.

hot wave
#

blackthornprod UnityChanOkay

lavish gate
#

His many dev games irk me.

#

I still watch them though.

static bay
#

Those are fine and kind of fun

#

I know he got into some drama over one of them recently.

honest haven
#

Im still having issues with my coroutine just does not seem to wait for 4s and hit anything underneath it

#

So i thought the issue might be the button i was originally calling it from as i deactivate it. So instead i created a new function called SplashScreen and called the coroutine from there just incase it was a deactivate game object issue.

teal viper
languid spire
honest haven
#

Yes i understand that the rest of the code would run. i was just adding any text just to double check

languid spire
#

So, there is nothing wrong with your code, so it must be a problem with the object that is running it

#

show your full console tab

honest haven
#

OnDisable is never called

teal viper
#

Are there any errors maybe?

honest haven
teal viper
#

Add a log at coroutine start

languid spire
#

Yes, log before and after the yield also add an OnDestroy method to the script and log that

honest haven
ebon robin
#

record a video

#

would be easier to debug

honest haven
teal viper
# honest haven

Share the whole script. I want to see the on disabled method

honest haven
#

yh two secs

pastel ivy
#

Hello

teal viper
honest haven
pastel ivy
#

Dose anyone know how to make a menu screen on unity

stuck jay
honest haven
ebon robin
#

can you change the name of the IEnumerator

teal viper
ebon robin
#

maybe theres a method or class with the same name

pastel ivy
#

Is unity easy to use

#

Just asking because it’s my first time using unity

ebon robin
#

yes but you need to learn the basics

teal viper
pastel ivy
ebon robin
#

basics of C# and Unity

#

if you already know Java, C or C++ then C# is very similar

honest haven
teal viper
ebon robin
#

could be a suspect

teal viper
#

Can you print the value of Time.timeScale when starting the coroutine?

honest haven
#

yes when i pause

static bay
pastel ivy
honest haven
#

and the game is in pause mode

ebon robin
languid spire
teal viper
#

Ok, well, WaitForSeconds isn't gonna work then.@honest haven

ebon robin
#

when timescale is 0 then the wait for second wont work

honest haven
static bay
#

Well the more accurate thing to say is WaitForSeconds takes into account the timescale.

honest haven
ebon robin
#

comment out the timescale and try again

languid spire
ebon robin
#

I think it likely did

honest haven
#

it pauses the player

languid spire
#

that's it then, craftingSplash.SetActive(true); pauses the game so the yield wont run

static bay
#

mmmm singletons

honest haven
#

lol yeah only using singtons for crafting menu, game manager and crafting manager as there is only one

static bay
#

iz k

teal viper
static bay
#

For pausing in general, not specifically his issue.

ebon robin
#

like coding a new time manager I guess?

#

I had to recode the animator just recently

eager girder
ebon robin
eager girder
stuck jay
teal viper
eager girder
pastel ivy
#

Is making a 2d game more difficult than 3d or the same

ebon robin
#

Unity and Unreal have the biggest user base and libraries so I just went with it

eager girder
#

like a selext option for dev mode to do custom service

hexed terrace
pallid nymph
#

I tend to use both time scale and an isPaused bool in a manager for pause

static bay
eager girder
#

i tried with EditorGUILayout but i abit mess up

ebon robin
#

3d needs model

static bay
pastel ivy
ebon robin
pastel ivy
ebon robin
#

I find snatching 3d models kinda dumb because your game would easily turn into a jumble of unrelated mess

hexed terrace
#

But let’s not get off topic for the channel, it’s a code channel.

ebon robin
#

2.5d is the way to go if you want some height in your game, handling height in 2d is easily nightmarish

pastel ivy
#

I am going to start working on it tomorrow

#

I’m working on the script on it

viscid needle
#

cant it's a video tutorial but it's the same as his

teal viper
cobalt pike
#

if(currentGun.carryBulletCount > 0)
{
currentGun.anim.SetTrigger("Reload");

 if(currentGun.currentBulletCount >= currentGun.reloadBulletCoumt)
 {
     currentGun.currentBulletCount = currentGun.reloadBulletCoumt;
     currentGun.carryBulletCount -= currentGun.reloadBulletCoumt;
 }
 else
 {
     currentGun.currentBulletCount = currentGun.carryBulletCount;
     currentGun.carryBulletCount = 0;
 }

}

In this script, I've fired all 10 shots, and I've got to load 10 rounds from the ammunition 23 left, and it should be 23-10 = 13, but I've got all 23 rounds loaded in the magazine

#

I can't find anything wrong with that coding. Did I miss anything?

viscid needle
languid spire
#

not be carryBulletCount?

cobalt pike
#

Public intel reload Bullet Coomt; // Number of bullet reloads
public intent current BulletCount;// the number of bullets left in the bullet hole
public int maxBulletCiunt;//maximum number of possession bullets
public int carrybulletCount; // number of bullets currently owned

languid spire
#
if(currentGun.carryBulletCount >= currentGun.reloadBulletCoumt)

makes more sense with the rest of your code

cobalt pike
#

It's been resolved. Thank you

nimble apex
#

can you force the transform of an object to be const (immutable)?

#

theres some mysterious codes that trying to modify the position.y of a gameobject in scene

#

and i cant find the code

languid spire
#

is that not what happens when you mark a game object as static?

nimble apex
#

so , if i can force the transform to be a const, i can induce an error which terminals will tell me what is modifying it

#

ok i gonna try it

languid spire
#

not sure it will throw an exception though, probably not

nimble apex
#

its getting annoying it took 2 hrs already

#

it turns out that the spawn position is modifying by other scripts

#

the code are scattered all over the place

languid spire
#

sounds like very bad design

nimble apex
#

lemme give u an example

#

when handling server errors, you often have certain codes right?

#

each code is responsible for certain server error and maybe its handling

#

like http 404 is not found

#

its more like

case xxx
//do something
.... and keep going

#

we have these scattered across 10 scripts

languid spire
#

ouch

nimble apex
#

i asked my supervisor, why we scattered them everywhere

#
  1. some error code are exclusive to certain scripts, like the handling requires some local variables
  2. if u stuff all 100 error code into one place it is too long to read
#

but i found out , only 2-3 handling are exclusive, other 95+ errors can be gathered up

#

so its more on "stuff all 100 error code into one place it is too long to read"

languid spire
#

yep, sounds worse than 'bad design' sounds more like 'no design whatsoever'

nimble apex
#

theres no design actually, A in charge of this, he wrote there, then B take over and write more code there

brazen canyon
nimble apex
#

C and D and E keep going

languid spire
charred spoke
languid spire
#

if he doesn't want to drag the game object I would presume he doesn't want to drag the component either

brazen canyon
#

But since these scripts don't be in a same game object so ...

languid spire
#

let me give you 2 choices.

  1. Find the game object then getcomponent on that object
  2. Find the Component directly.
    As I said both of these options are bad
#

f.y.i, using the word 'just' should be banned when talking about programming

#

also why are you pinging me into a conversation, you should know by now that that is against server rules

brazen canyon
#

I'm so sorry, I "only" want you know what message I'm replying to

#

Why using the word "just" is illegal ?

languid spire
#

I did not say it is illegal, I said it should be banned. Why?

  1. It shows a complete lack of understanding of the complexities of the question asked
  2. It shows the user is expecting the solution to be 'easy'
nimble apex
#

damn i found it

#

spent 2.5 hrs, found a breakpoint to add my bandaid code

#

problem solved

languid spire
nimble apex
#

so whats the bandaid :

lets say because of some faulty code, objA stopped at 0,10,0 , but you want it to stop at 0, 9 ,0

brazen canyon
#

Ok I understood

nimble apex
#

so i just gonna find a breakpoint, and do

transform.position = new Vector3 (x,y-1,z);
#

i did similar things there

ebon robin
#

why does your project have 5 people coding the same module and no thorough planning

nimble apex
#

the project im working on is from cocos2d

#

6yrs ago, the team decided to migrate it to unity

cobalt pike
#

(0,-1,0)

nimble apex
#

at that time, no experience unity devs in the team, so all codes are messy

#

and faulty

ebon robin
#

6 years abandoned?

nimble apex
#

nope

#

so basically, the first dude came in, write the code down, when he left, second guys came in, top it with more code on the original place

#

3rd guy, do the same thing, and keeps on and on

languid spire
nimble apex
#

there are no standards for what code, what strucutre

#

basically u see what did ur ancestor do, and you do the same

#

its called tradition lmao

ebon robin
#

I think standards of a team should have functions with comments of what the function does, params, expected output

nimble apex
#

we have

#

but thats not enough

#

the project is relatively huge

pallid nymph
#

I'd say that's overrated for small teams working on an internal project 😅

nimble apex
#

we only have documents to tell what code and what system do xxxxxx

#

but we dont have a standard like , where the code should belong

ebon robin
#

well Im a solo dev so I cant really understand why projects hires so many different people

nimble apex
#

so if you have 20ppl worked on the code, you have 20 kinds of codestyle

brazen canyon
#

So how do I access a variable that's in another class and in different Game Object ? :(((

nimble apex
#

like var A , some ppl tend to put it on manager, some ppl tend to put it in other gameobject

ebon robin
#

just do a data manager for any object with big chunk of data

#

you shouldnt mind too much about premature optimization early on

pallid nymph
#

"inject" the component through editor or code - call its getter for the data that you want 🤷‍♂️ (or maybe I'm missing some details on why that's not the choice?)

ebon robin
#

make the variable public

languid spire
#

do you guys actually not read the questions?

pallid nymph
#

reading takes time, and we're kinda lazy, but with good hearts! 😅 ❤️

ebon robin
#

you could do find or a GameObject Manager

brazen canyon
languid spire
# brazen canyon But you said it was bad

yes, but it is the only solution to the your question as asked. So you need to ask yourself do you want to do it that way or do it the 'normal' way, but that is down to you not us

median vapor
#

Im not sure if this question fits in this chanell but i wanted to ask what are actually headers, I dont quite understand the concept.

ebon robin
#

like [Header("")]? its for seperating sections of code by naming them

median vapor
ebon robin
#

in editor specifically

languid spire
median vapor
#

I didnt notice it in the insepctor until now

idle agate
#

why is main camera in the vr project setup not showing

#

it just shows under everything and not where i put main camera

wintry quarry
#

Wdym by "under everything"? Show screenshots?

ebon robin
#

is there a way to get specific animation of an animator using name (string) without having to loop over all animations in animator

lean geyser
#

Hey so Im a bit baffled over a problem. Essentially, I have a prefab with a script attached to it to allow for shooting, but it only works if I use the prefab from hierarchy which for some odd reason is in red, and nothing happens if I reference it directly from assets

languid spire
icy junco
#

what is the best way to learn unity and C#

languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

languid spire
icy junco
#

thajnks

lilac hemlock
#

Can someone help me out please?

I have a missile system, which moves an object from starting point to an ending point. I want to have multiple animation curves (X, Y, Z) that changes they way the object flies from A to B. Also, there is a scale. Scaling means how much the curve values (displacement along the up axis) are scaled. However, I can't make the missile to follow the curves for some reason. I tried to change Y Cruve and set scale, but it only changed the height of the total path. MissileManager -> Move has the function for this.

https://gdl.space/evivugirup.cs
https://gdl.space/uwanuzurik.cs

teal viper
sharp bloom
#

I have some kind of a planet that I would like to be covered with these hexagons, I figured I could use "transform.lookat" to get the correct orientation for them, but how would I cover the whole thing automatically?

swift crag
#

You won't be able to neatly tile the surface with hexagons, but it'll work if you leave decently sized gaps

pallid nymph
#

There is a way for sure... and it involves having a few pentagons... I'm sure Google knows

sharp bloom
swift crag
#

I'm not sure about the math to calculate the points to instance on.

sharp bloom
#

I thought maybe spawning circles of different radiuses and spawn those hexagons along the circles

#

Idk if that makes any sense

pallid nymph
sharp bloom
#

Never heard of the Fibonacci sphere algorithm

#

I wish I had more time to study math cuz I suck at it

pallid nymph
sharp bloom
#

Okay I understand that tiling a sphere with hexagon is impossible but it doesn't need to be math-perfect

pallid nymph
#

my point is - look online, there's plenty of info about it 🙂 I'd help, but I haven't done it myself

#

aaaand yeah, that would have a few pentagons... but do you care? people sometimes "mask" them in some way

verbal dome
#

Using an icosphere and spawning a hexagon on each triangle could work too

sharp bloom
#

Since this is supposed to be a planet maybe I could have them as the polar caps or something

sharp bloom
#

Maybe just triangles are enough

ebon robin
#

the math bro ☠️

sharp bloom
#

Yea ikr

ebon robin
#

and then the debug part

sharp bloom
#

I could just copy shit but I like to understand the math behind whatever I'm doing

pallid nymph
#

I haven't tried it myself 😅 shouldn't be too bad (plus there should be a lot of info about all the stuff online...), but I can't say

#

I'll go ask ChatGPT to write it for me, lets see how that goes 😂 (don't do that at home!)

ebon robin
#

found it

#

blender tho not unity

#

but still

pallid nymph
#

math tends to be language agnostic 😛

rocky canyon
pallid nymph
#

well, ChatGPT gave me this awesome alien ship formation

#

it's not exactly a sphere of hexes, but I appreciate it! 😄

swift crag
sharp bloom
#

Ah yes

#

Sphere

pallid nymph
#

such sphere, much wow!

icy sluice
#

hello, im having problem translating this from position to rotation

Vector3 dampingFactor = new Vector3(
    Mathf.Max(0, 1 - Damping * Time.fixedDeltaTime),
    Mathf.Max(0, 1 - Damping * Time.fixedDeltaTime),
    Mathf.Max(0, 1 - Damping * Time.fixedDeltaTime)
);
Vector3 acceleration = (((referenceObject.transform.position - gameObject.transform.position) * Stiffness) - Vector3.Scale(currentVelocity, dampingFactor)) * Time.fixedDeltaTime;
currentVelocity = Vector3.Scale(currentVelocity, dampingFactor) + acceleration;
currentPos += currentVelocity * Time.fixedDeltaTime;

gameObject.transform.position = currentPos;
sharp bloom
#

Okay I think I got something going on here

#

Now I need to adjust the circle smaller and make many of them