#💻┃code-beginner

1 messages · Page 306 of 1

wintry quarry
#

yeah idk why you put in Values before

#

that's not at all what you wanted

#

that's an unordered collection of just the values in the dictionary

spiral narwhal
#

Ahhhh I see

#

makes sense

#

thx

deft grail
#

you are in 2D, your method is for 3D OnCollisionEnter, OnCollisionEnter2D

stuck sinew
#

ah thanks man i kiss your hearth

stuck sinew
frail star
#

is there a way to set a value to a list limit?

deft grail
#

it has a variable for that

frail star
#

if I want the list to have 15 objects can I preset that?

frail star
scarlet skiff
#

quick question is Time.time since the application started or since that scene ur in has loaded?

deft grail
frail star
deft grail
#

and you would do that by List<> myList = new List<>(15); if im not wrong

wintry quarry
wintry quarry
#

if the list is intended to be exactly a known length and not grow or shrink, you should just use an array instead

frail star
eternal needle
#

That will also still allow it to go over 15 elements, to be clear. You can also just create your own function which checks the length then adds if it's not at max capacity

wintry quarry
#

but yeah if you want to set a max size for your list you'll need to write a little wrapper code around it to enforce the limit

frail star
#

I can't add to an array at runtime can I

wintry quarry
#

You can set elements in the array at runtime

#

or create a new larger array at runtime

#

which is essentially how lists work

south sky
#

Yo guys I want to made the UI panel to fade its alpha to clear when it is awake, how do I do this?

deft grail
wintry quarry
#

use Update, a coroutine, or a Tween library.

#

or maybe an animation sure

deft grail
#

depends how much work and how quick you want it done, you can pick the way to do it

south sky
#

Yo anyone know what name I need to reference the audio source in code. Wanna add the volume to a slider

stuck sinew
#

i need help again please, my player shoots projetiles and the projetiles should be make damge on an objekt "Enemy" but nothing works how do i do it do someone know it or know about a good youtube video

ivory bobcat
#

Maybe show what you've tried

deft grail
#

both objects

stuck sinew
deft grail
stuck sinew
#

!code

eternal falconBOT
south sky
stuck sinew
deft grail
stuck sinew
#

i only made a script for the enemy i though that wenn the script says, when tag "Bullet" collide with Gameobjekt it will be destroy

deft grail
#
  1. IsTrigger , 2. Rigidbody2D, 3. the Tag
summer stump
#

Or CharacterController, but that is unlikely to be used for a projectile
At least hopefully hahaha

queen adder
#

//LogicScript.cs

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

public class LogicScript : MonoBehaviour
{
    public int playerScore;
    public TextMeshProUGUI scoreText;
    public GameObject gameOverScreen;
    public BirdScript birdIsAlive;

//increase score
    public void addScore(int scoreToAdd)
    {
        playerScore = playerScore + scoreToAdd;
        scoreText.text = playerScore.ToString();
    }

//restart game
    public void restartGame()
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    
    public void gameOver()
    {
        gameOverScreen.SetActive(true);
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && birdIsAlive == false)
        {
            restartGame();
        }
    }
}
//BirdScript.cs

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

public class BirdScript : MonoBehaviour
{
    public Rigidbody2D myRigidBody;
    public float flapStrength;
    public LogicScript logic;
    public bool birdIsAlive = true;
    public LogicScript gameOverScreen;


    // Start is called before the first frame update
    void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && birdIsAlive == true)
        {
            myRigidBody.velocity = Vector2.up * flapStrength;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        logic.gameOver();
        birdIsAlive = false;
    }
}
#

im trying to make the game reset if my player character is dead and if the spacebar is pressed and im having an issue where it resets every time i press the space bar. heres my code

#

sorry for huge block of code

deft grail
deft grail
eternal falconBOT
summer stump
deft grail
#

idk about that, but its 2D anyway so character controller wont work

summer stump
deft grail
summer stump
wintry quarry
# queen adder ```cs //LogicScript.cs using System.Collections; using System.Collections.Gene...

Ok so you confused the shit out of yourself with your variable name here:

public BirdScript birdIsAlive;```
You named your BirdScript reference birdIsAlive. So what you're actually doing with 
`&& birdIsAlive == false` is just checking if you have a valid reference to the bird script. Which apparently, you do not. So that's always true. What you should do is name your variable properly:
```cs
public BirdScript bird;```

Then when you want to check if it's alive you would be doing:
```cs
if (!bird.birdIsAlive)```
south sky
#

ANyone knwo how I can access volume in script?

deft grail
#

or just place a . and the IDE will autofill the possible solutions

south sky
#

I feel like you just said rtfm

deft grail
south sky
deft grail
eternal needle
#

to be fair, there are gonna be a lot of members associated with unity stuff. Just look through the docs

small mantle
#

I have this Stab Goblin Character. It is an Enemy, that when it gets close to the player will attack him. The issue is that the attack Collider that hits the Player does not keep colliding with the Player even though in the Goblin Script, it keeps disabling and enabling the Collider. This is the Collision script on the Player: private void OnTriggerEnter2D(Collider2D collision) { if (collision.TryGetComponent<GoblinKnife>(out GoblinKnife goblinScript) && !goblinScript.hasHit) { print("hit"); TakeDamage(goblinScript.knifeDamage); goblinScript.hasHit = true; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.TryGetComponent<GoblinKnife>(out GoblinKnife goblinScript)) { print("hit Exit"); playerScript.currentHealth -= goblinScript.knifeDamage; goblinScript.hasHit= false; } } THE KNIFE OBJECT IS THE OBJECT WITH THE COLLIDER*

deft grail
eternal falconBOT
stuck sinew
#

!code

eternal falconBOT
stuck sinew
wintry quarry
#

enabling and disabling a collider and using OnTriggerEnter is kinda... wacky

stuck sinew
small mantle
deft grail
wintry quarry
#

I'm saying replace disabling and enabling the collider with a direct physics query and running the damage code

summer stump
stuck sinew
small mantle
deft grail
summer stump
eternal needle
#

right now your playing is checking for what is damaging it, when you want to add more damage sources you always have to adjust this script. Instead, just make a script that can deal damage and attach it to other objects

wintry quarry
#

The goblin script should handle its own attacking behavior

small mantle
wintry quarry
#

what do you mean by disabling issue

#

I told you not to use disabling/enabling anything

#

just use a direct physics query instead of that

small mantle
wintry quarry
#

Don't have an "attack collider" at all

#

Use a direct physics query every time you want the goblin to attack

#

use an animation event for hooking the code up to your animation

small mantle
wintry quarry
#

or Physics.BoxCast

#

Or Physics.OverlapCapsule

#

whatever makes sense

small mantle
#

I'll try that. Thanks!

queen adder
# wintry quarry Ok so you confused the shit out of yourself with your variable name here: ```cs ...

the game doesn't reset every time i press the spacebar but now it doesn't work at all

https://hastebin.com/share/ayamagejam.csharp

i get this error message in unity

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

im assuming it means that the bird script isnt referenced at line 34 and thats why its not working but i referenced it with public BirdScript bird;

wintry quarry
#

which is you never assigned your reference

stuck sinew
wintry quarry
#

but yeah you need to assign the bird reference properly

queen adder
#

ah

#

