#💻┃code-beginner

1 messages · Page 373 of 1

stuck palm
#

I see, what other differences are there between structs and classes apart from the value type Vs reference type thing? Cus I saw you could use methods in structs so it's basically just a class no?

teal viper
#

You could use methods in primitive types, like int, too.
Methods are not a defining feature of classes.

final kestrel
#

https://hatebin.com/fvwnrpkwvl I am following a tutorial which I talked a bit about yesterday. I have this script but it says cannot resolve symbol properties. I could not find a fix for this

teal viper
final kestrel
#

It says the type or namespace name 'Properties' does not exist in the namespace 'Unity'(are you missing an assembly reference?)

keen dew
#

Did you install the Properties package?

final kestrel
#

no because I could not find it in the package manager

teal viper
final kestrel
#

All right. Sorry.

keen dew
#

You can't just skip the package installation if you can't find it. You can't use the package if it isn't installed

final kestrel
#

I see. I have to install the package all right. I cannot find it though. I'm just searching for properties but maybe its named something other?

hexed terrace
#

Not all packages will show up in the PM, some need to be added manually by name. I've never heard of the properties package, so can't say if this is the case

#

There's usually install instructions on the docs

teal viper
#

Share a link

final kestrel
final kestrel
teal viper
teal viper
final kestrel
teal viper
final kestrel
#

Ah so it may be built in in the newer versions? Makes sense. Thanks for the help.

teal viper
#

Or removed in an newer version. Apis change over time.

hexed terrace
#

from the docs, looks like it hasn't been updated in quite some time - and was still in the experimental stage (so won't show up in the list of packages)

spiral narwhal
#

What am I not seeing here?

    public interface IAssetRepository<out T>
    {
        IEnumerable<T> GetAll();

        protected string ResourcePath(); // <-------
    }

    public class StorableItemRepository : IAssetRepository<ItemSO>
    {
        public IEnumerable<ItemSO> GetAll() => Resources.LoadAll<ItemSO>(ResourcePath());

        protected string ResourcePath() => "Items/Storable"; // <------ PROTECTED NOT ALLOWED
    }
languid spire
spiral narwhal
teal viper
#

The base class property needs to be virtual

languid spire
# spiral narwhal

sorry, not what I meant, sealed in the Interface declaration, not the implementation

spiral narwhal
#

Sealed interfaces must implement their behaviour

#

So that won't work :(

spiral narwhal
teal viper
#

I'm not sure what's the question anymore

#

Was there a question in the first place?

spiral narwhal
#

The question was why I was not allowed to inherit protected interface methods, and how to do it instead :p

languid spire
# spiral narwhal
public interface IController
{
    virtual void DoIt() { }
}

class Test : IController
{
    protected void DoIt()
    {
        throw new NotImplementedException();
    }

}
burnt vapor
#

So in your case either make it abstract, or return string.Empty if that works

#

Why do you want to seal the property anyway? If it's not virtual it can't be overridden, so it's sealed

spiral narwhal
#

Mm, let's go a step back. Because maybe that's not what I really want?
What I want is to have a interface that requires its implementors to define a string without making that field public

#

And at compile time

burnt vapor
#

You can specify internal features that must be implemented with an interface, but that's about it

#

What you want does not fall under the purpose of an interface

spiral narwhal
#

I see

#

Thanks anyway

burnt vapor
#

Abstract classes have more control since they allow protected, but this is obviously different over interfaces

willow scroll
#

Hey, I have a simple script with the ExecuteInEditMode attribute. Its Update method is called on runtime. Am I missing something?

[ExecuteInEditMode]
public class Test : MonoBehaviour
{
    private void Update() => print("Test - Update");
}
#

Oh, yeah

teal viper
willow scroll
#

For some reason, from the past experience using it, I thought it disables it on runtime

#

I think the past experience hasn't brought me much then

vast vessel
#

hey guys.
how can i convert WeaponConfig<Firearm> to WeaponConfig<Weapon> to get its public properties?
Firearm inherits Weapon, and WeaponConfig is a scriptable object :

wintry quarry
vast vessel
#

i have idffrent scripts like my weapon manager and UI manager, that need to access the icon Sprite, the dropped prefab, the player prefab, and the weapon type enum.

#

the weapon class is an abstract monobehavior with a Configuration property.
i am trying to override its getter in the Firearm script so that it returns config_ which is of type WeaponConfig<Firearm>

wintry quarry
vast vessel
#

yea

#

they are

wintry quarry
#

So then why do you need the specific subclass

vast vessel
#

for public List<Firemode<TWeapon>> firemodes;

#

and also the GetFireMode method

wintry quarry
#

This seems overcomplicated TBH

vast vessel
#

what shold i do then?

#

firemode needs to be generic

#

cant change that part

wintry quarry
#

Making a non-generic parent class might serve you well

#

Why does fire mode need to be generic

vast vessel
#

idk how to explain it. can we just skip that find another work around?

#

sorry xd

#

i guess i can send over all of my scripts so you can make of it what you will but i dont think anybody has the time or patience to read all of my code

teal viper
#

Firearm might inherit from Weapon, but WeaponConfig<Firearm> and WeaponConfig<Weapon> don't have that relationship. They're 2 unrelated classes.

#

So, Unless you implement a custom convert method, there's not much you can do

vast vessel
wintry quarry
#

My recommendation is to redesign this with less polymorphism, more composition.

teal viper
#

You can cast the Weapon into the specific inheriting class, but that's a meh solution

wintry quarry
#

If the properties are part of Weapon, that's all you need

#

If they're common to all weapons they should be part of Weapon

vast vessel
wintry quarry
#

Weapon should have a non generic WeaponConfig

#

Or at least a way to access it that way

vast vessel
wintry quarry
#

Because you haven't exposed it as a non generic version of WeaponConfig on Weapon

#

You don't have the ability to do that because you didn't make a non generic parent class for WeaponConfig

vast vessel
#

i guess i can do this, but it doesn't seem like a proper solution.

vast vessel
#

WeaponConfig is a scriptable object btw

wintry quarry
#

Of WeaponConfig

#

With all the fields on it except the parts that need to be generic

#

It's unclear what those are

vast vessel
#

the parent class and WeaponConfig

wintry quarry
#

I'm on my phone

#

A lot to type

teal viper
#
public class WeaponConfigBase : ScriptableObject
{ 
//your properties
}
public class WeaponConfig<Firearm>: WeaponConfigBase
{}
#

If you really need generics

#

I rarely ever have a need in them

#

@vast vessel

vast vessel
# teal viper If you really need generics

all of my fire modes, need the ReloadCoroutine, UseCoroutine, and StopUse coroutines.(which are called when the according buttons are pressed)

but heres the thing, i am going to be implementing different fire modes, for specific weapons, and they to get specific properties, from those weapons.
for example, my Firearm_Firemode class, needs to get specific properties, from Firearm, which don't exist in Weapon,
like firearm.isReloading, or firearm.raycastOrigin, and firearm.loadedAmmo.

this is why i made the Firemode class generic. so the methods are also generic and now, all classes inhareting from Firemode, can be used on any kind of weapon.

teal viper
#

Feels super convoluted to me.
I also don't understand how Firemode needing to be generic is related to your previous question.

vast vessel
#

maybe i should leave this till tomorrow, this bricked my brain.

#

idk wtf im doing anymore

teal viper
#

The relationship between all these classes is unclear.

#

What is a Firemode? Is it a mode of firing that a character has? Is it specific to each weapon?

#

So equipping a different weapon changes the way it is fired?

#

Why cacn't it be implemented in the weapon then?

weary egret
#

Why might access token here always be null?

public async Task InitSignIn()
{
    await UnityServices.InitializeAsync();
    await AuthenticationService.Instance.SignInAnonymouslyAsync();
    var playerInfo = await AuthenticationService.Instance.GetPlayerInfoAsync();
    var linkedAccount = playerInfo.Identities;
    if(!linkedAccount.Any(u => u.TypeId == "unity"))
    {
        SignInButton.SetActive(true);
    }
    Debug.Log("Init Sign In is successful.");
    var accessToken = PlayerAccountService.Instance.AccessToken;
    Debug.Log("Access Token: " + accessToken);
}
wintry quarry
wintry quarry
vast vessel
# teal viper What is a Firemode? Is it a mode of firing that a character has? Is it specific ...

here is what im trying to implement:

i have a weapon manager class that needs to have a list of weapons, that i can assign in the inspector,
it also needs to be able to call these functions, on any of these weapons : ReloadInputStarted, SecondaryAttackInputStarted, PrimaryAttackInputStarted and PrimaryAttackInputCanceled

now, i need each weapon, to have several ways of using that weapon, eg:
a rifle needs a semi auto, and an auto mode
a grenade needs a throw, and a drop mode,
a smg, can both shoot normal rounds, and it can also use its under barrel grenade launcher.

