#💻┃code-beginner

1 messages · Page 181 of 1

late bobcat
#

Ehy guys, i was trying to replicate vampire survivors for those who knows the game and i've a question. As you can see there's a circle around me (the one who's opacity is less). That circle should deal 30 dmg to enemies colliding with it (using ontriggerstay2d) and enemies have 30 hp. What am asking is. Enemies should get oneshot from the circle but instead, when there are many, some of them go trough, do you know why?

zealous oxide
#

slowly rotate the game object with the line renderer/laser so the second point on the line renderer lines up with the player character, but with a delay. i can do it instantaneously but im trying to get the rotation to move slowly, lag behind the player

scarlet skiff
#

i am trying to make one script that handles all the collision for the player, however, when colliding with a fireball there are two outcomes, one is that the player takes damage and the fireball is destroyed, and the other is that the foreball is reflected off the player and continues on its way.

problem is, the condition that needs to be true to reflect the fireball, is to check if the fireball has collided with the child "shield normal" of the parent player (the player has the script for collision). Problem is, this requires a OnCollisionEnter2D inside a OnCollisionEnter2D... which seems to be not possible, instead i opted to check if the fireball has collided with the shiled in the fireball script attached to the fireball itself, then if thats true, set a "isReflected" bool to true, but since im running two OnCollisionEnter2D they run at the same time and the "isReflected" bool is nit set to true on time

slender nymph
#

just check if it has collided with the shield and reflect if it has, if it has not then you check if it has collided with the player

#

you are way overthinking how to set this up. a simple if/else if is all you need

teal viper
zealous oxide
#

yeah i tried those but ultimately went with something a bit different which now works as intended. thanks for the suggestion 🙂

pseudo frigate
#

i have the following code on the inventory gameobjects, dragging them works but the initial mouse position is wrong. attached is an image of the hierarchy, theyre all under the same canvas, have tried a few different things but nothing is working, what am i doing wrong? the Holder object is the one moving around

    public void OnBeginDrag(PointerEventData eventData)
    {
        InventoryManager.Instance.draggedObjectImage.sprite = itemReferece.itemSprite;
        InventoryManager.Instance.draggedObjectRect.anchoredPosition = Input.mousePosition;
        Cursor.visible = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        InventoryManager.Instance.draggedObjectRect.anchoredPosition += eventData.delta / InventoryManager.Instance.inventoryCanvas.scaleFactor;
    }
elder osprey
#

Could I please get help with this?

teal viper
teal viper
harsh silo
#

!code

eternal falconBOT
harsh silo
#

Anyone know why this code is randomly at times getting this message:

"MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still triyng to access it."

pseudo frigate
harsh silo
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class WeaponScript : MonoBehaviour
{
    [SerializeField] Camera FPCamera;
    [SerializeField] float range = 100f;
    [SerializeField] float damage = 30f;
    [SerializeField] ParticleSystem muzzleFlash;
    [SerializeField] GameObject hitEffect;

        void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    private void Shoot()
    {
        PlayMuzzleFlash();
        ProcessRayCast();
    }

    private void PlayMuzzleFlash()
    {
        muzzleFlash.Play();
    }

    private void ProcessRayCast()
    {
        RaycastHit hit;
        if (Physics.Raycast(FPCamera.transform.position, FPCamera.transform.forward, out hit, range))
        {
            CreateHitImpact(hit);
            EnemyHealth target = hit.transform.GetComponent<EnemyHealth>();
            if (target == null) return;
            target.TakeDamage(damage);
        }
        else
        {
            return;
        }
    }

    private void CreateHitImpact(RaycastHit hit)
    {
        GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
        Destroy(impact, 1);
    }
}

wintry quarry
harsh silo
#

yeah the particle system is my muzzle flash effect, but i dont know why its getting deleted randomly

wintry quarry
#

the error message will contain a filename and line number. Start by looking there

harsh silo
#

MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.ParticleSystem.Play () (at <bed3c648adea411ea03fe29d57cdd527>:0)
WeaponScript.PlayMuzzleFlash () (at Assets/Scripts/WeaponScript.cs:31)
WeaponScript.Shoot () (at Assets/Scripts/WeaponScript.cs:25)
WeaponScript.Update () (at Assets/Scripts/WeaponScript.cs:19)

teal viper
scarlet skiff
#

it gets to the else statement first, which destroys the object

slender nymph
#

Why do you need that bool?

pseudo frigate
#

its screen space - camera, its a UI camera, not the main cam

wintry quarry
scarlet skiff
slender nymph
#

Again, why do you need that bool? Just check if it is colliding with the shield there

scarlet skiff
harsh silo
# wintry quarry Likely some other code you have is destroying it.

This is my enemy health script, but I don't have it on the muzzle flash particle effect is the weird part

public class EnemyHealth : MonoBehaviour
{
    [SerializeField] float hitPoints = 100f;
    
    public void TakeDamage(float damage)
    {
       hitPoints -= damage;
       if (hitPoints <= 0)
       { 
        Destroy(gameObject); 
       }
      
    }
}

#

i only have that script on my enemies

ivory bobcat
#

What do you have it on instead then?

harsh silo
#

That script is on my enemies but for some reason my muzzle flash particle effect is randomly getting destroyed from it

wintry quarry
#

Also note that you may have multiple copies of WeaponScript in the scene, and this problem could be happening on one copy but not others due to how they're set up differently and which Particle Systems they are referencing

harsh silo
#

The weapon script itself doesn't have the particle system assigned, just the item that the script is on

wintry quarry
harsh silo
wintry quarry
#

the instance

#

not the script itself

harsh silo
#

ahh

teal viper
harsh silo
#

ugh i cant even get it to trigger now

#

its very random when it happens vs when it doesnt

#

ok i triggered it, now it just says this as expected

wintry quarry
#

Is that object now destroyed?

harsh silo
#

yes it is

wintry quarry
#

ok so

#

figure out why that's happening

#

the problem lies there

#

it has nothing to do with this script

vale karma
#

how can i make the camera a FPS pov? as of now the camera can turn up and down, but not left and right. The player can turn, but the cameras Y rotation doesnt change

wintry quarry
harsh silo
#

the ONLY place I have any destroy command is in the enemy health script

vale karma
#
public void OnLook(InputAction.CallbackContext context)
{
    // Reads movement input from the Mouse Input Action.
    mouseInput = context.ReadValue<Vector2>();
    Debug.Log(context);

    // Sets the y-axis input from the Mouse inverted to the camera up/down rotation.
    // Clamps up/down view to 45 degrees.
    // Multiplies the x-axis input from the Mouse and sensitivity to the players left/right rotation.
    // Rotates the first person camera local to its own rotation.
    firstPersonCameraXRotation -= mouseInput.y;
    firstPersonCameraXRotation = Mathf.Clamp(firstPersonCameraXRotation, -45f, 45f);
    firstPersonCamera.transform.localEulerAngles = Vector3.right * firstPersonCameraXRotation;
    

    // Rotates the player with the player left/right rotation every time the mouse is moved.
    playerYRotation = mouseInput.x * mouseSensitivity * Time.deltaTime;
    gameObject.transform.Rotate(0f, playerYRotation, 0f);
 
}
wintry quarry
vale karma
#

i know but alot of them arent working for some reason. I had this issue before but dont know how it got fixed

wintry quarry
harsh silo
wintry quarry
vale karma
wintry quarry
vale karma
#

it has a character controller with the new input system

wintry quarry
#
gameObject.transform.Rotate(0f, playerYRotation, 0f);```
should instead be:
```cs
rb.rotation *= Quaternion.Euler(0, playerYRotation, 0);```
#

ok scratch that then

vale karma
#

using time.deltatime

harsh silo
#

ah that fixed it, ty @wintry quarry

wintry quarry
vale karma
#

at all? or just for the playerYRotation?

wintry quarry
#

When handling mouse input

vale karma
#

okay

wintry quarry
#

mouse input is by its nature already framerate independent

#

because the values you are getting are movement since the last frame

harsh silo
#

one more question though, its also happening on my bullet impact object, but that has "Stop ACtion" set to none

vale karma
#

i took it out, now the only thing im havin an issue with is how to rotate the camera on the Y axis of itself, normally you would parent the player over the camera, but its bad habit right?

harsh silo
wintry quarry
ivory bobcat
#

Assuming this impact object is what you're referring to

wintry quarry
#

the code looks ok on the left there

harsh silo
#

I changed it

#

this is what its supposed to be

#

and the effect works for a while then gets destroyed

#

this is the code in question

#

!code

eternal falconBOT
harsh silo
#
// Your code here
#
    private void CreateHitImpact(RaycastHit hit)
    {
        GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
        Destroy(impact, 1);
    }
}

wintry quarry
#

What's the error message?

harsh silo
#

same exact one as before

wintry quarry
#

Can't be

#

it would have a different filename and line number

#

show the stack trace

harsh silo
#

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
WeaponScript.CreateHitImpact (UnityEngine.RaycastHit hit) (at Assets/Scripts/WeaponScript.cs:52)
WeaponScript.ProcessRayCast () (at Assets/Scripts/WeaponScript.cs:39)
WeaponScript.Shoot () (at Assets/Scripts/WeaponScript.cs:26)
WeaponScript.Update () (at Assets/Scripts/WeaponScript.cs:19)

wintry quarry
#

So looks like you're destroying hitEffect somewhere

#

btw make sure you're referencing the prefab

#

and not some instance copy you have in the scene

wintry quarry
# harsh silo

because this screenshot seems to imply you have a copy in the scene for some reason

harsh silo
#

ok ill double check that

wintry quarry
#

delete any copies from the scene, and then double check the prefab itself

queen adder
#

SPRING

#

Im back from work

warm anvil
#

oh hey! speak of the devil, i was literally about to ask someone if they could pickup the baton question 🙂

queen adder
#

baton?

warm anvil
#

so the TLTR question was: how is this used / interpreted

InputAction action = playerInput.Actions["ActionName"]

#

baton, like a relay race (the metal rod passed along)

queen adder
#

From the InputAction asset

#

You have a list have actions

harsh silo
#

The prefab was what I had referenced

queen adder
#

You insert the action name from one of the actions from the input actions asset inside of ["ActionName"]

warm anvil
queen adder
#

Jesus christ i said action alot

warm anvil
#

so Backpack in this case ofc

queen adder
#

Yes^^

#

playerInput.actions["Backpack"];

ivory bobcat
warm anvil
#

so I think what you're stating as the next logic conclusion is that for example this code:

    private void OnEnable()
    {
        _input = new InputActions();
        _input.Humanoid.Backpack.performed += HandleBackpack;
        _input.Humanoid.Enable();
    }

    private void OnDisable()
    {
        _input.Humanoid.Backpack.performed -= HandleBackpack;
        _input.Humanoid.Disable();
    }

    public void HandleBackpack(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            Debug.Log("Attack performed");
        }
    }
ivory bobcat
#

Implies you've really referenced a prefab and not a scene object and it was destroyed

queen adder
#

Thats not how i would make it

#

Share the entire class please

harsh silo
#

well i have the prefab still and i re-applied it and its still happening

warm anvil
#

you can use that one line instead of possibly subscribing to an the HandleBackpack event and then having a separate method called HandleBackpack?

#
using UnityEngine;
using UnityEngine.InputSystem;

public class InputSystemController : MonoBehaviour
{
    private InputActions _input;

    void Awake()
    {
        PlayerInput playerInput = GetComponent<PlayerInput>();
        InputAction action = playerInput.Actions["ActionName"]
   }

    private void OnEnable()
    {
        _input = new InputActions();
        _input.Humanoid.Backpack.performed += HandleBackpack;
        _input.Humanoid.Enable();
    }

    private void OnDisable()
    {
        _input.Humanoid.Backpack.performed -= HandleBackpack;
        _input.Humanoid.Disable();
    }

    public void HandleBackpack(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            Debug.Log("Attack performed");
        }
    }
}
ivory bobcat
queen adder
#

Does that code work?

warm anvil
#

yes

#

well, not anything in Awake()

#

but everything else yes

queen adder
#

Oh thats because i dont use InputActions like that

#

I didnt even know it could be that simple

#

Im confused by that code

warm anvil
#

well, i can't take credit but I'm thrilled I can pass along at least something 🙂

harsh silo
queen adder
#

the InputActions instance knows about the BackPack action?

warm anvil
#

let me cross-check...

harsh silo
#

notice how the impact disappears after like 10 shots

queen adder
#

The console is printing Attack Perfomed?

#

Im not doubting you or anything im just shocked that works

wintry quarry
warm anvil
#

ik 🙂

harsh silo
#

those are the particle systems

queen adder
#

Well ok then

#

Did u need help with anything else

harsh silo
#

i just created an extra VFX_M4 item when troubleshooting before sending the vid

queen adder
#

Thats pretty simple thx for sharing!!

warm anvil
#

not at the moment, ty! you gave me an alternative. FYI all you need for it to work is an empty game object with that script and ofc you know an inputsystem object that's called InputActions (btw not to be confused with Unity.InputSystems's InputAction (non-plural).

arctic ibex
#

So, when i made my tilemap collider friction less (so i couldn't stick to the walls) this happened. I'm guessing it's cause the floor is so slippery, but I can't figure out how to fix it without making the walls grippy again. any ideas?

#

Wait, is it cause i use tranform.position to move the character instead of setting momentum?

ivory bobcat
arctic ibex
#

so it sets its position into the wall then gets ejected?

queen adder
#

I think u have "Create a C# class" Selected for ur input action asset

warm anvil
#

aka how do you act upon the action

queen adder
#

You have something else going on Spring

harsh silo
#

ahhhh

faint osprey
#

ok so im trying to get my enemy to dash to the players last position with this code private IEnumerator TreeDash() { moveBool = true; playerPos = player.transform; while(true) { gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, playerPos.position, 0.01f); yield return null; } }
ik theres no break in the while loop but for some reason when i run this it doesnt go the the location that i set at the top but it just follows the player constantly and i dont know why

warm anvil
#

no, just completing the thought/technique you shared was all

harsh silo
#

im a little slow tonight thank you all for the help

queen adder
#

You can delete my code

warm anvil
#

but doesn't it work?

queen adder
#

Its specifically for the player Input

#

No u have to do extra stuff for my code

#

I thought you were just trying to use the Player Input

warm anvil
#

oh ok, yours actually sounded VERY simple and was like, why do people do it the way I shared 🙂

queen adder
#

No urs is simpler

#

So good job👍

ivory bobcat
warm anvil
#

again, can't take credit - at least a person Fen here helped and there's seems to be a pattern of the technique from Inventory Systems on youtube and/or Unity's new Input System to show this technique

faint osprey
queen adder
#

Yeah Fen is way smarter than me when it comes to this stuff

warm anvil
#

have a good evenving vee, thanks for reaching to me again

queen adder
#

Ofc man you 2!

ivory bobcat
#

If you want to move to a value, cache the last known position and move towards that - not the players transform component.

faint osprey
ivory bobcat
#

position = player.transform.position

#

Where position should be a vector 3 value rather than a reference to the player transform

faint osprey
#

ah right that makes sense

#

its saying its not been assigned tho

ivory bobcat
#

Maybe show the error

faint osprey
#

wait no im dumb i got it

ornate olive
#

hey guys i need to add my text script but i cant seem to find a way to do that. i need to add the text to the score

frigid sequoia
#

Man I do not undertand a think of why this is working as it is working....

#

I want a proyectile to rotate towards the closest object with the tag enemy

#

If I use a separete script that just rotates a object towards another object and assing it there it works as intended, if I add that same code to this script, it doesn't

#

But in a really weird way

#

That cuve is tagged as an enemy

#

The botton left proyectiles seem to want to go DIRECTLY in the opposite direction

#

The rest just seem to straigh up ignoring

fierce shuttle
ornate olive
#

using UnityEngine;
using TMPro;

public class score : MonoBehaviour
{
public Transform player;
public TextMeshProUGUI scoreText;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
}

}

frigid sequoia
fierce shuttle
eternal falconBOT
teal viper
teal viper
#

In fact you don't set it at all

fierce shuttle
# ornate olive correct it does not'

That should, do you have any errors in your console that may be preventing your script from compiling? Can you show what your inspector looks like with that updated code?

rich adder
#

Yup it’s not compiled

#

You either didn’t save or you have complie errors

ornate olive
rich adder
ornate olive
rich adder
#

Check console window where the errors are if any

rich adder
eternal falconBOT
teal viper
radiant sail
#

quick question, can anybody tell me how to make the players speed stay the same when holding down W & A/D because if i move diagonally it makes the player move faster

void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

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

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);
        if(!isGrounded && velocity.y < 250)
        {
            velocity.y += gravity * Time.deltaTime;
        }
        controller.Move(velocity * Time.deltaTime);
    }```
teal viper
radiant sail
#

k thx

arctic ibex
#

Is there any easy way to make the floor more solid? I'm using a tilemap collider and i keep clipping through the floor when I'm falling to fast

rotund hull
#

how can i have a button on the script in the enspector

rich adder
rotund hull
#

no like in code you write something and when you go back into unity you see a button on the script component

#

what is that called

rich adder
rotund hull
teal viper
ripe shard
rich adder
rotund hull
rotund hull
arctic ibex
#

Why is the Physics 2D not working? It seems to work fine for the line above?

north kiln
#

What does the error say

#

Because I can see what's wrong, perhaps you can figure it out by reading it

arctic ibex
#

and i just realised I forgto the curly brackets, but it still says it so

north kiln
summer stump
north kiln
#

In this case, this is not how you write an else statement

faint osprey
#

how would i go about making it so my GameObject ignores colliders on other instantiated clones of that GameObject ive tried this but it doesnt work Physics2D.IgnoreCollision(wallCollider, wallCollider);

ripe shard
arctic ibex
cosmic dagger
faint osprey
cosmic dagger
rich adder
faint osprey
#

so would this work Physics2D.IgnoreLayerCollision(7, 7);

#

if all the objects i dont wanna collide with are on 7

ripe shard
rich adder
#

Use name to layer

#

A bit cleaner than magic numbers

cosmic dagger
ripe shard
#

Using named layers in code is terrible

soft wren
#

Is anyone able to help me out with a duck problem?

rich adder
#

If you change later the whole thing breaks

ripe shard
#

strings break, integers don’t

rich adder
#

U can use constant for that tho

ripe shard
#

Magic numbers are not fixed by turing them into strings, you put them in a variable/constant

faint osprey
#

if i have two colliders on an object is their a way to ignore collision on just one of them

rich adder
cosmic dagger
#

or use an SO with a LayerMask field and reference that. forget about strings or ints . . . thinksmart

rich adder
#

LayerMask doesn’t work on gameobject int no? @cosmic dagger

frigid sequoia
rich adder
#

Since that’s one layer and not multiple like LayerMask

frigid sequoia
#

Like it was the only enemy tag in scene anyways

cosmic dagger
rich adder
#

gameObject.Layer

cosmic dagger
#

oh, you mean the int that gameObject.layer represents?

#

nope. you have to convert it to a LayerMask. i use extension methods for that . . .

rich adder
#

Yes I recall I couldn’t use LayerMask with that and had to use LayerMask.NameToLayer to get it working

rich adder
summer stump
#

Would something like 1 << gameObject.layer work?

#

For the one direction only of course

rich adder
#

Interesing. haven’t dabbled into bitshift myself

shell sorrel
#

the bitshift should work for it

soft wren
#

transform.rotation = Quaternion.FromToRotation(transform.up, collision.contacts[0].normal);
I have this here which rotates an enemy along the normal of the wall it hits. How would I offset the rotation so it rotates 45 degrees away from the wall and not 90?

cosmic dagger
rich adder
#

Nice! Thanks guys

cosmic dagger
#

typically, i use a CompareLayer or ContainsLayer extension method to check if two layer masks are the same or if a layer mask is contained within another . . .

shell sorrel
#

once you do bitwise stuff enough you eventually remember what it all does

arctic ibex
#

This doesn't seem to be working for some reason and I can't figure it out. What is the blaringly obvious error that I'm certain I've made?
(Also, any suggestions on how to find solutions through google? I keep trying to go to google for help, but I always end up not getting any helpful information)

summer stump
arctic ibex
cosmic dagger
summer stump
cosmic dagger
arctic ibex
summer stump
#

Also, I see- ah yeah, what Random said

arctic ibex
cosmic dagger
#

one is a trigger, the other is a collision. one is 2d, the other is 3d . . .

#

details matter . . .

summer stump
cosmic dagger
#

place a log outside of the tag check and inside of the tag check to make sure the trigger method is called, and that the tag check is true . . .

summer stump
# arctic ibex nope

Show the whole gate !code

I suspect honestly that the bool DOES change, it just flips back immediately because of something else

eternal falconBOT
arctic ibex
thorn holly
#

Is it bad practice to put multiple classes in one script? Like for an FSM?

vale karma
#

would you guys recommend using a character controller or rigid body?

cosmic dagger
shell sorrel
cosmic dagger
thorn holly
cosmic dagger
vale karma
#

well its gonna be kind of realistic movement, basic walk run and jump

#

the problem is i dont know how to implement gravity into my character controller :/

arctic ibex
#

Wait nvm Aethenosity was right

#

I set the wrong bool

shell sorrel
thorn holly
thorn holly
vale karma
#

is it possible to still use a rigidbody or is that bad practice?

shell sorrel
#

yeah i often have a bunch of types defined in 1 file, if they are like data containers and stuff related to the main one

thorn holly
vale karma
#

im not picky lol, i just dont know how to get gravity to work

thorn holly
#

Rigidbody gives more freedom, while character controller is easier configurable

shell sorrel
#

@thorn holly the ones to be weary of is anything that needs a guid, since to get that it needs a meta file. So everything that derives from UnityEngine.Object

vale karma
#

yea ive noticed. but it feels like any coding with the controller is confusing bc idk how it uses .isGrounded in the characterController

#

multiple reasons.. also, i should probably learn rigidbodies in the longterm

thorn holly
teal viper
frigid sequoia
teal viper
#

And both parameters need to stay constant.

frigid sequoia
#

It works literally perfect when used in stand alone

shell sorrel
#

its not working how you think though

frigid sequoia
#

Like it smoothly interpolates between a and b based on the given speed

shell sorrel
#

its working likly because you are also feeding current position into the first arg not start position

#

lerp is not meant to move things at a given speed

winter prawn
#

Isn’t there a look towards or look at method?

shell sorrel
frigid sequoia
#

I don't get it

shell sorrel
#

lerp(a, b, t) returns a value between a and b base on where t is between 0 and 1

summer stump
shell sorrel
#

because you are feeding the current value into a every update you are moving towards it by what you passed to t

#

so if t was 0.5 it gives half way closer each update

#

but never reaches its final target because its always by half

#

normally people save there start pos pass it to a, pass destination to b, then start t at 0 and add deltaTime * a multiplier every frame

wispy karma
#
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class HighVelocityShot : MonoBehaviour, IAbility
{
    public float AbilityForce { get; private set; } = 20f; // Example force value
    public event Action<float, float> OnCooldownChanged;

    [SerializeField] private GameObject abilityPrefab;
    [SerializeField] private GameObject foregroundIcon;
    [SerializeField] private GameObject backgroundIcon;
    public GameObject AbilityPrefab => abilityPrefab;
    public GameObject ForegroundIcon => foregroundIcon;
    public GameObject BackgroundIcon => backgroundIcon;
    public float Cooldown => 5f; // Example cooldown
    public bool CanUse { get; set; } = true;
    public string AbilityName { get; } = "PillStorm";

    private Camera mainCamera;

    public void Awake()
    {
        mainCamera = Camera.main; // Cache the main camera reference
    }

    public void Activate(Transform firePoint, GameObject prefab, float force)
    {
        if (!CanUse)
        {
            Debug.Log($"{AbilityName} cannot be used due to cooldown or other conditions.");
            return;
        }

        Debug.Log($"Activating {AbilityName}");

        // Calculate direction towards the mouse cursor
        Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        Vector2 direction = (mousePosition - (Vector2)firePoint.position).normalized;

        // Create the explosive shot projectile
        GameObject shot = Instantiate(prefab, firePoint.position, Quaternion.identity);
        Rigidbody2D rb = shot.GetComponent<Rigidbody2D>();

        // Apply force in the direction of the mouse cursor
        rb.AddForce(direction * force, ForceMode2D.Impulse);
        StartCoroutine(CooldownRoutine());
    }

    public IEnumerator CooldownRoutine()
    {
        CanUse = false;
        float cooldownTimer = Cooldown;
        while (cooldownTimer > 0f)
        {
            cooldownTimer -= Time.deltaTime;
            OnCooldownChanged?.Invoke(cooldownTimer, Cooldown); // Update UI each frame during cooldown
            yield return null;
        }
        CanUse = true;
    }
}```

Hey I think I am running into an instantiation issue, I currently have a set of abilities that from within a list that can be interchagably swapped out on the fly. but none of the abilities can even instantiate or are returning null. Is this because of a parenting issue? Currently the script will is sitting on the parent of the child it's instantiating. I don't really know if this is a beginner or higher question
shell sorrel
#

why is it called AbilityPrefab but you are passing in a refernce to the GOW Parent GO

wispy karma
#

Because the way I orignally had it set up, was to just pass in the entire prefab but wouldn't that cause circular instantiation and just not work or break the game?

shell sorrel
#

code never shows what calls Activate, so can not see what prefab is being passed to Instantiate

wispy karma
#

One sec

shell sorrel
#

also no parent is being set, so they will be created in root of your active scene, which could be fine depend on what you want

wispy karma
#

The system itself is a little complicated and out of my personal scope, but I was tasked with creating an system which will store player abilities that can be swapped out in between bosses once unlocked, which in turn has to be able to swap out all icons, prefabs etc.

#

Anything that you could be interested in is in the codeshare, if you need any further clarification let me know, I appreciate you checking it out

shell sorrel
#

well it looks like the first issue i pointed out

#

where that code calls Activate, it passes in ability.AbilityPrefab, which does not point back to a prefab based on your inspector

#

but the GOW Parent object

wispy karma
#

So it was originally set up like this

#

But the problem that creates is circular instantiation no?

#

Because the script is attached to the object it's trying to instantiate

frigid sequoia
#

But honestly this is working so good that I cannot believe it is wrong

summer stump
cunning rapids
#

C# is an object-oriented programming langauge

wispy karma
#

Each time it fires the ability it creates a single instance of the bullet so that would be instantiation no?

cunning rapids
#

I don't know the context of the issue here enough

#

I just got here

#

Can you explain the problem quickly again?

rich adder
wispy karma
wispy karma
wispy karma
#

Totally forgot to change the mic and disable the camera on obs my bad

#

I don't think it's an inspector issue

cunning rapids
#

Are you sure you have the Action "AbilityThree"

#

Wait

#

Here

#

This is how that error message pops us

#

Ability is null

#

Check your inspector

#

Did you assign everything correctly?

wispy karma
frigid sequoia
wispy karma
cunning rapids
wispy karma
#

should be

nimble apex
#

background story: this is a system , or an UI to display game result

im optimizing a 20 lines code inside that UI, quite a lot to do, let starts with step 1

foreach (object gameInfo in history.gameInfo)
{
  gameResult.type = JsonConvert.DeserializeObject<Info>(JsonConvert.SerializeObject(gameInfo))
  //something more
}```

the game result UI receive data from server and populate itself, the model class that receives data will be used by many other classes, im told to not modify it, or the whole system will collapse
wispy karma
nimble apex
#

so, without modify the base model, is this good?

cunning rapids
wispy karma
#

I debugged and everything

cunning rapids
#

It looks good to me but I'm too sleep deprived to thoroughly check everything 😭

#

Some people should be able to help here

nimble apex
#

YOU NEED SLEEP

#

COMFY BED NOW

wispy karma
#

Activate is just a method I created for the interface

#
using System;
using System.Collections;
using UnityEngine;

public interface IAbility
{
    event Action<float, float> OnCooldownChanged;
    string AbilityName { get; }
    float Cooldown { get; }
    bool CanUse { get; set; }
    GameObject ForegroundIcon { get; }
    GameObject BackgroundIcon { get; }
    GameObject AbilityPrefab { get; } // Prefab for the ability
    float AbilityForce { get; } // Force to be used with the ability

    void Activate(Transform firePoint, GameObject prefab, float force);
    IEnumerator CooldownRoutine();
}```
summer stump
wispy karma
#

It's not a unity thing

frigid sequoia
#

Like, vectors, I could do, quaternions, no idea

wispy karma
#

Should I maybe put this question in a higher channel? or would this still be considered a beginner question?

teal viper
teal viper
low path
wispy karma
#

Yeah I just figured it out

#

It totally was the canuse variable

#

Thank you all for your help

#

I really appreciate it

#

I'll hop on back if it's not the case

obsidian fern
#

I'm trying to make a tank shell projectile that ricochets if it hits the object at too steep of an angle.

I had it figured out at first:

  • Sphere collider at the tip and explodes on impact.
  • and a Cylinder collider in the shape of a hockey puck right underneath. If the projectile touched the target with this first then, ricochet.

Problem is: it moves too fast so it sometimes phases through walls. I fixed this by making the sphere colliders height really large so it shoots ahead of the projectile reaching far.

But now how do implement the ricochet mechanic

cosmic dagger
obsidian fern
#

I'll have a look

vale karma
#

is it more expensive to call the return method IsGrounded(); that includes raycasts every time it needs to be checked, or if I just put IsGrounded(); in update and change it to a void method?

#

because i wanted to only use it when i need to, I guess for better (clearly not noticable) optimization, but i realize if my movement method calls the IsGrounded method and my movement method is in the Update method, then Id just be calling it multiple times + the update function

faint sluice
#

You're creating a function who's single purpose is to check if it's grounded and can be reused anywhere else

vale karma
#

yea i figured as well, then i thought if i just use IsGrounded in update and set it as a bool variable, maybe it would cost less?

#

Its really a point of do i want IsGrounded in the Update function lol, keeping things tidy

faint sluice
#

Depends on how often do you want to see if you're grounded or not

For most of my games

void Update()
{
If(isGrounded())
{
DoMovement();
}
}

Is pretty clean and tidy

#

Just make sure you're checking "isGrounded" only once per frame at Max

vale karma
#

then id probably want it in update. thats wat i was gettin to, if i have to check 4 different times at once it could be an issue

charred spoke
#

4 different if statements in a single Update wont even make a dent in the most basic of cpu’s

vale karma
#

ill just call the method in update once, and get the data from the variable

#

Yea but im trying to make a fps controller I can use in other games ill make, they have one on the asset store but i dont quite understand it, also it doesnt use the new input system

#

I want to make it look nice and be politically correct lol

faint sluice
charred spoke
#

Still

vale karma
#

I was using the new input system and a character controller, then realized the controller isnt that flexable

#

so i had to switch to rigidbodies, ive been working on a system all day lol

faint sluice
charred spoke
#

I mean what he is doing now is better in terms of code clarity and maintainability and even technically performance. Im just saying that modern cpus are truly insanely and disgustingly fast.

#

It helps to know that

vale karma
#

I work at a pc shop during the day, and let me tell you pcs are becoming the value of a car

frigid sequoia
#

It is still resulting in the same issue

arctic ibex
#

So I have all objects that reference the player do so by finding an boject with the tag "Player" at the start, and even though the player was technically not already in the scene and was being instantiated, it worked perfecty fin with no issues. But now it's just started not working. For some reason the object reference never works unless i put it in update or something. Is there way to fix this? Because it was working fine before. Technically teh new way (putting it in update) works fine but it just felels clunky and I'm sure theres a better way to do it.

vale karma
#

do i still need to add .normalized to the moveDirection if i am using the new input system?

rich adder
#

wdym

#

do you get error ? show error

#

if you think they somehow were able to find the player before instantiation you remember wrong lol

faint sluice
arctic ibex
arctic ibex
rich adder
teal viper
rich adder
# arctic ibex

if player is spawned in start ofc its not gonna find it

faint sluice
rich adder
#

they both run start

arctic ibex
#

Yeah but it was working perfectly fine before, with no issues

rich adder
#

use awake

arctic ibex
#

even though they were both on start

rich adder
#

scripts order aren't guaranteed , between diff starts

arctic ibex
faint sluice
charred spoke
arctic ibex
rich adder
#

why is player not in the scene already anyway lol

charred spoke
#

So either manually set execution order or certain scripts or redo when you spawn the player

arctic ibex
rich adder
arctic ibex
frigid sequoia
#

Instead this happens

#

I don't even know what they are trying to target

rich adder
# arctic ibex no

ohh , I mean the player can already be in the scene and just be assigned a new position..

frigid sequoia
rich adder
# arctic ibex how?

use the position you plug into Instantiate , just do playerPos.transform = newPos

#

for example

teal viper
eternal falconBOT
vale karma
rich adder
#

how would i know

vale karma
#

i had it in fixedupdate woops

#

dont worry i usually always send code after, unless i solved it like just now lol

frigid sequoia
frigid sequoia
eternal falconBOT
teal viper
frigid sequoia
#

Is not like that xd

faint sluice
#

` instead of '

north kiln
#

Even if you formatted it correctly, that's not correct.

#

Read the Large Code Blocks section.

faint sluice
#

Also large code block

#

Ye

frigid sequoia
#

It was not that large, it fitted the discord message length

#

But ok

north kiln
#

It pushed everything off-screen, it's large.

summer stump
frigid sequoia
#

It inherits form the generic proyectile, but should not be relevant, just hanldes basic collisions and movement

arctic ibex
#

https://hatebin.com/bappghduwl
For somereason the animator.SetTrigger("stand") isn't doing anything. The debug goes off, but nothing happens. No errors, just nothing. Anyone know what the issue is?

#

Also, prewarning, my code is horrible

faint sluice
arctic ibex
vale karma
#

I have this script on my Camera to look around. For some reason the mouse movement is really blocky/jittery. I set it up differently than I used to, but i dont see why its acting like that. Also, is this the best way to set up mouse look for a player?

public class FirstPersonPOVBehavior : MonoBehaviour
{

    public float sensX;
    public float sensY;

    public Vector2 view;

    public Transform playerModel;

    float xRotation;
    float yRotation;
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        ViewPort();
        
    }

    public void OnLook(InputAction.CallbackContext context)
    {
        view = context.ReadValue<Vector2>();
    }

    public void ViewPort()
    {
        yRotation += view.x;
        xRotation -= view.y;
        xRotation = Mathf.Clamp(xRotation, -45f, 45f);

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
        playerModel.rotation = Quaternion.Euler(0, yRotation, 0);
    }
eternal falconBOT
teal viper
wintry quarry
faint sluice
wintry quarry
#

Otherwise you need to actually rotate in the event function or consume the input when you use it

#

I.e. set view to V2.zero at the end of Update

vale karma
#

okay, how can i read the mouse input in update while still using the new input system?

arctic ibex
wintry quarry
#
view = Vector2.zero;``` at the end of Update
arctic ibex
#

huh, for some reason the preview doesn't show th eanimation

#

BUt the animation window does

faint sluice
arctic ibex
#

oh, i didn't even know that was there

#

thanks!

frigid sequoia
#

Cause it is not showing, should it?

wintry quarry
#

Did you enable gizmos?

frigid sequoia
#

I did dissable a lot of them, but not sure which is the one that shows that

teal viper
wintry quarry
frigid sequoia
#

Doesn't seem to show

#

That should show, right?

teal viper
#

Also make the radius bigger, like 5f or something

frigid sequoia
#

Mmmmm, what?

vale karma
rich adder
#

0.5f + 0.2f kekwait

#

just write 0.7f lol

vale karma
#

lol thats multiplicaton then addition right?

#

i dont like it either, i jus followed a tutorial

frigid sequoia
#

How?

rich adder
#

and how big is the player, show debug.drawray

frigid sequoia
#

Like why all of them aiming the right side???!!

vale karma
#

player is a 2m capsule

teal viper
vale karma
rich adder
rich adder
#

center?

#

or feet

vale karma
#

ohhhh you know what

#

it probably is because the center isnt at 1m, its at 0 bc i put the components on an empty parent over the model

#

let me try it out

rich adder
#

okay, though personally I would use a bigger shape for like edges, I usually use ray for slope angles n stuff

vale karma
#

what should i use? im still learnin, if theres a better method im down, im already not liking the setup i made. the camera controls the mouse and sensitivity, while the player controls movement, its a bit weird

frigid sequoia
#

Why?

rich adder
teal viper
# frigid sequoia

It does. It's just small. Which is why I told you to make it 5 units.

vale karma
rich adder
ivory bobcat
#

return hits > 0

rich adder
frigid sequoia
vale karma
rich adder
#

just play around with the engine

#

get familiar with components and how they works, scripts etc

teal viper
teal viper
frigid sequoia
#

Like in fact....

vale karma
#

ive already made a couple platformers from start to finish, and dabbled with menus and stuff, I am getting the hang of alot of it without needing to copy code completely. So right now im trying to wrap my head around the correct way to do things, even if its not needed as a beginner. Id rather make sound games with not alot of content than a broken game from youtube tutorials

frigid sequoia
#

From their position TO the target the rayscast is this

#

That's what they are looking towards

#

But why though?

rich adder
teal viper
rich adder
vale karma
frigid sequoia
#

Isn't much different

rich adder
frigid sequoia
#

Oh, I know why, is cause I am using a Vector3 instead of a transform rigth?

teal viper
frigid sequoia
#

Unity doesn't like that

teal viper
vale karma
teal viper
#

Where are you planning to use the transform anyway?

frigid sequoia
#

Cause the issue comes from when passing the target possition to the LookAtTarget, and I am pretty sure about that

rich adder
vale karma
#

@rich adder i dont have a character controller anymore :/ i gave it up for rigidbody

rich adder
teal viper
vale karma
frigid sequoia
#

Is returning using the correct positions in the debug, like those are the exact coordinates of the cube, but then is trying to look at that angle which is clearly not rotatingTowards the target

ebon robin
#

or 2.5d games

vale karma
#

ive tried my hand at it, im not ready to get into tilemap optimization yet, and i want to freeroam, so im doin 3d for now

teal viper
frigid sequoia
#

I have read it, I didn't understand shit

#

I curse the quaternions

#

Like why do we need them having Euler?

teal viper
#

To avoid gimbal lock and other nasty issues.

#

If you don't like quaternions, why not just set the object transform.forward instead..?

frigid sequoia
teal viper
#

You can set it and unity would rotate the object accordingly.

frigid sequoia
teal viper
#

To the direction you want it to face.
*To the desired forward direction.

vale karma
#

how can i smoothdamp the camera movement?

#

im guessing using Addforce is causing the camera to stutter or update weird

native seal
#

What are the use cases for a singleton over a static class? Which should my save system be?

night mural
# native seal What are the use cases for a singleton over a static class? Which should my save...

A static class is basically a freely read/writable global. Globals are generally bad, because they can be written from anywhere and therefore are easy to make mistakes with which are confusing to track down, and because they make it harder to test parts of your code in isolation.

A singleton is preferable because it's at least an instance, so in theory you could build another 'instance' of your game which includes its own version of that singleton, or you could make an instance of it for testing which isn't global. In practice though, most singleton implementations I've seen intentionally prevent these advantages and are globally accessible through a static reference, in which case I'm not sure there's much of an advantage.

Ideally you would compose your game out of non-global pieces which you can freely have multiple of in whatever context you need. If your game requires a single instance of a specific service you'll want to handle that properly, but that's different than how I see a singleton usually used where the code depends on there being a single instance of some global thing

native seal
#

would it be preferrable to use a singleton instance or just a static class

teal viper
native seal
#

right now im using a static class and its working fine, but is that the best choice?

#

will I run into problems down the line

night mural
#

maybe, but you can't pre-empt every problem and you shouldn't try

#

one good reason to avoid statics is if you want to turn off domain reloading, which can help you iterate faster

#

but you could also use them and just handle that yourself

native seal
#

what do you mean?

night mural
native seal
#

oh, so just an editor thing

#

wont effect the game

night mural
#

it might help you make the game more quickly, which affects it in that it needs to be made to exist

native seal
#

lol true

night mural
#

not existing is the biggest problem most games have

vale karma
native seal
#

so turning it off only effects static fields

#

everything else will reset properly

#

since it will technically leave scope

frigid sequoia
#

That just seems like the slerp I was doing at the beggining

night mural
native seal
#

im only really using static methods

frigid sequoia
#

Man, this is literally just, looking at a specific target with a transition, it can be that difficult, like wtf, I am tired of this issue

night mural
#

oh, static methods are great and you should use them as much as you'd like

native seal
#

and one static hashset for my item database which doesnt need to be reset anyway

frigid sequoia
#

Danm you quaternions

night mural
#

yeah it sounds like you do have some static data

grave forge
#

guys help pls i need help so bad

native seal
#

yes only the item database

night mural
#

but also it sounds like data which is reasonable enough to have be global, so have at it

native seal
#

aight thanks for the tips

night mural
# native seal yes only the item database

yeah. I would instance that (maybe as an SO) so that if i wanted to, i could have multiple item databases and swap those in for testing or whatever but it's not a big deal

native seal
#

yes its an SO

#

already

grave forge
#

tf is "assets\pickle.cs(7,12): error CS0246: The type or namespace name 'Rigidbody2d' could not be found (are you missing a using directive or an assembly reference?)"

native seal
#

cause i was planning on doing that

#

but havent had the need to make multiple databases yet

night mural
night mural
rare basin
#

using statement for rb2d?

grave forge
# rare basin show the code

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

public class pickle : MonoBehaviour
{
public Rigidbody2D Rigidbody2D

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

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

}

rare basin
#

the same as the type name

grave forge
#

ik

#

but even if i remove that

night mural
rare basin
#

well you can but

#

don't do it

grave forge
#

it still persesting

rare basin
#

remove that line, save it

#

go back to unity, what does the console says

grave forge
#

i removed it

rare basin
grave forge
#

Assets\pickle.cs(7,35): error CS1002: ; expected

rare basin
gaunt ice
#

!ide

eternal falconBOT
night mural
rare basin
#

you cannot do such thing

night mural
#

...that's not what i said?

rare basin
grave forge
#

hey it worked

#

wow

#

im putting u in credits

teal viper
frigid sequoia
frigid sequoia
native seal
#

so for my save system, i want it to loop through all things that implement the interface "ISavable." when the game starts. what would be the best way to do that? should I just make a public list and add them all manually?

#

or make the save system a singleton and use an event

teal viper
vale karma
#

could i add a rigidbody to the camera 😮

charred spoke
#

You could

frigid sequoia
teal viper
frigid sequoia
#

Like isn't that literally its purpose?

vale karma
#

idk why this pov is so jittery when i move, i never had this before

teal viper
#

Rotation is relative to the object, not to the world origin.

teal viper
charred spoke
teal viper
#

That's it's purpose.

native seal
charred spoke
#

Sure thats one way

native seal
#

is that what you would recommend

grave forge
#

how do i go back to original text cursor?

frigid sequoia
rare basin
grave forge
#

thx m8

frigid sequoia
teal viper
charred spoke
# native seal is that what you would recommend

I would not implement ISaveable on a monobehaviour. A simple class that can ne easily serialized and just holds data will do. It can register itslef in its constructor that way it cant be missed.

native seal
#

I am using it on scriptable objects, not a mb

frigid sequoia
#
  1. I am refering to a random position at which they are looking at, it is actually a rotation, but they all are all aiming at the same Position in the distance, is not like each one is changing it rotation locally
  2. I am using it correctly, I have literally copied the documentation and replaced the values, it is still pointing there after the changes
teal viper
# frigid sequoia 1. I am refering to a random position at which they are looking at, it is actual...
  1. This is because you're using the debug ray incorrectly as well. If you use Debug.Line instead you'll see that it is correct.
  2. What you have is totally not the same as the docs:
    Your code:
Quaternion lookAt = Quaternion.LookRotation(targetPosition);

Notice that targetPosition is an actual position, not a direction.

Docs code:

        Vector3 relativePos = target.position - transform.position;

        // the second argument, upwards, defaults to Vector3.up
        Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
        transform.rotation = rotation;

Notice how relativePos is a direction, not a position.

#

Maybe you should spend some time trying to understand what I'm saying and/or read through the docs and try to understand them, instead of blaming unity, quaternions and the rest of the world, trying to prove that your code is correct.

frigid sequoia
teal viper
#

Does that make sense?

frigid sequoia
#

It does, I have done this, I have change it, it is STILL doing the exact same thing

#

As if I changed nothing

frigid sequoia
vale karma
#

why is it taking unity longer and longer to click play or load?

night mural
vale karma
#

i just reloaded unity to free some ram, ive been working on this for about 10 hours straight lol

night mural
#

yeah it's good to restart unity every once in a while too

vale karma
#

i cant seem to find out where the mouse jitter comes from. I even commented out the new input system and used the old input system to see if it fixes the laggy issue but its not goin away

vale karma
#

so when i move the player, no jitter, when i jump and move the player, no jitter, when i move the mouse, no jitter, when i move the mouse and move the player, jitter

teal viper
vale karma
#

i thought so too, i changed it from gameObject.transform.rotation to rb.rotation , what can i do to fix that?

teal viper
#

Angular velocity or torque.

#

MoveRotation might be fine too

vale karma
#

i used a character controller the first time setting this up, so i guess i never saw this issue, idk how to use torque or angular velocity,doesnt MoveRotation use character controller?

teal viper
#

No. It's a method of an rb

#

Check the documentation

vale karma
#

i wish i didnt have work today, i could sit here for hours learnin about this stuff

vale karma
# teal viper Check the documentation

okay so Unity docs say "If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MoveRotation will resulting in a smooth transition between the two rotations in any intermediate frames rendered. This should be used if you want to continuously rotate a rigidbody in each FixedUpdate." and that rb.rotation teleports a rb from one rotation to another

cobalt solstice
#

I asked before here about some local saving data stuff, I'm now trying to look at a login. Everywhere I search is all using firebase but I'm wondering if there's any way I can do a local one at all so that I can personalise what will be used for the login details. Would this be done by just using methods through the local saving data that I mentioned or would it be done otherwise?

teal viper
cobalt solstice
night mural
cobalt solstice
#

User profiles where their times to complete get saved

night mural
#

but no passwords or security or anything

native seal
#

anyone know why OnApplicationQuit is not calling when I exit play mode?

night mural
#

then yeah you can just do that locally, even just using the filesystem (make a folder for each profile and read those/let the user select one on game start)

cobalt solstice
night mural
night mural
#

oh sorry

#

what's the point of a local password?

cobalt solstice
night mural
#

and those people trust enough to share a computer, but not enough to play their correct profile or whatever?

cobalt solstice
#

🤷‍♂️

night mural
#

basically it depends how secure you want to be

#

is why i'm asking this

#

lke if you need real security, it's going to be some work

cobalt solstice
#

I can look at using firebase it's just I can't use library IDs on there

night mural
#

if you just want people to input a username and a password and you have those stored in text (or compiled into the game) somewhere and it's ok if people can find them if they try, that's different

cobalt solstice
night mural
#

if there's no reason for the game to connect to a server i wouldn't want to use firebase

#

unless you want to store your data in there anyway i guess

cobalt solstice
#

Ye that's why I was checking in the first place, seemed unnecessary

night mural
#

well it's your code so you can have it do anything

#

if you want to prompt them for a username and password then you can

cobalt solstice
#

Just wasn't sure if I'd be using the regular way to save data

languid spire
#

If you want something which is semi-secure. Encrypt the user data using their username/password as the encryption key

night mural
#

and you'll have to decide how you want that to work and where those passwords come from and are stored and how secure they need to be

night mural
cobalt solstice
#

Ty

vale karma
#
Quaternion deltaRotation = Quaternion.Euler(playerRotation * Time.fixedDeltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);

if i remove rb.rotation, then the playermodel doesnt rotate, but if i leave rb.rotation in, then the player model rotates really slowly indefinetly until i move the mouse the other way.

#

i followed the Unity documentation, im trying to get the player model to follow the mouse input

delicate tangle
#

can someone help me when i try put this on bones it says this

#

they are the same tho

teal viper
#

What about compile errors?

languid spire
delicate tangle
#

ok

languid spire
#

That looks like you are using a lower case i in the filename but an upper case I in the class name

#

even though we cannot see the full fle name

native seal
#

anyone know why the Awake() on my singleton is being called between scenes even though it is dont destroy on load

north kiln
delicate tangle
native seal
#

its when i switch back to the scene it was initially in

north kiln
#

So it does exist there

native seal
#

ah yea

#

how do I fix that?

languid spire
#

if you have your singleton code in Awake and it's done correctly, there is nothing to fix

night mural
# native seal how do I fix that?

if your singleton itself were an SO, it would persist between scenes naturally and you wouldn't need to worry about any of this
you could also have a wrapper scene which loads sub-scenes, and then you can put your singletons and any persistent stuff in there so that it's only loaded once

native seal
#

so just make a initilization scene that switches immediately?

night mural
#

yep, or with a little menu with a 'start' button or something, because eventually your game will probably have a menu

native seal
#

aight thx

delicate tangle
delicate tangle
languid spire
#

you have 2 errors there

delicate tangle
#

oohhhhhhhhhhhhhhhhhhh i see that

languid spire
#

duplicate script/class

bold nova
#

Im trying to subscribe to an event in game manager, i realized singleton in it, so theres only one static instance of it, which i initialize in OnEnable, also i have bunch of listeners like background, timer etc. On those script i try to subscribe to an event in Awake method but i get null reference exception because instance is null

Here i set the instance of the session manager
 private void OnEnable()
 {
     if (Instance == null)
         Instance = this;
     else
         Destroy(gameObject);
     Debug.Log("Instance set");
     playerController.OnPlayerDied += EndSession;
 }

and try to subscribe to it, but i get null reference exc
 private void Awake()
 {
     SessionManager.Instance.OnGameOver += FinishTask;
 }
#

I thought that unity calls OnEnable() first, so by the time code is in awake methods of the background class, instance was already set

teal viper
languid spire
#

why do so many people think Destroy stops code execution?

bold nova
#

well, it is on;y in case another sessoin manager already exist

delicate tangle
languid spire
teal viper
bold nova
#

no, the logic was, if theres no game manager it would assign the first game object to the static insstance field and than subscribe that instance to playerDied event, if one game manager already exist, i dont need that game object and it should be destroyed

dapper egret
#

So if i make my start and awake methods public i would be able to manually call them,need to reinialize for multiplayer?

vague dirge
#

Hi, how could I mimic a Mario-like jump ? What I mean is that when my character jumps, it can move it the air as if he was on ground, and so he moves to freely during the jump. In Mario, you can alter the jump direction, but slightly, so you don't get frustrated if you land right after an edge for example. It stored the jump direction of my character as a vector, and summed it with the character direction vector, but when I do that, it can't go back for example. If I lower the speed, the whole jump would be slower and the problem is not solved. I think I should maybe set all the others directions "slower" than the jump direction maybe, but that seems too complicated. Does anyone know how to achieve this please ?

dapper egret
languid spire
dapper egret
languid spire
#

then you are probably better using OnEnable & Start rather than Awake & Start

delicate tangle
#

now im trying to put the circled bone into head and its saying that

languid spire
#

yes, exatly what it says

rare basin
#

also this is a code channel

teal viper
languid spire
#

not even sure why you would want to do that

dapper egret
eternal falconBOT
#

:teacher: Unity Learn ↗

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

delicate tangle
teal viper
delicate tangle
#

oh thank you very much

cinder spruce
#

Tags are changes inside the OnButtonClick method

languid spire
#

not gonna work, you cannot update and save changes to GameObject/Transform data at runtime

#

not that I'm recommending this, but you could save/load the tags to PlayerPrefs

cinder spruce
languid spire
#

use the gameobject name as the key and the tag as the value ?

cinder spruce
#

In fact what i want to do is to save the color of the changed buttons and load them when the scene is reloaded. This is the only method i could come up with so far

languid spire
rare basin
#

you can save the floats

#

then load the color based on these floats

#

r,g,b,a

cinder spruce
languid spire
rare basin
#

save each button's color

#

"Button1Color" "Button2Color" as a saved strings to player prefs

languid spire
#

I cannot believe you are seriously suggesting that

rare basin
#
for(int i=0; i < buttons.Count; i++)
{
    var saveString = $"Buttons{i}Color";
    Color buttonColor = buttons[i].GetColor();
    //save to player prefs the color 
}

or just JSON it

willow nexus
#

I want this gui popup box to be positioned so the top right corner is where the mouse is.

However, it also needs to be able to adjust for the size of the image inside it, which can change.
I thought i solved it but it changed based on screen size.... so if i fullscreen etc it displays differently

how can i do it properly thinker

#

current script is just this ```using UnityEngine;

public class CursorFollow : MonoBehaviour
{
public Vector2 offset;
private RectTransform rectTransform;

void Start()
{
    rectTransform = GetComponent<RectTransform>();
}

void Update()
{
    FollowCursor();
}

private void FollowCursor()
{
    Vector2 canvasPosition;
    RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)transform.parent, Input.mousePosition, null, out canvasPosition);
    rectTransform.anchoredPosition = canvasPosition + offset;
}

}```

cinder spruce
#

Line 77 SwapButtonColors, Line 84 SwapStats

languid spire
cinder spruce
languid spire
gilded sinew
#

is there a way to loop through all tiles of a tilemap (which are 3D game objects) and extract their position and name for example

#

i have a code that is working and is using raycast for that but is there a way to make it without raycast

cinder spruce
languid spire
cinder spruce
#

"Severity Code Description Project File Line Suppression State
Error CS0117 'PlayerPrefs' does not contain a definition for 'DeleteKey' Assembly-CSharp C:\Users\Ömer\Desktop\2d Samurai Game\Assets\Scripts\StatExchangeMenu.cs 160 Active
"

languid spire
#

my bad, change DeleteKey to Delete

cinder spruce
languid spire
#

yes, at least I'm pretty sure they are, maybe Unity added some new ones since I wrote the asset

#

Thanks for spotting that, I will update the asset to handle DeleteKey

cinder spruce
#

ok so where should i add the code to get the color of all buttons in all three arrays, inside the SwapButtonColors method?

languid spire
#

show your code

cinder spruce
#

i managed to save the stats, i don't understand why colors are too complicated to save. I think the array thing complicates things

rare basin
#
    public Transform[] healthButtonsParent;
    public Transform[] speedButtonsParent;
    public Transform[] damageButtonsParent;

why are you stroing them in array of transforms

#

why not Button[]?

#

i see you are doing GetComponent<Button>() everywhere

gilded sinew
#

guys i could really use help regarding tilemap

rare basin
#

any context? elaborate pls.. learn how to ask questions

#

how are we suppoesd to know what is wrong

#

and what is the expected behaviour

gilded sinew
#

so, when i print bounds and local bounds i get numbers that dont correspond with tilemap size

#

it has 10 000 tiles all next to each other

#

yet bounds are like its single cell or no cells at all

#

reason for doing this is i want to itterete through all tiles in tilemap and get their cell positions and name

#

so i can pair them

low path
#

Where’s “here” being printed?

languid spire
# cinder spruce https://hatebin.com/hmewqflkwr

tbh and not to be rude, but your code is awful but, you probably want something like this

void SwapButtonColors(Transform redButton, Transform whiteButton)
    {
        if (canSwap)
        {
            Image redImage = redButton.GetComponent<Image>();
            Image whiteImage = whiteButton.GetComponent<Image>();
            Color tempColor = redImage.color;
            redImage.color = whiteImage.color;
            whiteImage.color = tempColor;

        PlayerPrefs.Set(redButton.name,redImage.color);
        PlayerPrefs.Set(whiteButton.name,whiteImage.color);
        }
    }

You then need to see where you do the PlayerPrefs.Get to restore the state

gilded sinew
#

i really dont understand why are bounds such...

cinder spruce
#

awake method?

languid spire
#

Awake would be good

cunning rapids
languid spire
gilded sinew
# cunning rapids What're you trying to do exactly

i want to itterate through all tiles of a tilemap and store their position and name. I do have code that works using raycast but when using mesh collider, project gets incredibly laggy because of lot of mesh colliders on the scene, so i am trying to do it without it

gilded sinew
gilded sinew
gilded sinew
#

well

#

i never had this line of code

#

Tilemap tilemap = GetComponent<Tilemap>();

languid spire
#

whoops

gilded sinew
#

actually i shouldnt need it because script is not attached on that tile

#

but on other one so i am passing tilemap as reference in inspector

cunning rapids
gilded sinew
#

uhm not sure what you mean

#

my tiles are 3D objects

#

3D hexagons

cunning rapids
#

Oh shit

#

I misunderstood the question

#

My apologies

gilded sinew
#

all good

cinder spruce
final lark
#

Yo, im making a top down shooter.

Im trying to make a gun rotate so that its barrel points at the mouse, but didnt figure a way to di that, so im asking for help here

cinder spruce
languid spire
cinder spruce
#

ok, i'll give it another shot

languid spire
#

the documentation is pretty clear use either

Color color = PlayerPrefs.Get<Color>("key");

or

Color color;
PlayerPrefs.Get("key", out color);
fierce shuttle
final lark
#

Tbh i didn't search for the problem, i tried a bunch of solutions i made up and they didnt work

#

Do you have any recommendations for places to search for solutions in?

fierce shuttle
final lark
#

Ight

cinder spruce
languid spire
cinder spruce
languid spire
#

no time like the present

#

@cinder spruce tbh all of this would be much better in a script attached to each button so you can use OnEnable to Get and OnDisable to Set

#

purely from a design perspective

late bobcat
cinder spruce
languid spire
#

redImage and whiteImage are cached Image's. It's so you don't repeat GetComponent like you were doing

#

if you look at my code you will see I am using the button names as the keys

fierce geode
#

Is using Vector3.project a poor way of giving tight control when it comes to moving a character around? I found that using it and projecting the velocity vector around the players input gives some tight control

keen dew
#

define "tight control"

fierce geode
#

as in, tight as in the time between dictating a direction and the character finally moving in that direction

slender nymph
#

i don't see how Vector3.Project has anything to do with that 🤔

frosty hound
#

Projecting a vector has no bearing on tight controls

fierce geode
#

I thought projecting the velocity vector, basically the forward velocity towards the directions of the players input would give tighter controls

frosty hound
#

The input is already giving you the direction

#

How fast you accelerate and turn is entirely based on your implementation

#

But protecting the input isn't going to do anything useful

slender nymph
#

that line has nothing to do with that error. you need to remove the UIElements using directive

fierce geode
#

I found that doing like
rb.velocity = Vector3.Project(rb.velocity,new Vector3(playerinput.x,0,playerinput.y));
gave me tighter control over my character

#

maybe its just my dodgy code lol

slender nymph
#

show the full !code

eternal falconBOT
fierce geode
slender nymph
#

you are using GetAxis instead of GetAxisRaw. the former applies input smoothing, the latter does not

#

you do not need the line to project the velocity, you just need to stop smoothing the input

burnt mantle
#

hi guys, i have a character controller and when i setup the gravity my velocity.magnitude of the character controller is zero when i move and if i jump its not zero someone can help me pls ?

slender nymph
#

see #854851968446365696 for what to include when asking for help. you're not providing enough info/context which is why you didn't get an answer the first time you asked

fierce geode
#

Okay, the turning circle is not as loose as before. So yeah there was definitely a problem of input smoothing. Could afford to have the movement be tighter, but I could probably mess around with how I deccelerate my character to achieve the same effect.

cinder spruce
#

@languid spire i added these in awake:

 Color redImage = PlayerPrefs.Get<Color>("redButton");
 Color whiteImage = PlayerPrefs.Get<Color>("whiteButton");
#

no errors but didn't work either

slender nymph
fierce geode
#

Ah okay, I've just kind of assumed when moving something to always apply delta time to keep the movement the same speed regardless of frame rate.

#

anyway, thnak you @slender nymph ❤️

cinder spruce
burnt mantle
earnest atlas
#

I have multiple enemies that I want them to use waypoints as coordinates to travel to.

As of now Im using this code https://hatebin.com/zmqmjolqiz

Im not sure if this is good way. I noticed enemies getting stuck on right side of the movement. And I think its doing too much calculations.

#

Is there better ways to deal with moving multiple objects at same time?

slender nymph
# burnt mantle So my problem is when i ApplyGravity the variable currentSpeed return 0 and when...

multiple calls to CharacterController.Move are probably what is fucking that up. you probably need to combine your gravity and actual movement into a single call. execution order of when Move is being called will also likely affect it
https://docs.unity3d.com/ScriptReference/CharacterController-velocity.html

Note: The velocity returned is simply the difference in distance for the current timestep before and after a call to CharacterController.Move or CharacterController.SimpleMove.

languid spire
gritty parcel
#

Hello, I am a beginner. Does someone now how I can make this fit? The wall should be the size, of the white wall on the right.

slender nymph
#

this is a code channel

gritty parcel
#

but there is no channel for art questions

slender nymph
#

yes there is. look in id:browse and maybe you'll find them

languid spire
#

really?