sorry i started using unity like a week ago

wintry quarry
#

Yes you are struggling with the same thing almost every beginner struggles with - figuring out how references work

queen adder
wintry quarry
small mantle
queen adder
eternal needle
frosty lantern
#

can I make my object a child object to a "grouper" empty object without forcing the transforms to move together?

eternal needle
polar acorn
frosty lantern
#

wait no the grouper doesn't move

polar acorn
frosty lantern
#

it's just a folder object
oh so moving the child won't move the parent?

eternal needle
#

it is the other way around

frosty lantern
#

oh ok, i thought they were tied together and being a parent was for organization in code

#

cool

high oyster
#

im trying to make it so a walking sound plays when the player walks, i get no errors but no sound plays. could someone help? i wanted to incorporate the audio logic with my movement script but should i separate the two?

summer stump
high oyster
# summer stump You should generally try to separate things over combining. I am not gonna downl...

oh my bad ill put it in text


using UnityEngine.InputSystem;
using UnityEngine;

public class Movement2D : MonoBehaviour
{
   [SerializeField] private int speed = 3;
   private Rigidbody2D rb;
   private Animator animator;
   private Vector2 lastMovement = Vector2.zero;
   private bool hasStartedMoving = false; 
   public AudioSource AudioSource;
   public AudioClip walkSound;

   private void Awake()
   {
       rb = GetComponent<Rigidbody2D>();
       animator = GetComponent<Animator>();

       AudioSource.clip = walkSound;
       animator.SetFloat("X", 0f);
       animator.SetFloat("Y", -1f);
   }

   private void OnMovement(InputValue value)
   {
       Vector2 rawInput = value.Get<Vector2>();
       Vector2 movement = Vector2.zero;

       if (Mathf.Abs(rawInput.x) > Mathf.Abs(rawInput.y))
       {
           movement = new Vector2(rawInput.x, 0f);
       }
       else
       {
           movement = new Vector2(0f, rawInput.y);
       }

       if (movement.magnitude > 0.1f)
       {
           animator.SetBool("IsWalking", true);
           animator.SetFloat("X", movement.x);
           animator.SetFloat("Y", movement.y);
           lastMovement = movement.normalized;
           AudioSource.Play();
       }
       else
       {
           animator.SetBool("IsWalking", false);
       }

       rb.velocity = movement.normalized * speed;
   }

   private void FixedUpdate()
   {
       if (rb.velocity.magnitude < 0.01f && hasStartedMoving)
       {
           Vector2 roundedPosition = new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y));
           transform.position = roundedPosition;
           animator.SetFloat("X", lastMovement.x);
           animator.SetFloat("Y", lastMovement.y);
           AudioSource.Stop();
           hasStartedMoving = false;
       }
   }

}```
high oyster
#

ohhhhhhhh

#

i need to use events

summer stump
#

And yeah, events are useful, but not NECESSARY. It was just an idea

high oyster
#

thank you!

grizzled zealot
#

I'm currently using an array of <float, object> to list what kind of loot an enemy is going to drop. I already have 8 different loot items and I configure the array for each enemy.

I'm new to unity, but it seems to me that assigning all these values in the inspector is tedious, error-prone, and repetitive. Should I right away move away from 'programming' through the inspector and have these tables in an external file? I'm just thinking of balancing the game in the future and defining new loot types. It will be a nightmare to edit all of it through the inspector.

eternal needle
grizzled zealot
grizzled zealot
eternal needle
#

Assigning them to specific enemies wont be so fun though

grizzled zealot
#

I feel like making a large array with <enemyspawnid, Loot[]> in a well formatted way might provide an easier overview. Kinda like an excel table.

eternal needle
#

I would consider keeping a table purely for documentation purpose. In the actual game though, it's a lot nicer imo when you can just click on the enemy prefab, click on the assigned SO and see the values right there.

#

Also what about the case where 2 enemies share the same possible loot? Suddenly you have duplicated data, or duplicated ID

grizzled zealot
eternal needle
#

Im not entirely sure what you mean by read all the SOs and test for a monobehaviour.
Maybe share code

grizzled zealot
#

I have a factory (a singleton) which has a serializeable array of SOs. I drag all SOs into the list. When I spawn an object, the factory goes through the list of SOs to look whether it matches the spawnid and then instantiates an object.

sleek stone
#

so guys before this script started working but now it just broke all of a sudden and the camera rotates on the X axis about 90 degrees upward into the sky
anyone might know the issue
oh and when I forcefully reset the postion to 0 while in the game the camera starts rising back up to the 90 degree postion so like it doesnt let me change i

eternal needle
grizzled zealot
#

Sure, but a dictionary is not visible in the inspector (unless I buy Odin). With an array, I just select all SOs in the directory and drag them onto the factory.

#

The performance improvement is negligible unless you spawn often or have thousands of items.

eternal needle
eternal needle
sleek stone
grizzled zealot
eternal needle
sleek stone
eternal needle
grizzled zealot
eternal needle
eternal needle
#

With an excel sheet, you do not have a hard link between enemy ID and the prefab in game. There just so happens to be an ID in the sheet that matches the ID in game.
With drag and drop, there is a hard link

grizzled zealot
eternal needle
#

Right now my loot tables are pretty simple, so I wont really need to edit it much

grizzled zealot
eternal needle
oblique herald
#

Hey guys, I am stuck on a problem, where currently I want to have a tmp_inputfield (password) pop up to collect input from a user when I get closer to the object (OnCollisionEnter2D), I tried using password.gameObject.SetActive(true) but it said NullRefException, I always tried using password.ActivateInputField(); and it still is the same error, am I wrong for using those lines of code or is there just some referencing problem in my code

#
    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.gameObject.tag == "Player") {
            vaultText.gameObject.SetActive(true);
            password.ActivateInputField();
        }
    }

this is the code for OnCollisionEnter2D
where vaultText is just a tip for telling user the vault is locked, and it works and does show up,
but the lower one password.ActivateInputField(); doesnt

rare basin
#

vaultText or password is not referenced, it's null

oblique herald
#
    [SerializeField]
    public TMP_Text vaultText;

    [SerializeField]
    public TMP_InputField password;

how should I reference it then if you dont mind me asking

rare basin
#

you don't need to make it [SerializeField] if its alerady public

#

you need to drag&drop it in the inspector

oblique herald
#

i did

rare basin
#
if (collision.gameObject.tag == "Player") {
    Debug.Log($"Vault text: {vaultText}");
    Debug.Log($"Passowrd: {password}");
    vaultText.gameObject.SetActive(true);
    password.ActivateInputField();
}
#

show the debug logs

oblique herald
#

Vault text: vaultTip (TMPro.TextMeshProUGUI)
UnityEngine.Debug:Log (object)
vaultTip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/Script/vaultTip.cs:26)

Password:
UnityEngine.Debug:Log (object)
vaultTip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/Script/vaultTip.cs:27)

NullReferenceException: Object reference not set to an instance of an object
vaultTip.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Script/vaultTip.cs:29)

rare basin
#

what is line 29

oblique herald
#

password.ActivateInputField();

rare basin
#

the password is null

#

do you see a reference to password in the inspector

#

in runtime?

oblique herald
#

oh no

#

no it doesnt show in runtime

#

wait why is that..

rare basin
#

you probably override the reference somewhere

#

like in Start or Awake

oblique herald
#
    public void Start() {
        vaultText.gameObject.SetActive(false);
        vault = this.GetComponent<BoxCollider2D>();

        password.DeactivateInputField();
        password = this.GetComponent<TMP_InputField>();
    }
rare basin
#

yea, you dont mix it

#

you either drag&drop it in the inspector

#

or you reference it in the start/awake
unless you know what you're doing

oblique herald
#

okay ill try that

#

worked like charm. thanks.

near wadi
rare basin
#

it's free and CC0 license

#

and it looks like this (this is GenericDictionary<enum,Vector2>)

hazy minnow
#

!code

eternal falconBOT
hazy minnow
#
using System.Collections.Generic;
using UnityEngine;

public class ProjectileScript : MonoBehaviour
{
    public Rigidbody2D theSeedBrain;
    public float deadZone = -17;
    public float timer = 0;
    public float coolDown = 5;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (timer < coolDown)
        {
            timer = timer + Time.deltaTime;
        }
        else 
        {
            addSeed();
            timer = 0;
        }
        if (transform.position.y < deadZone)
        {
            Destroy(gameObject);
        }
    }
    public void addSeed()
    {
        Instantiate(theSeedBrain, new Vector3(0, -2, 0), transform.rotation);
    }
}
``` Why my code doesn't work
wintry quarry
hazy minnow
#