i call these firemodes. so the smg i mentioned, needs two fire modes, one for shooting rounds, and one for shooting grenades.
the weapon that has these firemodes, calls a function from its active firemode, and then the fire mode does what its supposed to do, like shoot bullets, instantiate a grenade prefab, or just Log something in the console. the behavior of each firemode will be defined in itsown class and all firemodes need to inharet from one class, so that one weapon could do multiple things.

some fire modes also need to store their ammo on their weapons script. which is why my firearm script, has this :public Dictionary<AmmoType, float> loadedAmmo;
this is where any firemodes that take ammo, store their ammo data.

#

phew

hasty tundra
#

Im trying to setup controller support for my game, and i followed a brackeys tutorial. This is pretty much identical to that code aside from variable names, but it doesnt register the inputs. Any ideas why?

lethal bolt
#

Am i missunderstandig?

swift crag
teal viper
# vast vessel here is what im trying to implement: i have a weapon manager class that needs t...

I don't see why that would require anything to be generic.
WeaponManager => list of Weapons
Weapon => list of FireModes
Weapons setup their specific firemodes from their settings/configs and call the required methods on them. If a fire mode needs to consume ammo, it can either call a method on a weapon with the required ammo type and amount, and the weapon would handle the dictionary, or the weapon could subscribe to a Fired event in FireMode to adjust it's ammo. You could also pass the ammo dictionary to the fire mode during setup and it would do it's own thing without needing to access the weapon at all.
So many ways without using generics, that imho make things way more complicated than they should be.

swift crag
#

You can do that with something like Controlls.Gameplay.Enable();

hasty tundra
#

i thought i was missing something

swift crag
#

Also, I'd just do this in Update instead:

#

tbh i would just do this in Update instead:

move = Controlls.Gameplay.LJoystick.ReadValue<Vector2>();
#

I do this for continuous values.

#

subscribing to performed makes sense for "button" style inputs

#

and one other thing: "LJoystick" isn't a good action name.

#

Actions are supposed to be things you do in the game.

#

like "move" or "shoot"

#

You bind things like "left joystick" or "X button" to those actions

polar acorn
# lethal bolt Am i missunderstandig?

The Three Commandments of OnCollisionEnter:

  1. Thou Shalt have a 3D Collider on each object
  2. Thou Shalt not tick isTrigger on either
  3. Thou Shalt have a 3D Rigidbody on at least one of them
cosmic smelt
#

hi ive been going through unity.learn and its just so confusing what do i do

slender bridge
#
  1. Though Shalt not be using 2d game with 3d collision detection.
slender bridge
cosmic smelt
weary egret
slender bridge
cosmic smelt
#

no

slender bridge
swift crag
cosmic smelt
swift crag
#

you said you are using unity learn

cosmic smelt
#

yeah i just clicked a link and started idk what im doing

swift crag
#

okay, so instead of clicking random links

#

pick the Unity Essentials pathway

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

rose kite
#

Hey guys I'm currently taking unity's junior coding class and I'm kinda stuck on when to use rotations and or spacing between the code and adding other information in between. (sorry if I'm not making sense, I'll put a piece of the code below this)

cosmic smelt
#

i think im on essentials

swift crag
rose kite
hasty tundra
swift crag
#

It gives you the (signed!) angle between two vectors

#
Vector2.SignedAngle(joystickInput, Vector2.right);
#

this gives you an angle between -180 and 180

#

You can then use this angle to calculate a rotation.

#
Quaternion.AngleAxis(angle, Vector3.forward);
#

assign that to transform.rotation and the object will rotate

cosmic smelt
#

@swift crag im doing essentials

swift crag
#

I might have something backwards here, so you may need to do -angle instead of angle.

rare basin
#
        private IEnumerator TriggerEnd(float delay)
        {
            OnMinigameEnd?.Invoke();
            IsPlaying = false;

            yield return new WaitForSecondsRealtime(delay);

            minigameCameraMover.MoveToPlayer();
            Stop();

            Debug.Log(1);
            Debug.Log(inputRestoreDelay);
            yield return new WaitForSecondsRealtime(inputRestoreDelay);
            Debug.Log(2);

            Player.interactionSystem.CanPerformInteraction(true);
            if (endExtensions) endExtensions.PerformActions();
        }

Why is the 2 not printing, but 1 and inputRestoreDelay is printing? The inputRestoreDelay is 0.1s. I'm not disabling the gameobject, not disabling the component and not destroying the gameobject, and not stopping the coroutine anywhere. Time.timeScale is 1

swift crag
#

It's a long enough expression that it's worth putting on its own line.

#

You could just shove that entire expression into the last line

teal viper
cosmic smelt
rare basin
#
    public virtual void MinigameEnd()
    {
        StartCoroutine(TriggerEnd(endDelay));
    }
rare basin
cosmic smelt
swift crag
vast vessel
teal viper
rare basin
swift crag
#

ah, yeah, it's this.StartCoroutine(this.TriggerEnd(delay))

teal viper
swift crag
rare basin
#

@teal viper

vast vessel
teal viper
cosmic smelt
rare basin
#

i tried restarting unity but it didin't help

#

even if i put yield return new WaitForSecondsRealtime(0);

#

it doesn't execute anything below that

swift crag
teal viper
cosmic smelt
vast vessel
swift crag
fossil drum
eternal falconBOT
teal viper
rare basin
#

it's pretty big class tho

teal viper
fossil drum
swift crag
vast vessel
rare basin
#

248 line

teal viper
cosmic smelt
swift crag
#

I literally can't tell you anything. All you've said is "I'm confused by everything".

swift crag
fossil drum
teal viper
vast vessel
#

so what should i do then?

Each fire mode SO holds the configs related to it. here is an example for a firemode, used by all kinds of guns:

rare basin
cosmic smelt
rare basin
#

nothing else

vast vessel
swift crag
rare basin
#

figured it out, i had a StopAllCoroutines() on class that interhited from Minigame

vast vessel
rare basin
#

fixed! 😄

teal viper
swift crag
#

I would punt the runtime logic into a separate class

#

The weapon definition tells the weapon what kinds of things it should do

#

The weapon actually does them

fossil drum
#

So it was the Stop command...

vast vessel
# swift crag that's not a firemode! that's the entire damn weapon!

i need each weapon, to have several ways of using that weapon, eg:
a rifle needs a semi auto, and an auto mode
a grenade needs a throw, and a drop mode,
a smg, can both shoot normal rounds, and it can also use its under barrel grenade launcher.

each of these is a firemode

rare basin
#

thank you

teal viper
vast vessel
#

that sounds a bit wasteful on the memory side of things

#

plus, all weapons that have shared firemodes, will work the same. cant the firemode config process the data?

#

why make an instance for each weapon

teal viper
vast vessel
#

if there are 20 npcs, using a rifle that has 3 firemodes, thats 120 instances

#

instead of just 3 firemode SOs

teal viper
#

Or what do you need it to access on the weapon?

lethal bolt
#

What did i do wrong i cant seem to find out?

teal viper
#

And probably makes it a bit worse too

teal viper
#

If the implementation of the SO is the same for all the weapon types, there shouldn't be any problem

vast vessel
#

what im saying we should do is this : for a normal gun firemode, all of the data(audio clips, damage, force and etc) stored on the SO.
then, have a Use method on the SO, which takes a muzzle transform from the weapon calling it, and then process the shooting using the data on the SO.

vast vessel
#

melee weapons, projectile weapons, raycast weapons and etc will need their own behavior

#

and i want each weapon to have multiple behaviors

#

like a gun that has both a raycast mode, and a projectile mode

#

maybe two raycast modes with diffrant fire rates

#

you get the idea

#

have you played half life 2?

teal viper
#

Well, in this case, I'd have a separation between the SO that holds the mutable config only and the runtime logic, that operates on the specific variables.

teal viper
vast vessel
#

do you remember this gun that could shoot bullets, and launch energy barlls as its seconday attack?

#

im saying is, each of those could be a firemode, and then the weapon script, would call the Use function of each of those fire modes, depending on wich mouse button is pressed

teal viper
#

Yes. I got the idea of what you're trying to implement, quite a while back. There's no need to clarify it.

vast vessel
#

idk

teal viper
teal viper
vast vessel
#

and the Projectile Launcher script and Raycaster would have SO fields for their config

#

right?

#

because that sounds way better then... whatever the fuck this is...

teal viper
autumn tusk
#

making a tutorial system for my game and i have a set of keycodes i want the code to listen for, how do i specify this?

#

i want to keep this as modular as possible

teal viper
ivory bobcat
autumn tusk
teal viper
vast vessel
ivory bobcat
knotty dawn
#

Hey guys, how do I make my player take continuous damage while coliding wiht an enemy?

ivory bobcat
#

Maybe consider using on collision stay (as well)?

knotty dawn
teal viper
ivory bobcat
knotty dawn
vast vessel
knotty dawn
#

ill just lower enemy damage

#

now how do i despawn an enemy?

#

nvm foundout

#

wiat now my enemies arent spawning anymore after 1 dies

#

😭

ivory bobcat
# vast vessel Firearm inherits from Weapon