well why when the timer reach 5 it doesn't Instantiate the object

elder axle
#

I have tried Everything i cant get the game over text which uses text mesh pro to pure white or any other light colors.

wintry quarry
wintry quarry
elder axle
wintry quarry
hexed terrace
vast crane
#

Someone please help me! My hand colliders was working but it won't anymore. When I make my hand press a button it doesn't work anymore which is strange.

wise saddle
#

hello

#

I recently returned to Unity and since then I have had a lot of bugs since the new versions

hazy minnow
#

How do I make a multiplayer systeme with 1 player that can host a party and another player can join by entering his ip adresse

teal viper
hazy minnow
#

ok

wise saddle
hexed terrace
#

you haven't assigned the rigidbody, but you're trying to use it

hazy minnow
#

Another question how to make when a collider touch another collider this one goes in the other direction

wise saddle
#

or in my script or inspector

hexed terrace
teal viper
wise saddle
#

What

burnt vapor
#

This is not related to your code but instead the editor inspector

wise saddle
#

thank you, and how do I do it in the inspector

hexed terrace
#

This is really basic stuff, you need to go to !learn and follow the beginner tuts

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wise saddle
#

OK GREAT THANK YOU GENTLEMEN

exotic hazel
#

Hi So i am using emmision color to give a glow effect to my lights.But i want to switch up the lught in code.I can just use the Color to switch up the albedo but how do i mention the emmision color so the color of the glow changes

wise saddle
#

I had my file dragged into the other one, sorry, I didn't see it. No more error message when I don't put it I still can't move my character.

burnt vapor
#

Consider logging the rigidbody's velocity after you update it

void notch
exotic hazel
#

Thank you

wise saddle
#

OK, thank you very well that's just it, it works thank you

exotic hazel
#

!code

eternal falconBOT
exotic hazel
#
void Update()
{
    StartCoroutine(ChangeColor());
}
IEnumerator ChangeColor()
{
    yield return new WaitForSeconds(3f);
    CurrentColor.color = CurrentColor.SetColor("_EmissiveColor",  Color.Lerp(CurrentColor.color, colors[Index], time  * Time.deltaTime));
    Index +=1;
}
void ResetIndex()
{
    if(Index == colors.Length)
    {
        Index = 0;
    }
}
}



Want to do this but theres an error

#

Color.Lerp(CurrentColor.color, colors[Index], time * Time.deltaTime));
This line

burnt vapor
#

So share the error

exotic hazel
#

oh right

wintry quarry
#

I would guess SetColor returns void

exotic hazel
#

yea

wintry quarry
#

Yeah why are you doing Color = SetColor

#

That doesn't make sense

#

I would expect one or the other

exotic hazel
#

oh wait it shoul be nothing there

burnt vapor
#

Basic c# questions like these can be avoided if you just learn c# before you even consider using Unity

#

This channel is not for these things

hazy minnow
#

number = Random.Range(1, 2); will the number be 1 or 2 ?

wintry quarry
#

Read the docs

exotic hazel
burnt vapor
#

Always read the error properly because most of the time it clearly explains the issue

exotic hazel
#

I just did something very wrong cus unity just crashed when the code was supposed to be run

hexed terrace
copper lotus
#

I'm creating a game, and would love to invite other people onto the project. But what is the best way to colaborate with other people and manage all the code? Google is sending me in so many directions that i'm honestly lost on what to actually choose (Github, Unity Teams, Unity DevOps, Unity Cloud, Perforce, ...).
What exactly should I be looking into (Free would be preferable)

swift elbow
#

Git/GitHub is widely used

copper lotus
#

I'll just use that then, thanks

hazy minnow
#
 {
     transform.position = Vector2(0, 0);
 }``` Why is this incorrect
languid spire
hazy minnow
#

oh ok

spiral narwhal
#

Why can Unity not serialise nullable enumeration constants?

#

i.e.

        [SerializeField] private DiceType? _requiredDiceType;
languid spire
spiral narwhal
#

Lool

rare basin
#

you can make a nullable wrapper<T>

#

i've used that workaround for some time

timber tide
#

just use classes :)

hazy minnow
#
    {
        if (collision.gameObject.layer == 3)
        {
            circle.initiPos();
            circle.leftOrRight();
            Debug.Log("YeaRunning");
        }
    }
}``` ```public void initiPos()
{
    transform.position = new Vector2(0, 0);
}``` Why the circle don't go to the position
rare basin
#

is the method being called

#

and that debug log printed?

hazy minnow
#

Yes the debug log is printed

rare basin
#

then the initiPos() is called aswell on circle instance

#

public void initiPos()
{
transform.position = new Vector2(0, 0);
Debug.Log($"Position: {transform.position}");
}

#

show that debug log

hazy minnow
#

Position: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
CircleLogic:initiPos () (at Assets/CircleLogic.cs:20)
Points:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Points.cs:24)

rare basin
#

then it is 0,0,0

#

and the method works correctly

#

you are probably overriting the transform.position somewhere else

hazy minnow
#

maybe

gaunt holly
#

i installed the input system package. in my script, i initialized a var: "public InputAction cameraControls;". back in the editor, i added a "CameraHorizontal" action and bound it to Negative/Positive. then i enabled it "cameraControls.Enable();". but how do I access this action?

hazy minnow
#

I corrected the script

cosmic dagger
tender stag
#

Script A:

#

Script B:

hazy minnow
#

My code was wrong beause I forgot that the script wasn't in the object that's why it didn't worked

tender stag
#

which means this check is useless

hazy minnow
#

How do I change the name of a script ?

cosmic dagger
hazy minnow
#

ok

tender stag
#

i dont know how to phrase it

#

but pretty much Script B is still called when its not supposed to

#

because of the order

#

which causes me to drop an item im holding

cosmic dagger
# tender stag

both codes run in Update. unfortunately, you can not determine which update runs first (unless you change the script execution order for both scripts, so that script B always executes after script A) . . .

tender stag
#

so whats my best bet

#

i could just call both drop functions in 1 script

cosmic dagger
tender stag
#

or i could just do this right?

cosmic dagger
#

whoa, a question about date time or smth just disappeared . . .

tender stag
#

would there be a way around this?

cosmic dagger
cosmic dagger
tender stag
#

its hard for me to explain

charred spoke
#

Why not add a &&inventoryIsOpen check to the shoulder part ?

#

If you want to drop from both states with G

atomic yew
#

how to change size of list with code?

hazy minnow
#

How to make that the ball don't go just on the x axe and how to make that the player don't slide until it hit a collider

#
  {
      if (Input.GetKeyDown(KeyCode.W) == true)
      {
          player1.velocity = Vector2.up * speedUp;
      }

      if (Input.GetKeyDown(KeyCode.S) == true)
      {
          player1.velocity = Vector2.down * speedDown;
      }
      if (Input.GetKeyDown(KeyCode.UpArrow) == true)
      {
          player2.velocity = Vector2.up * speedUp;
      }

      if (Input.GetKeyDown(KeyCode.DownArrow) == true)
      {
          player2.velocity = Vector2.down * speedDown;
      }
  }```
hazy minnow
#
{
    rNumber();
    if (right == true)
    {
        circleRig.velocity = Vector2.right * circleSpeed;
    }
    else
    {
        circleRig.velocity = Vector2.left * circleSpeed;
    }
}
public void rNumber() 
{
    number = Random.Range(1, 3);
    if (number == 1)
    {
        right = true;
    }
    else
    {
        right = false;
    }

}```
deft grail
hazy minnow
#

ok I will try

cosmic dagger
atomic yew
cosmic dagger
#

you can add elements to the list with code, but an array is a set size . . .

#

but you can change the size of an array from the inspector . . .

atomic yew
#

public class ItemDatas
{
public List<ItemData> dataItems = new List<ItemData>();
}

#

this is a list

#

it isn't an array

cosmic dagger
#

add a null reference in Start and check if it changhes . . .

polar acorn
cosmic dagger
hazy minnow
#

how to make when I add velocity to an object it doesn't go in the direction without stoping

wintry quarry
#

if you want it to stop, change the velocity again

atomic yew
wintry quarry
#

or add a force in the opposite direction

hazy minnow
#

ok

atomic yew
main karma
cosmic dagger
burnt vapor
#

Initializing a list accepts a single integer as a parameter which indicates the size

#

Same as how any other constructor works with parameters

hazy minnow
#
        {
            player1.velocity = Vector2.up * speedUp;
        }
        else
        {
            player1.velocity = 0;
        }```Why it don't work
burnt vapor
hazy minnow
#

the else part

burnt vapor
#

Consider logging the player's velocity and seeing what happends to it

#

Also consider logging the GetKeyDown statement and see if this gets called

#

As in, check if the actual method returns true/false

wintry quarry
#

player1.velocity = 0; this doesn't make sense

hazy minnow
#

so how do I make that the velocity stop

wintry quarry
#

velocity is a Vector3

#

set it to a vector with 0 on all axes, e.g. Vector3.zero

atomic yew
#

public class ItemDatas
{
public List<ItemData> dataItems[210];
} This isn't work

#

public class ItemDatas
{
public List<ItemData> dataItems = new List<ItemData>(210);
} This isn't work

#

void Start()
{
el = Player.GetComponent<El>();
er = GameObject.FindGameObjectWithTag("Envanter").GetComponent<Envanter>();

/*for(int i = 0; i < 210; i++)
{
    itemDatas.dataItems.Add(null);
}*/
itemDatas.dataItems.Capacity = 100;

StartCoroutine(ItemKaydetme1Cor());

} This isn't work

wintry quarry
eternal falconBOT
wintry quarry
#

and explain what "isn't work" means exactly.

atomic yew
#

What should I do to make empty instead of null value?

wintry quarry
#

make what empty

atomic yew
atomic yew
wintry quarry
atomic yew
wintry quarry
#

for a reference type like this

#

use an array sir

atomic yew
wintry quarry
#

Yes I saw the code

#

you don't need to show it again

#

Again you should really just use an array

#
ItemData[] items;

void Awake() {
  items = new ItemData[210];
}```
#

no need for a loop

atomic yew
ionic river
#

Hi, I'd like my character to fire a projectile at the target (the player) and move towards it. I've tried to do this but if I ever give my projectile an angle and apply the direction projectile.transform.position - target.transform.position then the arrow no longer goes in the right direction, if I remove the angle it goes in the right direction but is turned the wrong way. (I'm working on a 3D project)

#

what I've explained is from the enemy's POV

hazy minnow
#

Bro I thought the only way to move the player is to use velocity💀

summer stump
#

Here's all the main ways of moving

#

There are more too

hazy minnow
#

thx

#

Next time I will add mouvement I will read this

copper lotus
# summer stump

You have any more of those that help with decision making? Because damn I love me some diagrams

summer stump
copper lotus
#

Creating my class diagram but I'm getting a feeling that my thinking is going to create some problems later on. Any feedback? (Still WIP btw)

#

Basing my game on kingdom new crowns, if that makes it easier to give feedback

frosty hound
#

@queen adder Please don't crosspost. Also this is a programming channel.

hollow slate
#

good stuff.

hollow slate
burnt vapor
hollow slate
unique idol
#

Hello, I don't know if it's beginner question or maybe general / advanced, but I need help with chunks or cache.
I have tilemap 1500 width x 600 height. I created loading system which is loading all data between player position + and - 150 tiles every 5 seconds. It's ok when it's not unloading anything, but when it's going to unload tiles then it's lagging short amount of time, but still lagging. Video and picture should help to understand my problem.

The question is - how to optimize it more, remove unloader or it's possible to do it better? Maybe make similar option like load method has?

teal viper
unique idol
#

When I loaded all the tiles my ram goes high and unity wasn't going smooth.

#

Laggs everywhere.

teal viper
#

Are you using the unity tilemaps?

unique idol
#

Yes, unity tilemaps modified by extending TileBase.

teal viper
#

Tiles outside the camera frustum aren't rendered, so they shouldn't contribute to lag. And ram shouldn't be a problem. You're probably holding the "unloaded" tiles in memory anyway.

#

Basically, it's a classical case of premature optimization

unique idol
#

Well, it's 2 dimensional array with enums.

#

After player destroy block it's saved to array with null.

#

If player place any block - enum with tile information

teal viper
#

I mean, if you're planning to have an infinite level, that might be needed, but if you have a limited map, I'd just have it all in the tilemap at the same time.

#

Anyways, the answer to your original question is the same: profile the game to see what exactly causes the lag spikes.

unique idol
#

Ok, I'll try profiler

#

It will be limited map, but after loading entire map it caused lag, maybe your option will tell me more.

teal viper
#

Though, I'm going to sleep soon, so maybe someone else would be able to help you.

unique idol
#

Thanks.

#

Good night.

hollow slate
#

good night :)

timber tide
#

or do some lazy loading

unique idol
#

@timber tide I already did it, when I loaded entire map it took like 4 GB, when I loaded parts it took only 100 MB.

hollow slate
#

feels like the issue lies elsewhere though. It shouldn't be very intensive just to have those things on screen no?