Well, the SOs are completely different types like a List<int> isn't the same as a List<float> so you'd need to create a new SO instance and extract/cast all the data from the source to the target. Sounds convoluted and you'd probably be better off decoupling some data.

knotty dawn
#

is this how its meant to be...??

#

my enemy spawner keeps cloning and cloning

summer stump
#

That is my guess on what is happening

ivory bobcat
knotty dawn
#

is this what u guys mean?

summer stump
# knotty dawn

Yeah. For 1, that "enemy1" should be a prefab, not an object in the scene

What object is that attached to?

#

And dalphat is asking to see the actual code

knotty dawn
#

alright i can show that

#

this is spawner code

#

and htis is enemy stats

summer stump
#

You are spawning newEnemy

#

enemyPrefab is what should be in every instantiate call

#

Don't even pass a gameobject into the coroutine, just use enemyPrefab

ivory bobcat
knotty dawn
#

guys im so sorry but im completely lost rn 😭

#

i just copied this code

ivory bobcat
#
while(true) 
{
    yield ...
    Instantiate(...)
}```
knotty dawn
#

alright

#

how about time interval?

#

is there a time.sleep or something?

ivory bobcat
#

Why? What exactly are you trying to do with sleep?

knotty dawn
#

oh wait is that the yield line

summer stump
#

instantiate(enemyPrefab)

#

Do not pass in newEnemy to the instantiate call

knotty dawn
#

aite

#

mb if its frustrating, i just started tdy and just yoloed a project without watching any guides ;-;

ivory bobcat
# knotty dawn oh wait is that the yield line

Minor stuff but for optimization purposes, consider caching the new yield instruction before the loop and just yielding that cache in the loopcs var wait = new WaitFor... while(true) { yield return wait; Instantiate(...); }

ivory bobcat
knotty dawn
#

got it

#

so all in start function yeah?

wintry quarry
ivory bobcat
#

In the coroutine before you'd delay/instantiate - before the while loop

wintry quarry
#

Also - yes if you want it to refernece another field, the initialization needs to go in a method

knotty dawn
#

yep ran it and it works

#

yoooo it works, tysm guys

knotty dawn
summer stump
#

Prefabs are blue objects from the "project" window

#

I do recommend you at least go through the essentials pathway here
!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
knotty dawn
#

alright ill take a look at those links, thanks

queen adder
#

how do I do a ground check in 2d?

knotty dawn
#

like this so i can just delete my boi on the screen?

rose kite
#

the box im talking about

cosmic dagger
rose kite
cosmic dagger
#

at least, for an american keyboard . . .

rose kite
autumn tusk
#

is there a function for dontdestroyonloadobjects that activate when a scene is changed

#

tried this and it doesnt work

swift crag
cosmic dagger
autumn tusk
polar acorn
jagged flame
#

Unity project won't start anymore. I discarded all changes in Github back to the last working version and it still won't start. Nothing in the console. How do I troubleshoot this?

swift crag
#

so the project opens, but you can't enter play mode, you mean?

jagged flame
#

I can press play but it's just a blue screen

swift crag
#

you have the wrong scene open, probably

polar acorn
jagged flame
#

Oh you're right

#

Fuck

#

Why did it decide to do that? It's never done that in the dozens of other times I've run it 🤦‍♀️

#

Just wasted all that work, time to kms

polar acorn
swift crag
#

they threw out changes from git

polar acorn
#

Ah

swift crag
#

in the future, consider using git stash

#

or just committing

jagged flame
#

Using github desktop, it stashes all or none 😕

#

Used to VS where you can pick and choose the files

#

Sucks

polar acorn
knotty dawn
swift crag
#

(this is a situation where stashing everything makes sense, of course)

knotty dawn
#

i didnt touch the script at all

polar acorn
swift crag
#

you didn't have to touch the script to cause an error

knotty dawn
jagged flame
knotty dawn
summer stump
polar acorn
# knotty dawn

Then there exists an instance of EnemyStats where player is not set

summer stump
#

Oh huh. Different wrror?

knotty dawn
#

and how do i go about fixing it?

polar acorn
swift crag
knotty dawn
swift crag
#

That is not the enemy1 prefab.

#

That is C# code.

polar acorn
swift crag
#

Do you not know what a prefab is?

knotty dawn
#

barely

polar acorn
swift crag
#

you should read about how prefabs work

knotty dawn
#

type mismatch? does my player have to be a prefab as well?

polar acorn
swift crag
#

"Type mismatch" will appear when you have an invalid reference.

knotty dawn
#

oh ffs

polar acorn
#

Question: Why is this a public field anyway

knotty dawn
#

my player is an obj on scene

polar acorn
#

why not just use the player you've collided with

knotty dawn
polar acorn
swift crag
#

if the enemy only cares about the player when they hit the player, you don't need to tell them about the player in advance

#

you just whacked into the player

polar acorn
#

I would say yes it's bad practice to use something that literally does not function

hasty sleet
#

It doesn't have to do with the field.

#

The field is not causing it to break.

knotty dawn
hasty sleet
#

It's the fact it's not set properly

polar acorn
swift crag
#

changing it to private would simply guarantee that player is null

knotty dawn
#

im kinda lost sry

swift crag
hasty sleet
#

Enemies should probably automatically find and store a reference to the player script.

swift crag
#

would your bullet class look like this?

#
pubilc Enemy enemy1;
pubilc Enemy enemy2;
pubilc Enemy enemy3;
// ...
pubilc Enemy enemy100;
polar acorn
# knotty dawn wdym by this?

They mean that if the enemy only cares about the player when they hit the player, you don't need to reference the player in advance

#

use the object you hit

#

You're already checking its tag so you know how to reference it

#

Just, use that

late burrow
#

why material.shader.renderQueue is 3000 in editor while being 2000 when checked with code

knotty dawn
polar acorn
knotty dawn
#

its literally my first day of unity so i actually dont know what im doing

#

xd

polar acorn
#

and understand what it does

hasty sleet
knotty dawn
hasty sleet
knotty dawn
swift crag
#

If you've copied every line of code, then you will have no idea how to write your own code

#

Consider !learn .

eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
#

you'd just check if you hit an enemy, and if you did, you'd deal damage

#
Enemy enemyComponent = collider.GetComponent<Enemy>();

if (enemyComponent) {
  enemyComponent.Hurt(10000);
}
#

perhaps

knotty dawn
#

i understand what youre saying but idk how to apply that to my own code, sry

#

ill just take a step back and learn more first

#

before attempting this

#

thanks for all the help tho guys!

hasty sleet
# knotty dawn thanks for all the help tho guys!

Look into coding with C# and unity fundamentals first. If you copy code without understanding it, you're building your foundation on unstable ground. You don't even understand your current position, even less so how to progress from it.

knotty dawn
hasty sleet
dense root
#

Cannot tell you how many times I've made the mistake of just copying code

knotty dawn
#

wanted to try to make a game before I start working so i felt the pressure

burnt mantle
#

Hi guys i'm making a prop hunt like game and i have groundCheck with Collider.bounds.extents.y but with some model my result don't return true someone know why ? or have a better method to do a groundcheck

vernal thorn
#

My game lags so much on android and i dont know why

ornate spoke
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] private bool isPlayer1 = true;
    [SerializeField] private bool isPlayer2 = true;
    public Transform playerPosition;
    [SerializeField] private GameObject bulletPrefab;
    private float rotationStrength = 0.5f;
    [SerializeField] private Bullet bulletScript;
    void Start()
    {
        playerPosition = GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isPlayer1 && Input.GetButton("Fire1"))
        {
            transform.eulerAngles = transform.eulerAngles + new Vector3(0,0, rotationStrength);
        }

        if(isPlayer1 && Input.GetButtonUp("Fire1"))
        {
            bulletScript.Shot();
        }

        if(isPlayer2 && Input.GetButton("Fire2"))
        {
            transform.eulerAngles += new Vector3(0,0,rotationStrength);
        }

        if (isPlayer2 && Input.GetButtonUp("Fire2"))
        {
            bulletScript.Shot();
        }
    }
}

this wont shot for some reason

summer stump
vernal thorn
summer stump
swift crag
golden ermine
#

Hello everyone, I am trying to make Inventory but it doesnt work, I want it that when I pickup an item it will go to the first empty slot and change icon according to item I picked up, I want it to be able to pickup other items while Im holding my item and that other items will be assign to remaining empty slots. And I want it to switch between them with numbers from 1-5 and when I press G on item Im holding it will drop it from hand and inventory. This is Item script thats attached to items:https://hastebin.com/share/ozagayorev.csharp and this is Inventory script attachted to gameobject holding 5 slots(which are 5 ui images): https://hastebin.com/share/uficaziniw.csharp and this is interaction manager script: https://hastebin.com/share/afabehexiq.csharp

polar acorn
ornate spoke
polar acorn
ornate spoke
# polar acorn Whatever has the code you just showed

ok

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

public class Bullet : MonoBehaviour
{
    // Start is called before the first frame update
     public float speed = 50f;
     public Rigidbody2D rb;
    [SerializeField] private Gun gunScript;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
       
    }
    public void Shot()
    {
        Instantiate(gameObject, gunScript.playerPosition.position, gunScript.playerPosition.rotation);
        rb.velocity = Vector2.left * speed * Time.deltaTime;
        Destroy(gameObject, 3f);
    }
}
ornate spoke
#

then what?

ornate spoke
#

should I screen shot it?

polar acorn
#

yes

ornate spoke
polar acorn
# ornate spoke

So, whatever object you have assigned to BulletScript should be cloning itself, then setting its own velocity and destroying itself. I wonder, why are you doing it this way? Your gun already has a reference to the prefab. Wouldn't it make more sense to instantiate that prefab rather than having your bullets clone themselves at some random point in space?

ornate spoke
#

So I should make a method that instantiates the bullet within the gun script instead? I did this because I put a velocity (this was before) on the bullet before it got instantiated and it would go left instead of going in the direction it is facing.

polar acorn
ornate spoke
#

Ill try that, ty

lavish magnet
#

Trying to make this effect in my game where text fades in when an item is grabbed and stuff, and if multiple items are picked up fastly it will show like this and so on

#

But if grabbed too fastly it appears like this?

#

When the first popup starts, it will always be at the same position, something around (0, 177). ANd it lerps to that position, THen while its on screen if another box is picked up, I am lerping the existing popup(s) upwards by 1, to leave room for the new popup to spawn at the same position (0,177). It works slowly but not wwhen pickedup fastly.

eternal needle
lavish magnet
#

I am using a coroutine to lerp them. I assume the issue is: When a popup exists, and the player grabs a new box, the existing popup(s) will all move up to make room, but, whilst those popups are lerping up to make room, if the player grabs another box, the existing popup(s) should account again and their destination should be up more.

lavish magnet
#
    public void MoveUp(float amount)
    {
        //If just spawned in and another one spawns in, adjust endposition to go above that
        if (isMovingUp)
            endPosition += Vector2.up * amount;

        
        //If already moving up due to another and another spawns, adjust out smooth up destination

        smoothUpEndPosition = rectTransform.anchoredPosition + Vector2.up * amount;

        if (isSmoothMoving)
        {
            StopCoroutine(smoothMoveCoroutine);
            smoothUpEndPosition = new Vector2(smoothUpEndPosition.x, smoothUpEndPosition.y + amount);
        }

        smoothMoveCoroutine = StartCoroutine(SmoothMove(rectTransform.anchoredPosition));
    }
    private IEnumerator SmoothMove(Vector2 from)
    {
        float elapsedTime = 0f;
        isSmoothMoving = true;
        while (elapsedTime < moveUpDuration)
        {
            elapsedTime += Time.deltaTime;
            rectTransform.anchoredPosition = Vector2.Lerp(from, smoothUpEndPosition, elapsedTime / moveUpDuration);
            yield return null;
        }

        isSmoothMoving = false;
        rectTransform.anchoredPosition = smoothUpEndPosition;
    }```