#

4GB goddamn

#

nevermind.

unique idol
#

When I made map bigger, like 5000x2000 it took 8 GB

hollow slate
#

what are you LOADING?

unique idol
#

Tilemap 😄

timber tide
#

Havent really used unity's tilemap but this is why you chunk

unique idol
#

Tilemap took everything, and it's only loading script.

#

And it's why I made loader part by part.

#

Please check the video, it's after split load.

hollow slate
#

is it a terraria-type environment you're making?

unique idol
#

Yes.

wraith valley
#

Hello, my raycast doesn`t work

    // Update is called once per frame
    void Update()
    {
        if (h != null)
        {

            h = Input.GetAxis("Horizontal");
            Vector3 movement = Vector2.right * h * speed * Time.deltaTime;
            transform.position += movement;
            if (h >= 0.1)
            {
                animator.Play("BlackWerewolfWalk");
                GetComponent<SpriteRenderer>().flipX = false;
            }
            else if (h <= -0.1)
            {
                animator.Play("BlackWerewolfWalk");

                GetComponent<SpriteRenderer>().flipX = true;
            }

            else
            {
                animator.Play("BlackWerewolfIdle");
            }
        }
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            // transform.position = new Vector2(transform.position.x, transform.position.y * jumpForce *Time.deltaTime);
            rb2d.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }
        Jump();
    }

    void Jump()
    {
        Vector2 startPoint = transform.position;
        Vector2 endPoint = Vector2.down;
        float rangePoint = 0.1f;

        RaycastHit2D hitGround2D = Physics2D.Raycast(startPoint, endPoint, rangePoint);

        if (hitGround2D.collider != null)
        {
            if (hitGround2D.collider.CompareTag("Ground"))
            {
                isGround = true;
                Debug.Log("Ground");
            }
        }
        else
        {
            isGround = false;
            Debug.Log("Jump");
        }
    }
}
hollow slate
#

check where the raycast is going

#

use gizmos to see in the scene where the raycast is going

wraith valley
#

Clear too

hollow slate
#

Debug.DrawRay()

#

pretty useful for seeing it in the scene

wraith valley
#
 Debug.DrawRay(hitGround2D);
hollow slate
#

more like Debug.DrawRay(startPoint, endPoint, Color.blue, 5f);

#

something like that

#

if it happens in Update you can remove the 5f

hollow slate
#

maybe Debug.DrawRay(startPoint, endPoint * rangePoint, Color.blue, 5f);

#

that gives you the raycast you're doing.

#

keep in mind 2D ignores z to some extent.

half egret
#

I think your raycast isn't working because of the direction...let me double check

verbal dome
#

Yeah it takes a position+direction not two positions

hollow slate
#

you rotating your character?

#

direction should be fine.

verbal dome
half egret
#

Oh I'm dummy yeah

mild furnace
#

Any suggestions for keeping track player aggro, total damage dealt, and other metrics in a multiplayer game?
When you deal damage to an enemy or become detected by it, id like to see if its registered to a list and record metrics.
Keeping track of things like total damage dealt would be important for things like qualifying for item drops, while aggro could fluctuate and probably be reduced by a % on an interval.

#

Would it be dumb to use a nullable data type as keys in a dictionary?

#

For instance dictionary where key is reference to player networked object, and value would be context info

wintry quarry
mild furnace
#

So that you can easilly check aggroList.Contains(playerId) when you are handling detection checks and things lk that

#

Might be better to do it manually and loop through

wintry quarry
#

but why does it need to be nullable?

mild furnace
#

It doesnt exactly need to be,
I like using a reference to their NetworkIdentity component to easilly handle things on the server side

#

Using mirror in my case

#

Theres no guarantee that the gameobject might get destroyed though

#

Or moved to another scene

wintry quarry
#

definitely just use the int playerId or whatever as the key

mild furnace
#

I believe I can do that with NetworkIdentities in mirror

wintry quarry
#

a nullable int would mean your key is... null? Which means you have no idea what player it's for.

mild furnace
#

Havent had to til now though

#

Well yeah, that would be a case where I want to ignore/remove them from the list

wraith valley
#
void Jump()
    {
        Vector2 startPoint = transform.position;
        Vector2 endPoint = Vector2.down;
        float rangePoint = 0.1f;

        RaycastHit2D hitGround2D = Physics2D.Raycast(startPoint, endPoint, rangePoint);

        if (hitGround2D.collider != null)
        {
            if (hitGround2D.collider.CompareTag("Ground"))
            {
                isGround = true;
                Debug.Log("Ground");
                Debug.DrawRay(startPoint, endPoint, Color.green, rangePoint);
            }
        }
        else
        {
            isGround = false;
            Debug.Log("Jump");
            Debug.DrawRay(startPoint, endPoint, Color.red, rangePoint);
        }
    }
#

Only green

polar acorn
#

Also, endPoint is not a good name for what is a direction and not a point

wraith valley
wintry quarry
#

rangePoint is also...? why not just range?

polar acorn
wraith valley
wintry quarry
#

wat?

polar acorn
wraith valley
polar acorn
wintry quarry
#

what does tha thave to do with the name of the variable rangePoint?

wintry quarry
#

rangePoint implies it is a point in space or something.

#

It's just a range.

polar acorn
#

rangePoint is not a point. It should probably just be called range

wraith valley
#
if (hitGround2D.collider != null) { Debug.Log("yes"); }
        else { Debug.Log("no"); }
summer stump
#

Which is useless

polar acorn
wraith valley
#
if (hitGround2D.collider != null && hitGround2D.collider.CompareTag("Ground"))
    {
        
        Debug.Log("Hit Ground: " + hitGround2D.collider.gameObject.name);

    }
#

This?

polar acorn
#

we specifically are trying to find the thing that isn't ground that you're hitting

#

this, again, doesn't tell us any new information

wraith valley
#

I don't understand what you mean

polar acorn
#

That's it

summer stump
#

Don't have the && part

polar acorn
#

don't check for anything else on the object

#

just unconditionally log the thing the raycast hits

#

I literally told you exactly what to do. Why did you go and change everything else?

wraith valley
#

I don`t know how to do this

#

Raycast always hitting

polar acorn
wraith valley
#

I don`t know why

polar acorn
wraith valley
#
void Update()
{
    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 10f);
    
    if (hit.collider != null)
    {
        GameObject hitObject = hit.collider.gameObject;
        
        
        string objectName = hitObject.name;
        
        
        Debug.Log("Hit object name: " + objectName);
        
       
    }
}
polar acorn
#

This is going to tell you what this ray is hitting but that's not the ray you care about so why are you checking this one?

wraith valley
#

What?

#

This is my character

polar acorn
# wraith valley

So whatever ray you've put this log in is hitting BlackWerewolf

wraith valley
#

But that`s not object

#

This is my character

polar acorn
#

What do you mean "that's not object"

wraith valley
hollow slate
#

so, the ray is hitting your character instead of the ground then?

#

you would want to seperate layers, so that the ray ignores your character

wraith valley
#

In inspector?

hollow slate
#

every GameObject has a Layer, and it's used for many things

#

in this case you'd use it to ignore the physics of the player when raycasting.

#

Create a layer called "Player", and make sure the raycast uses a LayerMask.

polar acorn
hollow slate
#