#

This is on each popup, MoveUp is called everytime a new popup happens, so it can move up for the new popup. the IEnumerator SmoothMove() is so it can smoothly move upwards.

slender bridge
#

You should try free tools like Dottween

lavish magnet
#

I have DOTween, i cant figure out how to do that here

#

my if (isSmoothMoving) is for, if we are already moving to adjust room for a new one,and this function gets called again (a new popup has spawned) we must adjust our destination

ember spear
#

I feel kinda silly - can anyone remind me of the proper way to check for a spacebar press? Unity 2022.3.30f1

if (Input.GetKeyDown(KeyCode.Space) && (selectedDialogueType == DialogueType.Text || selectedDialogueType == DialogueType.Talk))
        {
            OnNextNode();
        }
#

This isn't working - it does with mouse button down.

lavish magnet
ember spear
#

Hm. Then I think something weirder is going on, because this isn't registering even with debug logging.

#

And without the conditionals

lavish magnet
slender bridge
ember spear
lavish magnet
#

I am attempting dotween right now

eternal needle
lavish magnet
#

Why is that different?

ember spear
#

Does anyone understand why ONLY GetMouseButton(0) works and displays its log here?

        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Mousebutton Left pressed.");
        }
        if (Input.GetMouseButtonDown(1))
        {
            Debug.Log("Mousebutton Right pressed.");
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Spacebar pressed.");
        }

I'm using the Old Input System - is there something else that could be blocking this?

#

This is all in Update()

lavish magnet
#

Space doesnt work?

#

Show the entire script?

#

Is the script on an active object?

#

The code is correct theirs something else messing with it

ember spear
#

This is the entire update method - like I said the mouse button 0 (left click) works, the obj is definitely active.

private void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            OnNextNode();
        }
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Mousebutton Left pressed.");
        }
        if (Input.GetMouseButtonDown(1))
        {
            Debug.Log("Mousebutton Right pressed.");
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Spacebar pressed.");
        }
        LayoutRebuilder.ForceRebuildLayoutImmediate(TextMessageContainerRectTransform);
    }
lavish magnet
#

If you hover over update does it say this?

ember spear
#

The rest of this is just JSON serialization and stuff, nothing else to do with input

polar acorn
ember spear
lavish magnet
#

if you comment out that bottom line will it be ok?

slender nymph
#

restart the editor, that's the usual fix if it isn't properly detecting your input

ember spear
eternal needle
# lavish magnet Why is that different?

Actually now that I look at this again, I'm not really sure how this exact code relates to the issue. It looks like this is just for a single object, but the problem you described was for many. Nothing here really shows that initial step where you spawn or get this text object

ember spear
slender nymph
#

something else is going on here then. are you certain you've saved your code and that it has recompiled after making these changes? are you certain you are using the correct component and that it is on an active object in the scene?

ember spear
slender nymph
#

then there is no reason at all those others wouldn't work unless you're just not pressing the keys or something has fundamentally broken in your project. there are no return statements, no errors in the console (at least in the screenshot you showed) and those are separate if statements so they should work. use the debugger to figure out what is going on 🤷‍♂️

ember spear
lavish magnet
#

😭

ember spear
#

Holy shit I'm in Simulator not GAME 🤦‍♂️

#

Thanks all

lavish magnet
#

what is that 😭

ember spear
#

My game uses a phone UI so I had no idea lol (very similar game UI to real iphone)

#

Simulator is Unity's phone simulation tool.

#

It doesn't handle keyboard Keycode inputs.

#

At least, not in Editor as far as I can see.

shell herald
#

I am currently having a confusing problem with ink and my quest system. when i speak with the npc the first time, it all works great, i can accept the quest and the dialogue ends. but when i speak with the npc again, it starts at the == QuestAccept== section on the ink text rather than the start for no apparent reason.

Script that displays the dialogue and interacts with ink
https://hastebin.com/share/rujakajoji.csharp

Script thatis part of quest progression
https://hastebin.com/share/isotiqavoj.csharp

Ink Text
https://hastebin.com/share/atoqugaxar.rust

polar acorn
lavish magnet
#

Fixed it

slender nymph
#

it should be a law that if you fix something you should say how you fixed it so that people searching a similar issue in the future find what you did instead of just the phrase "fixed it"

lavish magnet
#

yheah i was looking at it to figure out how too 😭

#

Its looking like if the tween was just spawning in, i adjusted its spawn in end position, but i also never stopped it from still doing the original moveup that others were doing

#
    public void MoveUp(float amount)
    {

        //Spawning in and another poup spawns in, we have to spawn in higher
        if (spawningInTween != null && spawningInTween.IsActive())
        {
            spawningInTween.Kill();
            endPosition += Vector2.up * amount;
            spawningInTween = rectTransform.DOAnchorPos(endPosition, fadeInDuration);
        }

        //If already moving up due to another and another spawns, adjust move up destination to move up more

        if (moveUpTween != null && moveUpTween.IsActive())
        {
            moveUpTween.Kill();
            smoothUpEndPosition += Vector2.up * amount;
        }
        //If not already moving up, our position is just up by amount
        else
        {
            smoothUpEndPosition = rectTransform.anchoredPosition + Vector2.up * amount;
        }


        //Move from current position, Upwards to account

        if (!spawningInTween.IsActive())
            moveUpTween = rectTransform.DOAnchorPos(smoothUpEndPosition, moveUpDuration);

    }
``` ended up with this
final kestrel
#

Hey all. I have been studying serializing and deserializing. I got confused at one point. When I deserialize, dont I need some kind of Identification to put the data back into my lets say Player object? or is it enough to just match the deserialize data to my player data? Will it automatically put stuff in my Player?

languid spire
stiff fjord
final kestrel
final kestrel
obtuse cove
#

Update:

  1. Terrain now only has the "Tilemap Collider 2D".
  2. To ensure that there was a collision between the fireballs and the ground, I checked the "Is Trigger" option together with the one that was always active, namely "Used By Composite".
  3. I created a separate script for fireball collisions: https://gdl.space/kirizuyujo.cpp

But now that the fireballs get destroyed, when they collide with both types of terrain, as soon as I click play, the character starts crouching without being able to get up even though he can move and immediately falls through the terrain.

languid spire
final kestrel
arctic shadow
#

hey, can anyone help explain to me why my code defualts the resolution to one that isnt native to my monitor? It happens when i build and run. Here is the code:

dense root
stiff fjord
shell herald
dense root
#

So when your player interacts with the NPC the QuestAccept is triggering right away?

shell herald
#

yes

#

but only the second time i talk to that npc

#

the first time works normal

dense root
#

Interesting

#

What do you suspect is causing that?

arctic shadow
vestal adder
#

considering making my own pathfinding system

shell herald
#

i have added the scripts i deem most relevant to this in the other pastebins

dense root
dense root
#

So it works the first time, right? Something must have changed the second time you talk to the NPC for it to behave differently.

shell herald
#

yes, because the first time, you accept the quest. and when the quest is already accepted, the dialogue has a different behaviour, however the starting point is identical, it should start the same way, but it doesnt

dense root
#

If I had to guess based on skimming your code it would have something to do with this:

    private void HandleTags()
    {
        if (story.currentTags.Count <= 0)
        {
            return;
        }

        foreach (var currentTag in story.currentTags)
        {
            if (currentTag.Contains("addQuest"))
            {
                var questName = currentTag.Split(' ')[1];
                var quest = questConfig.quests.First(q => q.GetId() == questName);
                GameState.StartQuest(quest);
                // FindObjectOfType<QuestLogView>().ShowActiveQuests();
            }

            if (currentTag.Contains("removeQuest"))
            {
                var questName = currentTag.Split(' ')[1];
                GameState.RemoveQuest(questName);
                 // FindObjectOfType<QuestLogView>(true).ShowActiveQuests();
            }
        }
    }
#

Hmm maybe not... hard to tell without touching it myself

warm condor
#

hey guys, can someone here explain me what an abstract class is, and what it means to implement a class?

shell herald
dense root
shell herald
#

currently my suspect is this section

    {
        FindObjectOfType<PlayerInput>().enabled = false;
        gameObject.SetActive(true);
        story = new Story(textAsset.text);

        Cursor.visible = true;
        Cursor.lockState = CursorLockMode.None;

        foreach (var quest in GameState.GetCompletableQuests())
        {
            story.variablesState["finished_"+quest.Quest.GetId().ToLower()] = true;
        }

        foreach (var quest in GameState.GetActiveQuests())
        {
            story.variablesState["started_"+quest.Quest.GetId().ToLower()] = true;
            Debug.Log("Queststarted is true");
        }

        ShowStory();
    }```
#

because that debug log does not trigger (it should trigger the second time)

dense root
#

That's likely your bug then, no?

shell herald
#

if it is, i am unable to figure it out. i ve been sitting infront of those lines for hours and idk whats wrong

dense root
#

Have you tried using the debugger?

#

Where it isn't being triggered, and inspect the variable in question

shell herald
#

yes, but the game doesnt actually recognize anything wrong, atleast debugger gives me nothing

dense root
#

Interesting

#

Let's review, so your quest dialog appears on the second press which is unintended, right?

#

Second interaction*

shell herald
#

yes

#

the red is what happens the first time, the blue is what should happen the second time, but the yellow is what actually happens

dense root
#

Oh I see understand your problem

#

Interesting

#

Well something is causing [0, 1, 2] to bypass 1 if I understand how you would arrange dialog like this

shell herald
#

wait a second. i ll try something

crisp tapir
#

Hello! I have a question about displaying health on Unity 2022 LTS. This is the code I used for 2018 to display health but this same code doesn't work on 2022. There must be some change I don't know about with the version. Also I am new to 2022 because I used 2018 for 2 years in college.

slender nymph
#

your text object is more than likely a TMP_Text (or more specifically a TextMeshProUGUI which inherits from that) rather than the legacy Text object. of course you'd be receiving a NullReferenceException at runtime if that were the case and surely you'd mention if you had errors 😉

#

the two separate health variables are also kind of redundant, and the GetComponent call every frame is pointless when you can just store the reference to the component instead of referring to its gameobject to then call GetComponent on that

crisp tapir
#

Thank you so much I did it! lol

willow anvil
#

idk why would u need to assign it and not use

swift crag
#

that's literally the code they already had

#

other than using a different variable

crisp tapir
#

It's for a game I am making. There will be an enemy that will damage the player and the health will start at 100 and go down when the player gets near the enemy

cosmic quail
crisp tapir
cosmic dagger
#

Uh, who is that?

polar acorn
#

I have no idea what a Jimmy Vegas is but you should just use ToString

crisp tapir
#

He does tutorials for Unity

#

Tutorials for making games

#

His videos helped me learn C#

cosmic dagger
#

I'd definitely cache that GetComponent though . . .

slender nymph
#

the entire GetComponent is unnecessary if they just make their healthDisplay variable the correct type

cosmic dagger
#

Also true . . .

swift crag
#

yes, you should just assign a reference to the text component directly

#

GameObject is almost always the wrong type.

warm condor
#

hey guys, can someone here explain me what an abstract class is, and what it means to implement a class?

summer stump
warm condor
#

what do you mean by inherit?

swift crag
#

you should read the whole "Object-oriented programming" section here

polar acorn
swift crag
#

an abstract class is too vague to exist yet

#

but it can still have qualities of its own

#

a common thing I wind up doing is something like this

#
public abstract class Scorer {
  public abstract float GetScore(Item item);
}

public class ValueScorer : Scorer {
  public float GetScore(Item item) {
    return item.value;
  }
}

public class ConstantScorer : Scorer {
  public float GetScore(Item item) {
    return 4;
  }
}
#

every Scorer can give you a score for an item

dry ravine
#

I'm using 2d unity to make a game, when my rigidbody touches the ground object and i try to move the value barely increases, and the value just kind of spasms if that makes sense, changing the decimals very slimly back and fourth

swift crag
#

but I can't create a Scorer

#

(this is a case where you could just use an interface, of course -- but you can also have abstract classes with some concrete code in them!)

swift crag
dry ravine
summer stump
dry ravine
summer stump
#

Oh ok. Well show code

#

!code

eternal falconBOT
warm condor
cosmic dagger
swift crag
#

Abstract classes can contain abstract members, and you can't instantiate an abstract class.

#

An abstract member has no implementation. Child classes must implement it (or also be abstract)

#

That's pretty much it.

dry ravine
#

(jumpheight is for future)

#

using a box colider and a box colider for ground

willow anvil
summer stump
warm condor
swift crag
cosmic dagger
willow anvil
summer stump
swift sedge
dry ravine
summer stump
dry ravine
#

Sorry im probably giving you brainrot with my explanations lmaoo

summer stump
#

It's all good

fervent abyss
#

i get this error even tho i dont have any missing scripts on that gameobject?

hasty sleet
#

I usually encounter this error after deleting a script or storing a field reference to a script that no longer exists

#

Look through all of your gameobjects one by one and check for a missing script, and consider restarting your editor / reloading domain.

fervent abyss
#

i moved and deleted some scripts but they arent related to network runner objcte in any way

hasty sleet
#

There is 100% a reference somewhere that is no longer functional

#

It is up to you to find it.

#

If the problem is "My toast is burnt but I cooked it perfectly", perhaps the assumption is flawed?

fervent abyss
#

i cant find it.... lmao in my scripts on the object i just checked all referenced scripts are present

glad rune
#

im wondering why ToBlue doesnt work. i checked and the skin has the right info. I am changing a skin of a 2d character in ToBlue, maybe i need to change something else. btw i change the animator because the skin changes when it jumps

hasty sleet
#

Reload domain, restart editor, check every game object, and check the inspector window for every game object thoroughly. Check the fields of EXISTING scripts for missing references.

hasty sleet
#

And is as RunTimeAnimatorController redundant? The highlighting in your editor makes me think it is. Mouse over it and check the context actions.

glad rune
fervent abyss
#

oh lol i opened this object prefab and it actually has a missing scirpt

glad rune
#

and it is reduntant yes. idk what that means tho

#

im new

swift sedge
#

it means you can remove it with no errors

hasty sleet
#

This is a variable declaration

#

like public float myFloatNumber

#

What is the actual value of that variable, and is it compatible with the property you're setting equal to the value?

glad rune
#

i put the animator override controller

shell herald
# dense root Interesting

figured it out, as always its a highercase lowercase mismatch and the debugger couldnt catch it because ink text is in a seperate file

glad rune
#

of the blue version of the skin

polar acorn
#

First off, have you put a debug log in ToBlue to ensure it's even running at all?

glad rune
#

yeah it doesnt even run

slender nymph
#

do you have errors in your console? those Find calls then the GetComponent calls can absolutely fail and cause the following code to not run

glad rune
#

nope

slender nymph
#

then you need to debug your condition for calling the ToBlue method

polar acorn
glad rune
#

the skin data doesnt stay the same after i switch scenes