also works. Might want to do both.

hollow slate
#

found that I more often wanted to interact with things than not ya know?

wraith valley
#

Raycast is lost

hollow slate
#

it's... lost?

wraith valley
#

I don`t see its

swift elbow
wraith valley
polar acorn
hollow slate
#

you mean the Debug.DrawRay?

wraith valley
hollow slate
#

strange... maybe it only runs when the raycast hits something. Make sure it runs every Update regardless of what happens.

#

either way, google on how to set up LayerMasks with raycasts and objects - it's very useful to know :)

wraith valley
#
 if (hitGround2D.collider != null)
        {
            if (hitGround2D.collider.CompareTag("Ground"))
            {
                isGround = true;
                Debug.Log("Ground");
                Debug.DrawRay(startPoint, endPoint, Color.green, rangeWerewolf);
                GameObject gameobj = hitGround2D.collider.gameObject;
                Debug.Log(gameobj.name);
            }
        }
        else
        {
            isGround = false;
            Debug.Log("Jump");
            Debug.DrawRay(startPoint, endPoint, Color.red, rangeWerewolf);
        }
#

Debug.Log doesn`t work too

polar acorn
polar acorn
#

that was the whole point of the log

wraith valley
hollow slate
#

put the Debug.DrawRay in front of the first if

#

have it always run

#

don't put it behind an else

wraith valley
hollow slate
#

also, due to how raycasts work (at least the one you're using), it stops after it hits anything.
What's happening is that the ray is hitting your character (because it starts inside it), and never continues towards the ground.

polar acorn
wraith valley
#

But doesn`t work

polar acorn
hollow slate
#

I told you why.

polar acorn
#

Do you have any idea at all what you're doing

hollow slate
#

you need to use Layers.

summer stump
hollow slate
#

Ignore the player with the raycast.

wraith valley
#

Just raycast

wraith valley
hollow slate
#

see, now we see the beam again.

wraith valley
#

I`ll watch

polar acorn
#

it's working right there

hollow slate
#

see how the beam starts inside the player?

polar acorn
#

the red ray is visible

hollow slate
#

this means that the player is being hit.

wraith valley
hollow slate
#

Because of this, the ground is never hit. The player is blocking the ground.

polar acorn
#

And now you can see it

verbal dome
#

Unless 2D is different

polar acorn
hollow slate
#

I think it is.

verbal dome
#

I see

hollow slate
#

@wraith valley Do you understand what's happening?
The red line starts from the top and ends at the bottom. The thing is, it's not actually what your raycast is doing. As soon as the player is hit (the ray starts from the player, so it's instantly hit) the raycast stops traveling.
It never hits the ground, because the player is in the way. You need to set up LayerMasks to fix this issue.

frosty lantern
#

So using getname isn't working very well for me:

enum colorPiece {dark = -1,  light = 1};
[SerializeField] int startSide;
void Start()
{
    color = (colorPiece)startSide;
    kingFolder = new GameObject(System.Enum.GetName(typeof(colorPiece), color) + "King Folder");

}
polar acorn
frosty lantern
#

I want it to say dark king folder

wraith valley
hollow slate
#

Raycasts hit colliders.

#

The player has a collider yes?

wraith valley
hollow slate
#

so the raycast hits the player, and then stops.

wraith valley
#

But collider without tag Ground

hollow slate
#

It's like a lazer pointer, it doesn't go through objects, it stops when it hits them.

#

yes, but tags are different from LayerMasks.

#

Tags are a type of name for an object. A LayerMask actually affects the way physics works on objects

#

the issue is that we're hitting the player ->

wraith valley
hollow slate
#

then we check for the tag on the player

summer stump
hollow slate
#

we don't care what the player's tag is right? We want to know about the ground below the player.

wraith valley
polar acorn
wraith valley
#

Already working

summer stump
wraith valley
hollow slate
#

@wraith valley Do you understand why it's working now?
You can see where the ray is yes?

hollow slate
#

the ray isn't colliding with the player anymore, so it checks the ground like we want to

wraith valley
#

Collider don`t colliding with ray

hollow slate
#

the thing is, we don't want the werewolf underground right?

summer stump
hollow slate
#

yes!

hollow slate
wraith valley
hollow slate
#

LayerMasks Brian.

summer stump
#

Ah, I thought you switched from tag to layer

hollow slate
#

I want him to.

wraith valley
hollow slate
#

YES!

summer stump
# wraith valley What?

You need to google a guide on layers and layermasks. The docs are good. Maybe look up a video too

hollow slate
#

exactly this

wraith valley
#

I`d rather to watch video

hollow slate
#

yes, I agree.

#

Video is usually easier and better.

polar acorn
wraith valley
hollow slate
hollow slate
#

LayerMasks are a bit more complicated, but I'm sure you'll get the hang of it

wraith valley
#

I did that

#