polar acorn
#

Is it supposed to? What's making it do so?

glad rune
#

yeah in the shop when you click a button i call

#

public void JsonEquipSkin(int equipSkin)
{
info.skin = equipSkin;
string SkinInf = JsonUtility.ToJson(info);
string filePath = Application.persistentDataPath + "/SkinInfo.json";
System.IO.File.WriteAllText(filePath, SkinInf);
Debug.Log(SkinInf);
}

#

so json file

slender nymph
#

and are you loading that when you switch scenes?

polar acorn
#

Are you sure you're reading that data back before you attempt to read from it?

slender nymph
#

specifically before this code runs?

glad rune
slender nymph
#

you read the file then deserialize the contents. pretty much the exact opposite of what you are doing in JsonEquipSkin

glad rune
#

yeah i think its the fact that it creates a new one probably when i check because i reference data = SkinInfo.info and not data = SkinData, but i cant reference SkinData because it doesnt derive from monobehaviour.

slender nymph
#

again, you need to deserialize the saved data when you load a new scene

glad rune
#

so the current reference is alright the one where i reference new skindata?

slender nymph
#

after you deserialize the data you assign it to your variable

sick jay
#

if(a != null || b != null)

is a statement like this going to run ONLY if one or the other is true, or will it still work if both are true?

#

^edited to make it simplier

slender nymph
#

it will run if either one is true. that includes both. in fact if the first is true it won't even evaluate the second

sick jay
#

thank you

wintry quarry
polar acorn
#

There's also XOR, which is ^. if (a ^ b) will run only if exactly one of the two is true

dense root
#

I'm using the new input system yet I'm lost on how to debug whether or not I am receiving input correctly in the first place. Any insights appreciated

private void Move(Vector2 direction)
{
    if (CanMove(direction))
    {
        transform.position = (Vector3)direction;
    }
}
#

I guess my question is how do I know the script is receiving input to begin with? Do I use a Debug.Log? Or do I look at this debugging tool shown above

rocky canyon
#

u can debug log direction..

#

or in that debug menu u can find the keys u use.. and watch for them to change..

#

it'll go from 0 to 1 when the key is being pressed

dense root
#

Well of course that is working but I am trying to debug whether or not it is communicating with the script, I'll try to Debug.Log the direction and see what happens

rocky canyon
#

ya, thats the first thing u should try

dense root
#

Yeah it's shooting a blank

rocky canyon
#

is the action set up correctly?

dense root
#

It's my first time doing it, so I'm not entirely sure

rocky canyon
#

and do u subscribe to it and all that jazz?

#

im not too familiar with it but im trying to learn as well

dense root
#

Pretty sure I've mapped out the keys correctly

#

But we need to know whether or not it is firing to be extra sure

rocky canyon
#

can u show ur input script?

dense root
#

The PlayerController.cs? Sure

rocky canyon
#

not the generated one.. but the part where u assign direction

dense root
#

What's super confusing is that it generates all these files like InputSystem.input, PlayerMovement, etc.

rocky canyon
#

heres how mine looks for context

#
    private void OnMove(InputAction.CallbackContext context)
    {
        Vector2 movement = context.ReadValue<Vector2>();
        Debug.Log($"Move: {movement}");
    }```
#

my move function looks liek this

dense root
#

On a cursory look they seem similar

rocky canyon
#

and no console errors?

dense root
#

None

short hazel
#

Code looks correct. If you're not getting the log, then the if statement on line 41 did not succeed. Try placing the log outside of that

dense root
#

Like I said I think what's happening is the input system is not firing, it's probably registering my key stroke, but not communicating that with the script

rocky canyon
#

its enabled correct?

#

in the project settings

dense root
#

Let me triple check

#

Yup enabled

short hazel
#

Also log in Awake, OnEnable, Start

rocky canyon
#

id try loggin in other functions like spr2 mentions too

#

im just brain-storming b/c im new to it as well

dense root
#

No worries, let me take some time here and see what I can do

#

I think this video might offer some insights into debugging the new input system
https://www.youtube.com/watch?v=ICh1ZEaVUjc&t=2s

Learn how to debug your input using the Input Debugger! See all of your controls and their current values, debug remote devices, and visualize your current action values!

ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
https://sam-yam.itch.io/samyam-full-source-code-to-all-videos

🤝 Support Me 🤝
Patreon: https://www.patreon.com/samyg
D...

▶ Play video
#

I'll try some stuff and report back

dense root
rocky canyon
#

no, log the input in those i think is what he meant

short hazel
#

Start isn't logged though

rocky canyon
#

lol

dense root
#

Start isn't used but I can if you'd like

#

Sorry it is

short hazel
#

That's where you tell the input action to notify you when it's triggered, so it's pretty important to ensure it's executed

dense root
short hazel
#

Now place a log in Move() but outside the if statement. If you get the log (when making inputs), then it's the if statement that fails

dense root
#

Like this?

    private void Move(Vector2 direction)
    {
        Debug.Log("Move");
        if (CanMove(direction))
        {
            transform.position = (Vector3)direction;
            Debug.Log("Direction" + direction);
        }
    }
short hazel
#

Yep

dense root
#

You're right, the input is failing

#

Saved me 20 minutes of watching a debugging video

short hazel
#

The input is there

dense root
#

Yeah

rocky canyon
#

the if conditonal isnt being met

short hazel
#

It's your CanMove() function that's returning false

dense root
#

We don't need no fancy tools just logic 😂

#

The player appears to be moving incrementally but stuck, for example when I press the S key twice it won't move the number further

#

it's like they're stuck in one grid cell or something

short hazel
#

Make sure both tilemaps are perfectly aligned. Since you only get the position from the groundTilemap but feed it both to that and collisionTilemap, the method won't work correctly if groundTilemap and collisionTilemap aren't perfecly superimposed

dense root
#

I see... so what is happening is despite there being a tile it registers as false no matter what is pressed. Interesting...

dense root
#

If I'm reading this correctly they are in fact, superimposed

short hazel
#

An alternative would be to duplicate line 50 and change it to get the position on the collisionTilemap, so you have two distinct position variables relative to each tilemap

dense root
#

I'm not sure I quite understand that solution

#

Let me think about it for a second

#

Oh I see get the collisionTilemap instead of groundTilemap

#

Still won't budge

#

OH WAIT

#

Let me try something

#

Nevermind I thought disabling the player's collider might do the trick

#

But I would need it in the long run anyways

short hazel
#

You'll need to modify your code so you can debug all these position values calculated from the tilemaps, as well as the results of both HasTile() calls

dense root
#

Okay on it

dense root
# short hazel You'll need to modify your code so you can debug all these position values calcu...

Wait the result of HasTile is always false right now, we wrote debug calls for that

    private bool CanMove(Vector2 direction)
    {
        //Vector3Int gridPosition = groundTilemap.WorldToCell(transform.position + (Vector3)direction);
        Vector3Int gridPosition = collisionTilemap.WorldToCell(transform.position + (Vector3)direction);

        Debug.Log("gridPosition: " + gridPosition.ToString());
        
        // If either the ground does not exist or ground does exist but has a collision
        if (!groundTilemap.HasTile(gridPosition) || collisionTilemap.HasTile(gridPosition))
        {
            Debug.Log("False");
            return false;
        }
        else
        {
            Debug.Log("True");
            return true;
        }
    }
#

Do you think it could have anything to do with the initial starting position of the player?

short hazel
#

Which one of the two returns false/true? Note that you have a ! on the first one

dense root
#

Darn Unity isn't letting me type in the inspector rounded values...

#

It translates to: if there is no ground tile or there is no collider return false

short hazel
#

For the method to return true, there needs to be a tile on the ground map AND no tile on the collision map for the specified position. One of these two aren't returning the value you expect

#

Log both return values of HasTile, separately

dense root
#

Ohhh

short hazel
#

The code can be simplified down to the following btw:

// On ground and no collision
return groundTilemap.HasTile(gridPosition) && !collisionTilemap.HasTile(gridPosition)
dense root
#

The collision tilemap is registering as having a collider

#

Weird

short hazel
#

Yep so at that position it's detecting a tile on the collision map

dense root
#

Oh when it's empty it registers the WHOLE tilemap as a collider

#

Why I didn't put an object for testing is beyond me

#

Hmm even with an object it's still making the whole tilemap a collider

#

Is it a setting?

short hazel
#

HasTile doesn't care about the collider, but rather whether there's a tile at the position you specify
Disabing the collider entirely should have no effect on the result of HasTile [citation needed]

dense root
#

Oh right....

short hazel
#

Why does your tilemap have a rigidbody? Is that standard when you create one? Seems weird

slender nymph
#

the composite collider requires it

dense root
#

Let me delete Collider Tilemap and remake it, maybe there's something weird happening I can't see

short hazel
#

Right, and the tilemap collider requires a composite collider I guess

dense root
#

Nope still won't budge

slender nymph
#

it's not required, but it does make it perform as one singular collider instead of a bunch of smaller ones

dense root
#

I knew I had a reason to be scared before changing my old movement system to this new fancy one 😂

#

Trying to fix what was only slightly broken haha

short hazel
#

Take the Vector3Int value containing the position of the tile on the map from the log, and manually locate it from the scene view

cosmic dagger
dense root
#

Well it's not the new Input system that's causing trouble, it's me trying to move my character in a perfect grid that's causing the headache

short hazel
#

In the last screenshot you posted, your player is located between two tiles, usually it should be at the center of one, otherwise transform.position might just be low/high enough for WorldToCell() to mistakenly locate you in the cell directly to the left/right of your player

dense root
#

Yeah I was thinking I needed to fiddle what that value

#

But freakin' Unity won't let me type values so I can't get a perfect .5

#

Let me restart the editor see if that does the trick

#

Fml even with the player perfectly centered in the grid he won't move a damn

#

Swearing under breath ensues

#

Wait the issue is pretty simple, there's always a collisionTileMap tile for some reason

#

But even when I disable it, it still results in true

#

More swearing

slender nymph
#

disabling it does not remove the tiles so i imagine that the HasTile method will still return the same value

short hazel
#

Maybe it doesn't care if the object is disabled, as it's not a physics call per se
Move the tilemap away, or delete it completely

#

Prefer moving it, otherwise you'll get a NullReferenceException in your code

slender nymph
#

or disable the other one and see what tiles are actually set on the Col tilemap

short hazel
#

Maybe it's completely filled with tiles indeed lol

dense root
#

Remade the collision tilemap just to be extra sure and no dice, it's not filled

violet glacier
#

Is there a way to hold (for 100ms) and drag an item in inventory slot? I'm using event system (ipointer) and not new input system

rocky canyon
#

when u click start a timer.. once timer > 100ms allow drag (move image to mouse position)..

#

if u ever release reset the timer

dense root
#

So now we're getting True, which is definitely a step in the right direction. Yet he still refuses to move. 🤔

rocky canyon
#

input works 👍

dense root
#

Yeah lol

#

We didn't need to use the fancy analysis tools

dreamy musk
#

Yeah, I am in pain.

#

the game runs just fine

#

what did I do wrong again

slender nymph
#

are you intending to use sqlite from Unity.VisualScripting.Dependencies in your BirdScript?

dreamy musk
#

I have no idea man

#

probably not

slender nymph
#

then remove line 4 of BirdScript

#

also for future reference, always start from the first error in your console. the top one is what caused the bottom one

slender nymph
#

what was not clear about what i said

dreamy musk
#

expect to hear back from me 😭

dense root
#

Is it possible I need to tell my script what transform.position to move despite being attached to the player?

private void Move(Vector2 direction)
{
    //Debug.Log("Move");
    if (CanMove(direction))
    {
        //Debug.Log("CanMove");
        transform.position += (Vector3)direction;
        Debug.Log("Direction" + direction);
    }
}
slender bridge
slender nymph
#

if that log is printing then that object is being moved. which means if you see it constantly in the same place then something else may be affecting is position, this could be code, or something like the animator controlling its position

dense root
#

Oh my goodness I am so dumb.

#

I'll show you what was happening

#

Celebrate good times.

#

In retrospect I should printed the position of the player somewhere along the line

trim herald
#

Hello I am currently following Japser Flick's compute shaders tutorial(I'm not aware of how well known catlike coding is) and this is my first time writing shaders, I get a Kernal Index (0) out of range error. I looked this up and apparently that means the shader didn't compile. Also in my project the compute shader appears as a text asset with a compute shader inside of it? I haven't seen this anywhere else and am wondering if it is related to my error and for some reason unity isn't recognizing the shader as it is supposed to. When I look at the compiled code, theres not really anything in there it says "**** Platform Direct3D 11:
no variants for this platform (no compute support, or no kernels)"

eternal falconBOT
cinder mason
#

I am making a 2d character controller, and I am using addforce to move the player but the player never stops.
Changing the friction makes the player stick to walls, adding drag makes the jump buggy, and if I used rgidibody2d.velocity instead it would prevent other forces like dashing or walljumping
this is the movement code:

rb.AddForce(new Vector2(direction * speed, 0), ForceMode2D.Impulse);
spare mountain
cinder mason
#

that speeds it up if I keep adding the movement velocity

spare mountain
cinder mason
#

that would work for jumping but for movement it would keep speeding up

spare mountain
#

or does that interfere with dashes?

shell sorrel
#

sounds like you want a damping force

ivory bobcat
#

Maybe consider using something other than the Rigid body component if Rigid body physics isn't wanted. A non physics controller option would be the Character Controller component. There are also controller assets in the asset store that might be useful such as the kinematic character controller but it's quite complicated.

shell sorrel
#

the vast majority of games do not use phyiscs for character movement

#

it just does not offer enough control and fine tuning

ivory bobcat
#

Gravity isn't enough to justify a rigid body component 😅

shell sorrel
#

you can still drive your rigidbody so it can push other physics objects around and detect events so you know when to prevent movement

#

but where its movement is all in your logic

spare mountain
sterile radish
#

right now how this script works is by checking for a click from the player which calls the gamemanager.OnClick method which then starts a timer to check when the player can click again. instead of the gamemanager.OnClick function being called when the player clicks, how would I call it after the timer check has been completed?

https://hatebin.com/wrzcjqccqs

ivory bobcat
ivory bobcat
queen adder
#

blue box is a trigger, what's like the best way to let it decide what direction to turn to?

#

it rotates like this btw

ivory bobcat
queen adder
#

and vv

spare mountain
queen adder
#

current direction is to use 2 triggers, but that's not really fun

shadow mango
#

Hi there, I'm facing an issue I really don't understand since I've found SOOOO many intel that clearly says that I'm not doing anything wrong so maybe I'm false but I'm total lost rn.

I'm using enums to allow multiple mobs to "recognize" other mob "types (e.g. hostile, peacefull) and mob "species" (e.g. spider, plant). Since enum cehcking can starting to be pretty uglywhen checking for many mob types and species, I want to use Flag enum to allow multiple choices (e.g. TargetMobType = Hostile | Peacefull)

Now problem is that when I'm in the inspector setting those "filters" I definitely can't since when I'm choosing one possibility, the variable is randomly set to "Everything" or "None", and an out of bound error is fire.

Got any idea about that ?

ivory bobcat
versed vale
#

I have a game that I'm making that works like this. 0 gravity basket ball in 2d basically. I have set up multiplayer but am struggling figuring out how to let everyone interact with the ball (being able to grab and throw it) At the moment I have it so the ball can be grabbed and thrown by the host, and so that everyone else can see the ball but not interact.. Wanting direction as to where I should look, at the moment been trying to serverRpc but not sure if I should keep trying or do something else.. Here's how I spawn it in currently:

        if (Input.GetKeyDown(KeyCode.B))
        {
            SpawnBallServerRpc();
        }




    }

    [ServerRpc]
    void SpawnBallServerRpc()
    {
        Ball = Instantiate(BallPref);
        Ball.GetComponent<NetworkObject>().Spawn(true);
        BallRB = Ball.GetComponent<Rigidbody2D>();
        BallNetworkObject = Ball.GetComponent<NetworkObject>();
        BallNetworkObject.ChangeOwnership(NetworkManager.LocalClientId);
        foundBall = true;
    }```

and some other stuff I've tried implementing

```c#
    [ServerRpc]
    void HoldBallServerRpc(Vector2 handPos)
    {
        BallRB.MovePosition(handPos);
    }

    [ServerRpc]
    void SetBallVelServerRpc(Vector2 vel)
    {
        BallRB.velocity = vel;
    }```

And some other stuff for when I grab the ball

```c#
else if (HoldingOntoBall && foundBall) {
            Debug.Log("Holding");
            // Move the hand to the desired position
            HandRB.MovePosition(towardsPosition);
            //Move the ball via server rpc
            HoldBallServerRpc(HandRB.position);
            // Calculate velocity
            Vector2 velocity = (towardsPosition - BallRB.position) / Time.fixedDeltaTime; 
            Vector2 clampedVelocity = Vector2.ClampMagnitude(velocity, MaxBallVelocity);
            //Set Velocity
            SetBallVelServerRpc(clampedVelocity);```

Let me know if I need to include other important parts of the project I may have over looked. Thanks in advance for at least reading this 🙂
shell orchid
#

so i have my code and for some reason i want the bullethole effect to not show when im in my reload animation. i have been following a tutorial and when this problem occured i have been searching for a solution for days. when i have my reload animation playing and i click the bullethole effect shows and i dont want that. https://pastebin.com/xjSFJCTD

ivory bobcat
eternal falconBOT
spare mountain
#