When readed friend`s code

#

Easily write from 0

hollow slate
#

https://www.youtube.com/watch?v=uDYE3RFMNzk
Watch this all the way to 7:30 and you should have a better understanding :)

✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=uDYE3RFMNzk
Let's look at Layers and Bitmasks to see how they work. We can manipulate Physics interactions and what a Camera sees.

If you have any questions post them in the comments and I'll do my best to answer them.

🔔 Subscribe for more Unity Tutorials https://...

▶ Play video
hollow slate
#

it covers all three things you need to know.

wraith valley
#

Oh...🗿

hollow slate
#

yeah, that's a part of it. I think he mentions it in the video.

frosty lantern
wraith valley
#

I saw Code Monkey

#

He has games in Unity

polar acorn
hollow slate
frosty lantern
hollow slate
#

Debug.Log(color);
check what it is

#

before the operation.

hollow slate
spiral narwhal
#

In C#, is there a way to automatically have a class create an instance of itself?

This is my current version, which is rather error-prone, and it feels like there must be a pattern that does it better:

        public void StartNewGame()
        {
            _serviceManager = new();

            new ActionService();
            new CombatService();
            new MapService();
            new PlayerService();
            new RNGService();
            new GameTaskService();
            new GamePhaseService();
            new TurnService();

            _serviceManager.InitAll();
        }
frosty lantern
#

It's definitely the assigning to the color

polar acorn
frosty lantern
#

maybe the cast was wrong?

polar acorn
#

those would end up being blank

frosty lantern
#

yeah the start side is correct but the assignment to color turns to 0

#

wait the assignment nees to be befors instantiatefolders my b

#

got it, the color=(colorpiece)startside needed to be done before the initialize pieces call

scarlet skiff
#

shouldnt this activate the gameobject?

#

like tick the little box here

rich adder
scarlet skiff
#

it should be

#

the animation does play

#

i can see it playing

#

but the landmine stays inactive

rich adder
#

also whats up with that internal landMine is probably null too

scarlet skiff
#

it shouldnt be null

scarlet skiff
#

here is full

#

its their spawner

#

wait

#

nvm i think i know the problem

obtuse veldt
#

Hi, I encountered this problem..., I tried to replace the "collisionInfo" with "triggerinfo", and unsurprisingly it didn't work. May someone help me? Thanks

rich adder
wintry quarry
#

You're missing the parameter for the method

#

also the parameter would directly be the collider for this

#

From a basic C# standpoint - you can only use variables that exist in the scope 😄

scarlet skiff
#

the issue was that i had forgotten a previous attempt where basically i had it disable the landmine in update lol, anyways solved 👍

rich adder
#

it even has proper example with Trigger

stuck palm
#
IEnumerator WinSequence()
    {
        if (lastPlace != null)
        {
            Character player = Instantiate(lastPlace.character.characterPrefab, lastPlaceSpawn.position,
                Quaternion.identity).GetComponent<Character>();
            InitPlayers();
            player.playerShape.material = lastPlace.character.color[lastPlace.controller.colorNum];
            yield return new WaitForSeconds(1);
        }

Why is this code block running when last place has nothing in it?

hollow slate
#

I guess Last Place itself isn't null - because it seems to be a container of some sort. Does that sound right?

#

it looks to be from the inspector at least.

stuck palm
#

last place and the other places are of type Win character

public class WinCharacter
{
    public CharacterInfo character;
    public MatchPlayerData match;
    public PlayerInputController controller;
}
hollow slate
#

And what's WinCharacter?

#

oh

#

yeah, it exists.

rich adder
#

its serialized in the inspector

stuck palm
#

oh wait i see yeah

hollow slate
#

so the WinCharacter itself actually exists, but you need to check WinCharacter.character != null

stuck palm
#

is it because of this?

hollow slate
#

that should be fine.

#

you only care if the character exists no?

rich adder
#

Unity will automatically do new() on POCOs embedded(public/serializefield) as Serializable

stuck palm
#

okay, i'll remove that then

#

let me test now

rich adder
#

if(lastPlace.character == null) return

stuck palm
rich adder
stuck palm
#

oh lmao

rich adder
#

like class/struct are pocos

dusty canopy
#

So I dont know if this is allowed here but im at my wits end. If i make a public field in a script that is inside an animator. So an animator object, why cant I drag anything into it?

#

it wont let me drag any of my animators into it

#

and its really driving me up the wall

wintry quarry
dusty canopy
#

Animators

wintry quarry
#

from where?

dusty canopy
#

my hierarchy. Objects that have animations on them

polar acorn
wintry quarry
#

Assets cannot reference scene objects

dusty canopy
#

ah right. How do i get around that then?

wintry quarry
#

Since this is a StateMachineBehaviour (right? that's how scripts attached to animatins work I think?) you get access to the Animator in every single callback in the StateMachineBehaviour

dusty canopy
#

How do I change a param in another animator in this animator

#

if i cant reference it

wintry quarry
#

I don't understand what that question means

dusty canopy
#

I have other animators that I want to reference so I can change their parameters

wintry quarry
#

You get the animator reference in the callbacks

dusty canopy
#

not the current running animator

wintry quarry
#

for the animator this animation is attached to

dusty canopy
#

other ones

wintry quarry
#

You'll ahve to get the reference programmatically somehow

#

Either by proxying through some other script attached to the object

#

or some other way

#

if you want to set it in the inspector, using a proxy MonoBehaviour may be the easiest thing

#

For example:

    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        MyProxyScript ex = animator.GetComponent<MyProxyScript>();
        Animator someOtherAnimator = ex.SomeAnimator;
    }```
dusty canopy
#

I dont understand "MyProxyScript". What type would that actually be lol.

#

oh wait thatd be a new script or smth

#

cos its a class type

polar acorn
wintry quarry
#

It would derive from MonoBehaviour

south mural
#

my models broke after install URP

#

how can I fix this error?

summer stump
south mural
#

dangg

summer stump
#

Try reimporting* them

south mural
#

I already reinstalled Baretti A1

#

okey

formal escarp
#

Sorry for dumb question. But Deltatime is only for small numbers right? Not for whole/big numbers. like 7.

short hazel
formal escarp
short hazel
#

(delta time is the time in seconds elapsed since the last frame was rendered)

abstract monolith
#

im trying to make a grappling hook but when it hooks it just makes the character spin i cant figure out why

formal escarp
#
using UnityEngine;
using UnityEngine.UI;

public class Controller_Hud : MonoBehaviour
{
    public static bool gameOver = false;
    public Text distanceText;
    public Text gameOverText;
    private float distance = 0;

    void Start()
    {
        gameOver = false;
        distance = 0;
        distanceText.text = distance.ToString();
        gameOverText.gameObject.SetActive(false);
    }

    void Update()
    {
        if (gameOver)
        {
            Time.timeScale = 0;
            gameOverText.text = "Skill Issue \n Total Distance: " + distance.ToString();
            gameOverText.gameObject.SetActive(true);
        }
        else
        {
            distance += Time.deltaTime;
            distanceText.text = distance.ToString();
        }
    }
}
short hazel
#

If you need it to go faster, multiply the value by another number. Like 2, to go twice as fast

#

(2 per second)

formal escarp
#

oh. i did not thought of that. thanks.

#

not sure how i can do that tho, but ill try i guess.

short hazel
#

Your current code will increase distance by 1 each second while you're not in a game over state

#

+= Time.deltaTime * 2 for 2 per second

lilac hemlock
#

Can someone help me out please. I attached a script for movement of my airplane. For some reason, after I do a couple of spins (line 90), my airplane starts to shake a little on turns. Also, sometimes spins perform weirdly if i am doing them during turning (line 146, line 228).

https://gdl.space/tovunucixu.cs

abstract monolith
wintry quarry
abstract monolith
#

how do i keep it from spinning all arround

wintry quarry
#

that's a no-no

wintry quarry
#

oh nevermind your Rigidbody is kinematic?

rich adder
lilac hemlock
abstract monolith
wintry quarry
# lilac hemlock yes

you know you don't have to disable gravity if you make it kinematic. Gravity won't affect the kinematic body anywat

abstract monolith
#

it like uses the grapple then spins arround after it grappled on to something

lilac hemlock
rich adder
abstract monolith
#

ill send the code 1 sec

wintry quarry
abstract monolith
rich adder
#

oh spring joints are tricky

#

is this from a tutorial? but yea might need to lock rotation maybe on rb

lilac hemlock
wintry quarry
#

which is quite long

#

and involves a lot of weird/adhoc improper Lerping etc

abstract monolith
wintry quarry
# lilac hemlock improper?

Like you're doing a lot of stuff like smoothYawChange = Mathf.Lerp(smoothYawChange, yawChange, yawSmoothing);

rich adder
wintry quarry
#

which is not going to be framerate independent and may certainly cause jitter etc

#

that's not really a "correct" usage of Lerp

lilac hemlock
lilac hemlock
abstract monolith
#

this what happens

wintry quarry
#

you are just asking how to constrain the rotation of your Rigidbody.

#

Do so in the inspector for your Rigidbody under "Constraints"

abstract monolith
#

ok

stuck palm
#

how can i chenge the shape outer spot in code

outer cobalt
#

my game has a respawn, when the player dies it doesnt have a follow anymore on my cinemachine, how do i freeze the cameras movement till he respawns?

#

currently i am getting movement when he dies, i dont want that

outer cobalt
#

yea thats literally what i just thought of myself lmfao

#

lemme c

outer cobalt
scarlet skiff
#

if invoke is called several times before it manages to run the method it is invoking with it still invoke it 3 times or once?

wintry quarry
scarlet skiff
#

alright thanks

bitter minnow
#