``` not '''

#

next to the 1 key

shadow mango
#
IndexOutOfRangeException: Index was outside the bounds of the array.
UnityEditor.MaskFieldDropDown.DrawGUIForArrays () (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEditor.MaskFieldDropDown.OnGUI (UnityEngine.Rect rect) (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEditor.PopupWindow.OnGUI () (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEditor.HostView.OldOnGUI () (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <f6650f702d1247c2a5311a89b759ba03>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
shadow mango
spare mountain
#

np

ivory bobcat
shadow mango
shadow mango
#

This class inherits from NetworkBehaviour, inspector might be modified there idk

ivory bobcat
shadow mango
#

As you can see on these screenshots it even make the last choise disapear and selected value is not the same.
The first screenshot is an empty script with only 2 variables of enum types

#

and it works like a charm

#

plus you can see that the display of the list is quitte weird

ivory bobcat
#

You've got something happening on validate which would occur when changing stuff from the editor.

shadow mango
#

I'm using KBCore.Refs to automatically assign serialized private properties instead of drag n drop from the inspector could this be related ?

private void OnValidate()
{
    this.ValidateRefs();
}
[SerializeField, Self] private NetworkObject m_networkObject;
ivory bobcat
shadow mango
#
[Space(20)]
[SerializeField, Child] private Animator _animator;
[SerializeField, Self] private SphereCollider _detectionCollider;
[SerializeField, Self] private CapsuleCollider _physicalCollider;
[SerializeField, Self] private NavMeshAgent _navMeshAgent;
[SerializeField, Child] private AttackPoint _attackPoint;
#

OK !

ivory bobcat
#

If it goes away but you'd still like to use it, you may need to consult the dev who wrote it.

shadow mango
#

Nop still identical, I even removed include statement, could it happen because it stored inside a serializable class ?

#

Nope I've tried moving the code out of the class and still not working lmao

zenith cypress
#

Does it do it if you give the enums a None = 0

shadow mango
ivory bobcat
zenith cypress
#

What Unity version is this 🤔

shadow mango
#

It could do that even without being included in the class ? Because I removed it and still no progress

ivory bobcat
#

I've got no clue 😅

shadow mango
shadow mango
ivory bobcat
shadow mango
#

Yes that's a great idea actually

zenith cypress
#

Works fine on my end

ivory bobcat
zenith cypress
#

No idea what KBCore is; the enum

shadow mango
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using KBCore.Refs;

public class Test : MonoBehaviour
{
    [SerializeField, Self] private Animator _animator;
    public TypeOfEntity EntityType;
    public Species Specie;
    
    public void OnValidate()
    {
        this.ValidateRefs();
    }
}```
#

If this isn't dark magic I don't know what it is

ivory bobcat
#

It's reflection acquiring some fields with attributes from some type that likely has a value not within bounds of your actual field/type.

shadow mango
#

Could it be because I'm already using LayerMask ref in the class ?

timber tide
#

errors will usually stop later execution of code so it could be something totally not related to the enum

shadow mango
#

Ok so now my IDE event prevent me from writing new scripts wtf

#

Definitely here :

#

Could it be related to a Library error ? Because I had to deleted and generate project library earlier today

#

well yesterday now

#

I have to go to sleep, I'm since 12am yesterday and its 6am here, Ive encountered many more problems while trying to edit other scripts, @timber tide might be right I may need to check for missing dependancies idk will se in few hours. Many thanks for your time @ivory bobcat & @zenith cypress

violet glacier
#

Is update expensive? I've been using mostly coroutines

void Update()
{
  if (active) // do something
}
ivory bobcat
#

Just to answer your question though, a bool check every frame isn't expensive.

violet glacier
#

Thanks :)

neat parcel
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

zinc shuttle
#

!code

eternal falconBOT
mystic steeple
#
            if (fillMode && _currentMode == Mode.Terrain)
            {
                _stopwatch = new System.Diagnostics.Stopwatch();
                StartCoroutine(FillWithinPaintedAreaCoroutine(x, y,Map.instance.mapSize[0], Map.instance.mapSize[1]));
            }
-------------
    private IEnumerator FillWithinPaintedAreaCoroutine(int x, int y, int maxX, int maxY)
    {
        if (_stopwatch.ElapsedMilliseconds >= 200)
        {
            yield return null;
            _stopwatch.Reset();
            _stopwatch.Start();
        }
        if (x < 0 || x >= maxX || y < 0 || y >= maxY) yield break;

        if (Map.instance.GetBiome(x, y) == (Biome)_type) yield break;
        
        Map.instance.SetBiome(x, y, (Biome)_type);
        UpdateTile(x,y);

        // Recursively fill neighboring pixels
        yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
        yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
        yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
        yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left
    }```

Hi guys! I've been struggling to grasp coroutines a bit q.q I want each frame to spend a max of 0.2 seconds filling in tiles but I believe this keeps pausing on every single tile? How do I go about making the coroutine correctly?
queen adder
#

is it a good idea to inherit from GameObject in unity?????

#

or am i only supposed to inherit from MonoBwehaviour

#

i am trying to create a complex trees of objects

silent vault
#

Hello, I'm trying to extend the dropdown to a multi select dropdown.

{
    private List<int> selected = new();
    public bool isMulti = false;
}```
But the isMulti bool does not show in the editor in normal mode. It does show in debug mode. Why is that ?
mystic steeple
zinc shuttle
#

!code

eternal falconBOT
queen adder
#

also another question

zinc shuttle
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball_mechanism : MonoBehaviour
{
    public GameObject Ballstart;
    public GameObject Ballend;

    public static bool isDone;
    public static bool canPlayAudio;

    public static int score;
    

    void Start()
    {
        isDone = false;
        //canPlayAudio = false;
    }


    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag(gameObject.tag)&&isDone==false)
        {
        
            Vector3 spawnPosition = collision.gameObject.transform.position;
            GameObject newObject = Instantiate(Ballend, spawnPosition, Quaternion.identity);
            
            //Destroy(GameObject.FindWithTag(gameObject.tag));
            Destroy(collision.gameObject);
            Destroy(Ballstart);
            score++;
            canPlayAudio=true;
 
            Debug.Log("destroyed" + score);
            isDone = true;
            Invoke("DelayedDone",0.5f);
        
        }
       
    }
    public void DelayedDone()
    {
      Debug.Log("i set the bool to false");
      isDone=false;
      canPlayAudio=false;
    }


}

#

why is invoke not working

#

it is working on code simmilar to this

silent vault
zinc shuttle
#

but no debug for invoke

ivory bobcat
mystic steeple
silent vault
mystic steeple
zinc shuttle
ivory bobcat
# mystic steeple But isn't that exactly what my stopwatch does?

I'm uncertain but it wouldn't require a coroutine (unless you're trying to continue execution of instructions where you'd last left off - which you might be with those recursive yield statements below, now that I think about it).
Is there an unwanted behavior that you're seeing?

mystic steeple
#

Well it seems to constantly be pausing it every frame rather than every 0.2 seconds

ivory bobcat
#

Log how much time has elapsed before returning null

mystic steeple
#

Not sure how I log when things yield

#

Oh in the stopwatch

queen adder
#

if i want to change position of a game object i need to use gameObject.transform.postion
is there anything similar for velocity? i know of rigidbody component which should have .addForce --> moves body via forces not velocities (more realistic)

which approach better:

  • create a separate _velocity field in my component and move my game object via component._velocity += component._acceleration / component,_mass * Time.DeltaTime

  • or should i add rigidbody component and use its addForce to move it

and if rigid body is a better approach, should it be added to an empty game object ? i mean won't anything colide with it ? even if it doesn't have a mesh?

ivory bobcat
#

If it states 0.2, then we would assume it's working as intended - excluding not accounting for time between frames.

mystic steeple
# mystic steeple

But this is what I mean, I'd expect this map to be like updating every 0.2 seconds, but it's updating constantly like a stream, which makes me think that the frame stops after every tile

#

Is the recursive yield at the bottom where I yield on each function call, not causing it to pause every call?

#

I know I am updating a texture but I wouldn't see that unless a new frame came right? Because the renderer would be waiting for the frame to finish

ivory bobcat
mystic steeple
#

Better yet... If I completely comment out the stopwatch / yield bit there, it still acts the exact same way

ivory bobcat
#

I'm not sure what your question is but the yielding function would finish before the other yielding functions are called.

#

Assuming you're wanting all recursive functions to be called within a single frame

mystic steeple
#

I'm not sure how else to word it... The coroutine appears to be constantly yielding, so basically every 1 frame, it updates 1 tile and this is insanely slow...

I want it to do as many tiles as it can in 0.2 seconds before it yields and then continue to do as many as possible

ivory bobcat
mystic steeple
#

How can I verify it?

2 ways

  1. I removed the stopwatch completely so now there is no stopwatch there to yield it, so it is constantly yielding without a stopwatch
  2. My eyes? You can see the FPS of the video, if it wasn't yielding none stop, the FPS would be way lower
#

Frames are not being slowed down at all... so it's needlessly handing control back to Unity none stop

ivory bobcat
#

You need to count how many pixels are filled per iteration - it could just be the writing to texture is slow etc

#

Number 2 is an assumption.

mystic steeple
#

Look even if that is the case... Which probably is a factor and I can optimise in the future, it doesn't change the fact that it's yielding none stop