How can I modify a rigidbody's velocity to approach a specific magnitude value of maxForce? Should I be using AddForce? How would I do the calculation?

scarlet skiff
#

how does one invoke a method but its through a reference like spawner.Spawn() but invoke it and make it run in 1seconds

rich adder
rich adder
scarlet skiff
#

i make a method that runs spawner.Spawn() then invoke that method?

rich adder
scarlet skiff
#

yes to run the Spawn() method in spawner after 1 second

rich adder
#

using a coroutine

#
public void Spawn()
{
    StartCoroutine(SpawnDelayed(1));
}
IEnumerator SpawnDelayed(float time)
{
    yield return new WaitForSeconds(time);
    //do stuff
}```
scarlet skiff
rich adder
#

huh? I said put the delay in the spawner script

scarlet skiff
rich adder
#

either way you can do it, you can also put delay in script B 🤷‍♂️
You can reverse it

private void CallSpawnDelayed(){
    StartCoroutine(SpawnDelayed(1));
}
IEnumerator SpawnDelayed(float time){
    yield return new WaitForSeconds(time);
    spawnerScript.Spawn();
}```
scarlet skiff
#

i use the Spawn() method in antoher way as well do if there is a solution to not change it id rather do that (cuz also i have 12 spawners that would need to be changed)

rich adder
#

if you explained what you're trying to do or why you need delay it would help offer a suggestion

scarlet skiff
#

basically, a timer n a bunch of rng stuff happen

#

if they all are right

#

return true

#

then the method decides wat type of projectile to fire

#

but i dont want it to spawn at that exact moment

#

otherwise the spawns will be in bulks

#

so i wanna space em out by 0 - 1second (thats the return value of SpawnDelayer())

rich adder
#

Put the loops inside a coroutine and use yield

scarlet skiff
#

but idk how to invoke the spawner.spawn()

young fossil
#

Is there anything inherently wrong with using a static FSM for my game states?

rich adder
wintry quarry
scarlet skiff
#

hmm alright

young fossil
#

Is it okay to make the FSM public and static? I can't think of a way to encapsulate it

rocky canyon
#

generic state machine?

rich adder
#

shouldn't an enum suffice for a game state?

wintry quarry
green copper
#

the code for adding to the singleton works fine, the code for removing it leaves an empty gameobject

young fossil
wintry quarry
vale geode
#

hi, im having dificulties understanding how to acess a script in my game, im working on a enemy ai that uses a StateMachine, the enemy object uses a script for its ai that calls other scripts that are its states, being a patrolState and a attackState, im having dificulties in the attackState script being called, the way its supposed to work is by a canSeePlayer method that uses a ray to detect a player, i have run various debugs log, and it should work since it has all the requirements for the attackState to be called, but i dont really know what to do, these parts is where i think the issues are https://paste.myst.rs/3y6ymz3b

young fossil
wintry quarry
green copper
wintry quarry
#

which does include a static reference

rich adder
green copper
wintry quarry
young fossil
wintry quarry
rich adder
#

though personally would Invoke an event when statechanged and broadcasting the enum

young fossil
#

thank you

wintry quarry
green copper
vale geode
wintry quarry
vale geode
# wintry quarry You are going to need to get way more specific than "difficulties"

it doesnt transition to an attackState, previously i had it working, but i then started to implement another enemy type in the stateMachine.cs wich is responsable for mojoraty of the logic between transitioning from a state when requirements are met, such as a method for seeing the player wich in varios debugs i ran shows its true and a method for the transiotioning wich also comes has true, the problem im having is its not going into the desired state wich is the AttackState

stuck palm
#
stats.DOMove(new Vector3(208, -374.2f, 0), 1)```
#

why is this sending it here?

#

stats is a rect transform

ivory bobcat
#

Is the object a child of something else?

wintry quarry
green copper
#

InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <546dbfe4aa3a47b4a64849b03910c33f>:0)

I get this error code approximately ten percent of the time when destroying a turret object, but only when the inspector panel for a singleton keeping an array of all turrets is open

stuck palm
wintry quarry
nimble wigeon
#

hi guys, so im working on a 2d adventure game and ive got down the basic movement, camera follow, and i tried adding a heart system and it shows the heart and everything but when i enter game mode the hearts are nowhere to be found, this is my scene and health scripts:

green copper
#

or is it going to cause big problems later because something at the core is wrong?

wintry quarry
#

It should be on only one object.

#

oh nvm it's on the player

#

are you sure it's not on any other objects?

#

also show your game view

wintry quarry
north kiln
eternal falconBOT
nimble wigeon
nimble wigeon
nimble wigeon
#

in the video his shows up in the top left when he enters game mode

wintry quarry
#

you cropped the window so it's hard to tell

nimble wigeon
#

thats while running

wintry quarry
#

Ok so show those hearts in scene view when it's running. And also show their inspectors

nimble wigeon
wintry quarry
#

this is not anything that I asked to see 😦

#

I asked to see their inspectors too please!

nimble wigeon
wintry quarry
#

select them

wintry quarry
#

Make em bigger

nimble wigeon
#

i've never used UI before so i didnt know how big to make them

wintry quarry
wintry quarry
#

you can open game and scene windows side by side if you want

scarlet skiff
native seal
rich adder
eternal needle
#

Goddamn [][][]

#

I pray that isnt 3 dictionaries

polar acorn
#

why is the parameter of type MonoBehaviour

scarlet skiff
scarlet skiff
#

idk

scarlet skiff
polar acorn
scarlet skiff
#

it kinda is

#

well a dictionary containing 2 dictionaries

eternal needle
#

Memes arent allowed here, but really focus on restructuring this. You 100% do not need whatever that value type is.
If you wanna pass in a spawner script specifically then you dont use monobehaviour, use either some common interface or abstract class that the spawners all implement

#

First things first, get rid of that triple dictionary

scarlet skiff
rich adder
#

either way starting a new coroutine is wrong approach

polar acorn
rich adder
#

if you want to pause each loop , the whole function needs to be IEnumerator and put yields in the loops

scarlet skiff
rich adder
polar acorn
scarlet skiff
rich adder
scarlet skiff
#

ye sorry it was a bit hard to articulate

rich adder
#

oh there

#

that makes sense

polar acorn
#

Probably the best way to do this would be to have the spawners themselves spin up the coroutine that waits then spawns the object

#

So .spawn starts a coroutine with a random delay and then does whatever

scarlet skiff
#

yea but like due to how everything is set up, with .spawn being used in other scripts and havign a bunhc of different types pf spawners, id prefer if there was a way without changing the spawn method

polar acorn
scarlet skiff
#

i suppose that is a solution, but if there is a way to do it via the original script and not the spawner script that would be nicer

polar acorn
scarlet skiff
polar acorn
obtuse osprey
#

why is it red around this sprite?

scarlet skiff
#

but how would that look like? for example how would i be able to pass a spawner of type FireballSpawner in here

rich adder
#

also not code related

polar acorn
obtuse osprey
#

ive looked for tutorials but i cant find any

rich adder
deft grail
obtuse osprey
deft grail
obtuse osprey
#

okay lets try again

thorn holly
#

is there any shortcut way to correlate, say, "Color.green" to the string "Green", or do I have to make a dictionary or something?

deft grail
rich adder
#

ig depends on your usecase

thorn holly