#💻┃code-beginner

1 messages · Page 182 of 1

gritty parcel
#

ok sorry

thin sedge
#

Hi! I'm trying to make an "enemy" attack something and then right after, bounce back from the target to then go back and attack again. Here's the code I have on the enemy right now:

using System.Collections.Generic;
using UnityEngine;

public class enemyBehavior : MonoBehaviour
{


    [SerializeField] float speed = 5;
    [SerializeField] float damage = -1;
    [SerializeField] string damageTag = "TownHall";
    Rigidbody2D rb;
    Transform target;
    Vector2 moveDirection;

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

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        target = GameObject.Find("TownHall").transform;
    }

    void Update()
    {
        rb.velocity = transform.right * speed;

        if (target)
        {
            Vector3 direction = (target.position - transform.position).normalized;
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

            moveDirection = direction;
        }
    }

    private void FixedUpdate()
    {
        if (target)
        {
            rb.velocity = new Vector2(moveDirection.x, moveDirection.y) * speed;
        }
    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag(damageTag))
        {
            collision.gameObject.GetComponent<Health>().AddHitpoints(damage);
            rb.velocity = new Vector2(0, rb.velocity.y);
        }
    }



}

And here's the object in unity if that's any useful stuff too:

#

Also, it's a 2D game

keen dew
#

What's the question/problem?

thin sedge
keen dew
#

That's not a question

thin sedge
#

Ok, how can I make that happen?

keen dew
#

What does your code do now?

thin sedge
#

Right now it just collides and stays there right next to the target

#

And deals damage once

keen dew
#

Add a variable that tracks the enemy state, if it's attacking or bouncing back. After attack change it to bouncing-back state. Have it do in Update either the attack or the bounce back behavior depending on the variable.

wraith wadi
#

is there a way to hold the execution of the program until the INT variable reaches the value 0 or whichever value i want?
similar to the iEnumerator waituntil or waithold?

languid spire
#

while loop?

earnest atlas
glossy eagle
#

Hi. Does anyone know how to save changes to an InputActionMap (new input system) please?

earnest atlas
#

Yeah I do

#

What you want?

glossy eagle
#

Well basically save the changes done to an InputActionMap at runtime😅

earnest atlas
#

Wait do you mean change bindings?

glossy eagle
#

Like I made a rebind system but now I need to save it and load it when the run ends/starts

lean basin
#

How to convert Vector3 to Quaternion?
the Vector3 is not euler angle, but a direction which transform is facing, or transform.forward.

glossy eagle
glossy eagle
earnest atlas
#

Well I hadnt had experience with that. I could help with setting it up but so far has no reasons to rebind it

rare basin
#

so you can save the new binding as a json

#

then load the jason in your LoadGame() functions

glossy eagle
# earnest atlas Well I hadnt had experience with that. I could help with setting it up but so fa...

like, with the default unity rebinding system you can't create composite bindings or new bindings, so I basically had to do it using something like the following:

reference.action.AddCompositeBinding("ButtonWithTwoModifiers")
                            .With("Modifier1", list[0].inputControls[0].path, "", "ExtraInfo(inf=42)")
                            .With("Modifier2", list[1].inputControls[0].path)
                            .With("Button", list[2].inputControls[0].path);
glossy eagle
timber tide
#

if you cant remap directly, maybe make a manager that take the input and points to another action

#

probably a dictionary

#

maybe you'd have to create a whole new map if you want to do it that way

glossy eagle
#

So like making a whole new input system basically?

#

like the thing is that with what I have right now it works for the run, but it doesn't save

timber tide
#

well, that's how you would do it with the original input system, I'd just map keycodes to actions

cinder spruce
#

i don't follow you. Difference in what way? I can see that they're different.

rare basin
#

i mean the approach you suggested

timber tide
#

you can very much make a system like that and I do it for hotkeys

rare basin
#

you can remap, and that's not the issue

#

he remapped

rare basin
#

he now wants to saved the remapped inputs and load them

#

replace the actions binding with the saved one

timber tide
#

right, which I gave a suggestion just remap them on load

#

is it how you should do it? I'm not sure. Can you do it that way? Sure, why not

rare basin
#

and then how would you attach your custom dictionary

#

to the new input system?

glossy eagle
#

like the problem basically is that I wanted the player to be able to create multiple key combinations for the same action, like some games do, so the player had to be able to add bew bindings, not just modify existing ones😅

timber tide
#

every dictionary can be saved as a list of structs that can be a kvp for your dictionary

gilded sinew
#

where you pass this tilemap.cellbounds i want to test this solution too

rare basin
#

to the newi nput system

gilded sinew
#

what values whould i give to area

rare basin
#

so the new input system asset actually uses your binding?

#

it dosent work like that

queen adder
#

can i tell vsc do undefine UNITY_EDITOR?

languid spire
timber tide
rare basin
#

then it's making your own entire input system

gilded sinew
timber tide
#

you don't need to change the subscription model, only the behavior of which the methods should produce

cinder spruce
glossy eagle
#

and isn't there a way to just apply those changes to the "action prefab" basically?

rare basin
#

throught the InputAsset

#

so if you replace "A" to "B" keys in your dictionayr

#

you also need to replace it in the InputAsset

languid spire
rare basin
#

how can you connect that

#

you cannot have "A" in InputAsset, and "B" in your custom map dictionary

#

you need to replace binding on each action

#

otherwise SkipLetter in this case won't be triggered

timber tide
#

Press key1 on keyboard -> goes into hotkey1 method -> hotkey1 maps to the action hotbar2

rare basin
#

so how do you want to trigger SkipLetter based on your custom input map dictionary

warm iris
#

i have a game idea but i dont know how to make it 😦

rare basin
#

so it detected key1 press

languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

warm iris
wraith wadi
rare basin
warm iris
cinder spruce
timber tide
# rare basin so it detected key1 press

yes, and instead of using hotbar1 action, you do the comparison in the method to check the action. It works, but if you want to change the map internally that's fine too, but otherwise it's quick and easy solution to rebinding

earnest atlas
#

if(enemys==0) do something

rare basin
#

it's not remapping at all

timber tide
#

But it is, you just have an extra comparison down the line

rare basin
#

did you work with new input system?

timber tide
#

it's how you do rebinding with the original system

cinder spruce
rare basin
#

the old system*

timber tide
#

1 extra comparison isn't going to break your game x_x

rare basin
#

but that won't even work...

timber tide
#

but I do it for my hotkeys!

rare basin
#

i want to trigger SkipLetter function

languid spire
rare basin
timber tide
#

not im not I'm using the new input

rare basin
#

then why do you make your life harder

#

with all this stuff lol

timber tide
#

because I don't need to make a whole new map when I can save some json and read from that

rare basin
#

no one told anything about creating a whole new map

#

you can just save json

#

and load the json and replace bindings

#

instead of doing some extra dictionary and internal comparisions

#

you can just replace the actual binding to different keys

glossy eagle
#

oh so you can just make the action into a string to save it as json?

cinder spruce
timber tide
#

either way its a solution and I decide to just keep the method names discreet enough to be reused

rare basin
#

the entire GameInput.cs class is a json

#

you just save the bindings json you have

#

then you load it and replace

glossy eagle
rare basin
#

you can use any JSON utility you want

#

unity built-in one, newton json etc

languid spire
rare basin
#

iirc you can do sth like

glossy eagle
#

okay thanks, lemme try it real quick, thanks

rare basin
#
public InputActionAsset myAsset;
 
public void SaveBinds()
{
     string bindData = myAsset.ToJson();
}
#

and myAsset.FromJson();

#

then on the entier action binding set you just do

#

actionSet.LoadFromJson(loadedJson);

#

unity has all the methods for it

timber tide
#

if I had a more analog specific game I would probably just rebind it since that is continous input, but for key presses I just used what I did in my previous system and it works fine

rare basin
#

googled "unity new input system save binding as json", plenty of examples @glossy eagle

cinder spruce
# languid spire really! Then you are obviously doing this is the wrong place. Seriously, you sho...

Listen i know why i get this error. But i asked you before if i should type this line in the awake method and you said yes. If i cannot enter it as a string should i declare those variables in the awake method or before the awake method? Or do i need to write that code in a seperate method and call it in the Awake. Like i did for the floats. The example in your website is not like this, or i cannot see the similarity

languid spire
#

And I said you should call Get in the Awake method, not type this line in the Awake method

cinder spruce
languid spire
#

tbh you can avoid all this grief and implement a separate script as I said above

languid spire
swift crag
#

This will not help you.

#

If you want to learn to write C# while creating games, then use !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
#

Since when does playerprefs have a generic Get?

languid spire
#

he's using my asset

polar acorn
#

Ah, okay

languid spire
#

which I sincerely regret recommending to him

polar acorn
#

I was wondering why no one was calling out that as an error

burnt mantle
#

Now my problem is my character teleport when i jump and he fall too fast someone have some tips to have a better gravity ? my gravity is 9.81 and jumpForce = 10

swift crag
#

you're multiplying moveDirection by playerSpeed

#

but moveDirection.y might be way larger than 1

#

I would do moveDirection *= playerSpeed; before setting moveDirection.y = ySpeed;

burnt mantle
swift crag
#

Show your new code.

glossy eagle
burnt mantle
scarlet skiff
#

how do you make a collider work as a collider but not push things with rigidbody 2d?

swift crag
#

However, I don't think this is going to let the collider function as a platform at all

#

But I'm not sure! I don't do much 2D

#

maybe it will indeed give you a thing you can stand on, but that can't push you if it moves into you

#

Note that this is a pretty new feature. It's only in 2022.2 or later

swift crag
scarlet skiff
#

what if i make it a trigger

#

and use the thingie method, like ocllision but for triggers

swift crag
#

then it will be able to produce OnTriggerEnter/etc. messages

#

but it won't physically interact with anything

scarlet skiff
#

cool, nice thanks

verbal dome
swift crag
timid saffron
#

The associated script can not be loaded. Please fix any compile errors and assign a valid script.

timid saffron
#

nothing

slender nymph
#

conveniently cropped out the bit that shows that types of logs are hidden and how many there are

polar acorn
timid saffron
slender nymph
polar acorn
# timid saffron

Hm, make sure the script is saved then restart unity. Compilation seems to be stuck in something

timid saffron
slender nymph
#

and what happens when you remove and readd it? whoops missed the from

polar acorn
#

Those names don't match and I couldn't notice in the original screenshot with it cropped

timid saffron
#

damn

verbal dome
#

Oh

timid saffron
#

yea I wrote transfrom

#

ok fixed 👍

polar acorn
#

It looked kosher on the original screenshot but I didn't check too closely

verbal dome
#

Warnings dont lie

timid saffron
#

aö sorry guyz I am burned out I guess

#

it wa s simple mistake I couldnt fix it for 10 mins

earnest atlas
#
void Start()
{
    _enemyController = GetComponentInParent<EnemyController>();
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.layer != _playerMask) return;
    _enemyController.TriggeredByPlayer = true;
}

void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.layer != _playerMask) return;
    _enemyController.TriggeredByPlayer = false;
}

I have this code just to detect player in region. For some reason its not really working?

#

OnTrigger calls are not being performed

#

Collider settings

verbal dome
#

You are comparkng a layer to a mask it seems

earnest atlas
#

Yeah but issue its not even getting a call

verbal dome
#

Not the same thing even though both can be represented as ints

polar acorn
slender nymph
earnest atlas
polar acorn
#

Okay so it's not hitting any break points in those functions, that would indeed mean it's not getting called

slender nymph
cinder spruce
# languid spire that is exactly what you are doing, you are not thinking yourself about what you...

"I wonder if you even understand one single line of the code that you have" Ok this was belittling and discouraging. I couldn't have gotten even this far, if i don't understand a single line of code. There are some subjects which i have less understanding than others, this doesn't mean that i know nothing about coding. There are 8 games i released on itch.io so far. Game development is not just about coding. This was really disappointing. There's nothing more to talk about

earnest atlas
#

Yeah I had copied wrong one

polar acorn
earnest atlas
#

Player has rb, collision is trigger

#

Both have collision

#

I mean similar code I have to pick crystals is working

polar acorn
#

Are you moving the player via rigidbody?

earnest atlas
#

Via setting transform

#

rb movement only on jump

polar acorn
#

That doesn't provide physics messages

swift crag
#

that's also going to confuse the physics system in general

earnest atlas
#

I should use rb to move player?

swift crag
#

(and it won't work at all if you turn on interpolation)

polar acorn
#

You need to use the rigidbody to move if you want the rigidbody to know when it moves into something

earnest atlas
#

But I can collect cristals with same movement system

#

That are same ontrigger

cinder spruce
earnest atlas
#
  void OnTriggerEnter2D(Collider2D other)
  {
      if (!other.CompareTag("Player")) return;
      GameController.Instance.Score++;
      Destroy(gameObject);
  }```

This is practically same code
#

I can change the tag from player to layer

swift crag
#

if you want me to come to a different conclusion, provide more flattering information

earnest atlas
#

Wich one of 2 I need?

swift crag
#

PhysicsScene2D is used if you have multiple physics scenes.

#

you can ignore that

timber tide
#

oh that's a neat method

earnest atlas
#

I need to call this function on FixedUpdate like ray hit?

polar acorn
earnest atlas
#

btw do I need to make Update, Awake, etc private?

swift crag
#

No. Unity doesn't care about the access modifier

timber tide
#

doesn't matter but I usually make them protected

swift crag
#

Some Unity code makes those methods protected

#

see Selectable for an example

#

It'll have things like protected virtual void Start() so that you can override the methods in child classes

#

Unity uses reflection to yank those methods out of the object, no matter what the access modifier is

earnest atlas
#

What means min deapth?

swift crag
#

read the documentation

slender nymph
#

what do the docs say

polar acorn
earnest atlas
#

Only include objects with a Z coordinate (depth) greater than or equal to this value.

swift crag
#

triple jinx

earnest atlas
#

Oh

#

So not really usefull for 2d

timber tide
#

surprised it even has depth

swift crag
#

It is useful for 2D.

#

But if you aren't explicitly putting objects are different depths, you can ignore it

earnest atlas
#

I mean if everything is on same Z

polar acorn
timber tide
#

2D is really 3D ;)

polar acorn
earnest atlas
#

Yeah I know that 2d is 3d in overcoat

#

How was that saying

#

I forgor

swift crag
#

Well, not really.

#

The physics engine is completely different

#

it's Box2D instead of PhysX (or whatever nvidia's thing is)

#

look at your build report -- it's in the editor log after a build runs

timid saffron
swift crag
polar acorn
#

Unity projects big

slender nymph
#

you forgot to remove the line of code that says to make your game 1gb big

swift crag
#

Note that there will be a baseline size for a game -- Unity needs to include...

  • its own code
  • its own assets
slender nymph
timber tide
#

Unity takes like like 400 gbs of my drive out of like 10 different projects/editor versions

polar acorn
#

Unity projects indeed big

swift crag
#

Are you talking about the built game or the project?

earnest atlas
#

You can delete Library, temp, logs

swift crag
#

oh that's expected

earnest atlas
#

It will clear up a lot of space

swift crag
#

Unity needs a lot of space for imported data, temporary files...

earnest atlas
#

What operations are calculation heavy from unity?

timber tide
#

any terrible find operation in update

earnest atlas
#

So every good coder should always use as much find as posible

timber tide
#

enjoy searching through tree gameobject #1352

earnest atlas
#

Yeah I suspected that find is iterating through all objects

#

Is it fine to use at start to reach some component?

#

Or there is better way when you cant serialize it?

verbal dome
#

There is usually a better way

polar acorn
#

Find is never necessary

verbal dome
#

Calling Find just once could cause a small hitch if you have lots of objects

winter prawn
#

Square root is pretty bad but it can be necessary

faint osprey
#

How would i go about making a navmesh on a map that is instantiated around 3 seconds after start

scarlet skiff
#

why this no work, the gameobject has an isTrigger collider^
and the ground has just a collider
neither got rigidbody2d

verbal dome
scarlet skiff
#

but... i i check if they have collided using their collider not using their rigidbody

#

Collider2D collision

polar acorn
#

That'd be a pretty fancy function to achieve that

scarlet skiff
#

so... at least one must have a rigidbody?

winter prawn
slender nymph
earnest atlas
#

Im having an issue. I serialized PLayer object on prefab with transfrom but aparently transform is not getting updated positions... So this happend

#

left birdies. How to add player from the level to serialize

#

Or get his transform?

slender nymph
#

prefabs cannot reference in-scene objects. which i'm fairly sure you've been told before.

#

so your prefab is probably referencing another prefab. which, notably, does not exist in the scene

earnest atlas
#

I was infact not

scarlet skiff
#

okay appearanlty a rigidbody with a trigger collider was the combo that i needed

#

set gravity to 0

#

and ye thr arrows dont push things

wintry quarry
earnest atlas
#

Well I fixed prefab issue

small cypress
#

hi everyone. i need help with making api. may someone dm me and help...?

rare basin
#

noone will dm you

#

discrube your issue here

small cypress
polar acorn
#

But accurate

languid spire
#

not rude, true

small cypress
#

😦

polar acorn
#

Asking for someone's direct undivided attention before you've even actually asked your question is also rude, by the way

young warren
small cypress
#

fuck it

#

the trouble is that i dont know much about api

young warren
#

start with what you're trying to achieve

small cypress
#

but i need to make it for my school project

rare basin
#

plenty of tutorials

#

i'd start with "what is API"

earnest atlas
#

and what means school project 😄

small cypress
#

i need to make a game

#

to graduate

earnest atlas
#

Yes.

small cypress
#

ok.

summer stump
earnest atlas
#

Was wondering why my kill floor is not working.

That small square is my hotbox 🙂

small cypress
#

Unity api.

summer stump
#

!docs

eternal falconBOT
summer stump
#

There ya go

polar acorn
earnest atlas
#

Imagine in RL something similar happens

#

Dont step on that square or u die

polar acorn
earnest atlas
#

Thats not a bug, thats a feature

polar acorn
#

Fair

earnest atlas
#

devs should just add kill walls into every Out of bounds areas

#

this gonna fix all speedrunners

cinder spruce
#

@languid spire I managed to do it with the help of your tool but with a different code. I thank you for that. But you hurt me

#

@swift crag you too

swift crag
#

Okay.

brittle rune
#

help I accidently crashed my project and now i couldnt opened a new instance for the same project

#

how to fix?

swift crag
brittle rune
#

already restart and even quit the program, yet it still persist

swift crag
#

"quit the program"?

brittle rune
#

from task manager and exiting the unity hub, both doesnt work

swift crag
#

but you restarted your computer

languid spire
#

make sure the Temp folder in your project is deleted

swift crag
#

there should be nothing to quit at that point

#

after that, I'd guess there's a lockfile, yeah

brittle rune
#

uh...i double checked, guess the files are also lost
its all became empty

#

no way to recover?

rare basin
#

without version control/backup? no

swift crag
#

you're in the wrong scene

brittle rune
#

its all empty, nvm, please teach me how to avoid this happen again, how to set up backup or version control?

rare basin
#

did you open correct project?

rare basin
#

or svn or whatever you want

polar acorn
honest haven
#
    {
        Debug.Log(currentState);
        if (currentState == State.Running)
        {
            Vector3 direction = (_target.position - transform.position).normalized;
            _rigidbody.AddForce(direction * moveSpeed);


            SetAnimationState("Run");
        }
    }``` my npc wont move stays in current spot can also confirm the debug shows current stat as running
brittle rune
languid spire
polar acorn
fierce shuttle
# brittle rune its all empty, nvm, please teach me how to avoid this happen again, how to set u...

Personally I would suggest looking into github, gitlab or bitbucket, all great git solutions for backing up your project, then get either "Github for Desktop" or my personal favorite "SourceTree" and get familiar with "push", "pull" and "commit", there are other things that can be useful to learn later like merging, diffing and branching, but those first 3 are the ones youll use the most often (watching a tutorial on how to use git can help) - this is not the only approach but I think github + sourcetree/github for desktop is a good start to get familiar with source control in general and is relatively easy to setup - just remember to actually push commits to your git/repo often so you always have a mostly-latest version you can pull from

brittle rune
polar acorn
brittle rune
polar acorn
brittle rune
honest haven
polar acorn
#

Is the sprite inside the box

brittle rune
polar acorn
# brittle rune

Can't be sure from this angle, but with that selected you should be able to rotate around and see if it's in view

brittle rune
thorn holly
#

For FSMs, is it good practice to make a bunch of states for small states, like transitions, or should bigger states group in those smaller states?

timber tide
#

substates are fine

thorn holly
#

What’s a substate?

verbal dome
#

A state that is a child of another state

polar acorn
#

A state inside a state

thorn holly
#

So say I have a thing where a button comes in, player selects a button, and button comes out, and then it repeats that 5 times with different buttons. So I would make a state for each of the five things, and then in each of those, I make three substates: the buttons coming in, the button getting selected, and then the buttons going out?

warm pawn
#

hey dose somebody use an addon to visual studio that will show you options that could follow
example: collision. body colider contacts ...?
just like examples

wintry quarry
#

If you don't have it you haven't set up VS properly

#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

warm pawn
#

ok i try to set it up thx

timber tide
thorn holly
#

Alr thx

#

I think I understand substates now

#

So use states for big general tasks

#

And substates for each step of that task

#

Right?

timber tide
#

There's a lot of definitions for state and statemachines, but ideally you do want to design your logic by grouping behaviors, but that's not always the easiest approach

swift crag
#

If you're in a sub-state, you're also in the parent state

thorn holly
#

Yeah

#

Alr thanks!

timber tide
#

I usually stick to major -> minor states and no more, as branching out can dilute the logic

#

as far as something like a character controller or pathfinding logic machines go

jaunty coyote
#

I have a 3D model, downloaded an animation from internet all works nicely, the problem is that im want an fps game and when i parent the camera to the head bone it is shaky because of the animation. Would it be ok if i did a script that would constantly update the camera position to the head bone?

swift crag
#

I had that exact problem.

#

Most of the camera-shake was from rotation, not translation

#

So I just have a script that, in LateUpdate, sets the camera's world rotation (transform.rotation) to where it should be pointing

#

Now the camera is only moving, not moving and rotating

#

I also use IK to make the head rotate in the direction the player is trying to look, which prevents the camera from getting way out of alignment with your head.

#

It's still not as clean as just having the camera floating in space. Most games don't show a first-person body (or fake it) for a reason!

jaunty coyote
scarlet skiff
#

i wanna set a bool to be true after a 1 second wait inside one of the methods i have, i was thinking i could use invoke then put the string of a newly made method that does nothing except set the bools value to true.. but.. there has to be a better way, a way that doesnt involve making a whole new method just for that..?

swift crag
#

you have to run some code later, so you have to have a method to call

#

of course, you could also just check in Update or something

cosmic quail
#

coroutine

swift crag
#
float delayTime;

public void SetDelay() {
  delayTime = Time.time + 1;
}

void Update() {
  if (delayTime <= Time.time) {
    // whatever
  }
}
cosmic quail
swift crag
#

Starting a coroutine creates garbage, since you have to create the IEnumerator. Unity will also create a Coroutine object.

#

Then it'll have to check if the coroutine should get MoveNext() called on it

scarlet skiff
#

its a part of a method, i cannot use update for this one

swift crag
#

It looks like native code does that when you use WaitForSeconds, so I don't know exactly how that works behind the scenes

#

none of this really matters unless you've got thousands of these things, though

#

you want to go with whatever is easiest to understand

timber tide
#

that reminds me, what resources do we have when it comes to pooling coroutines if that's even possible

wintry quarry
#

Coroutines can't be pooled

timber tide
#

some of my object pools require some coroutines to sort out stuff before being dequeued

wintry quarry
#

IEnumerator can't be reset so it can't be reused

scarlet skiff
#

i just wanted so the player doesnt move left or right which immedietly overwrites the velocity

wintry quarry
#

Use a coroutine

#

As mentioned

timber tide
#

guess it depends if polling in update is more performative than creating the coroutines

cosmic quail
swift crag
#

it's all internal stuff

ivory bobcat
swift crag
#

include the ever-dreaded IntPtr

cosmic quail
ivory bobcat
cosmic quail
swift crag
#

it's a number that can be used as a pointer

#

god I love the new numeric interfaces

#

they make the documentation look so good

languid spire
wintry quarry
#

Lmao

ivory bobcat
timber tide
ivory bobcat
#

Of course, cache objects where ever possible though.

cosmic quail
limpid shoal
#

Hello, I've been working on a function where the "Pickup" void is triggered by touching an object tagged "Pistol." The goal is to change a bool from false to true. In my world, there are two guns: a prop gun and a real gun, with the latter being a child of the player. Initially, the real gun doesn't appear, and the prop gun's role is to delete itself upon player touch. Subsequently, the real gun should appear and become shootable when the "showRealGun" bool is true. I'm currently facing a challenge in changing the bool from false to true in the script. I've spent about an hour searching for a solution but haven't found one. If you, the person reading this, have an easier or better solution, please let me know.

cosmic quail
honest haven
#

trying to problem solve somthing here and im lost. i have a bit of code that if the distance is less then 2 attack else continue to chase the player. Well when its in attack stage, i want to work out if the enemy hit the player first or the player hit the enemy first. The thing is there is a sphere that works out if player is inside to do this chasing and hitting like so ``` private void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player"))
{
float distance = Vector3.Distance(transform.position, other.transform.position);

        if (distance < 2f)
        {
            _canChase = false;
            _rigidbody.velocity = Vector3.zero;
            currentState = State.Attacking;
        }
        else if (distance > 3.5)
        {
            _canChase = true;
        }
    }
}``` Also the weapon is nested inside the npc script. How can i work out who hit who first when they dont share the same script. also my trigger stay is always checking tag player. if that makes sence
timid saffron
#

hello trying to code on my own since the pathway ended. I did position and scale scripts alright but stuck here.

scarlet skiff
#

is there any way to make 2 objects whoich both have colliders and rigidbodies2d to not collide with eachother besides using layers?

ivory bobcat
ivory bobcat
verbal dome
#

Lets you specify 2 colliders

timber tide
timid saffron
cosmic quail
scarlet skiff
#

oh nvm i see u alr said that

verbal dome
#

FYI you can also do transform.eulerAngles = new Vector3(...). Same thing

limpid shoal
ivory bobcat
# timid saffron I thought rotation hapens in 3d so I used that

What you see in the inspector isn't what the rotation property holds. The rotation property holds a Quaternion, which is completely different from a Vector3. Their only similarities are the x, y and z components - in name. Quaternion would have a w component and the values it hold are not Euler values.

timber tide
#

!code

eternal falconBOT
timid saffron
#

its ok now

#

or should i change public vector3 too

swift crag
#

you can directly serialize a Quaternion if you want

#

it shows up as the familiar Euler angles

ivory bobcat
swift crag
#

I use this to make a character's mouth open and close, for example

scarlet skiff
livid frigate
#

Hi guys, how to make melee and range combat system in 2d?

swift crag
#

I just do Quaternion.Lerp(closedRotation, openRotation, amount)

timid saffron
#

let me try

cosmic quail
swift crag
#

You learn a lot of little things once you start getting picky about creating garbage

#

note that you can't save WaitForSecondsRealtime, because that one stores the remaining time directly in the object

#

go figure

timber tide
#

really at this point I am doing more c++ than c#

#

even events are creating too much garbo

livid frigate
timid saffron
#

I think it shouldnt be vector 3 there

timid saffron
polar acorn
timid saffron
#

there was an easier way in unity essentials pathwayü

timid saffron
ivory bobcat
swift crag
# timid saffron

are you actually trying to make an object rotate between a start and end rotation?

#

i was just showing an example of how you can serialize Quaternions.

timid saffron
#

Im trying to make object rotate endlessly as long as the game runs

scarlet skiff
#

bro i keep getting this error sometimes even tho i know for a fact it has a reference

swift crag
polar acorn
swift crag
#

(also, I lied; I was using Slerp)

polar acorn
swift crag
#

Perhaps you have multiple instances of the same class.

timid saffron
scarlet skiff
polar acorn
ivory bobcat
swift crag
ivory bobcat
polar acorn
timid saffron
#

I dont know

#

is it vector3

#

or something else

polar acorn
#

What are you trying to make a variable of

ivory bobcat
#

What are you trying to expose to the inspector and other classes?

timid saffron
#

so you sent "transform.rotation *= Quaternion.Euler(Time.deltaTime, 0, 0);"

swift crag
#

you don't just put stuff there for no reason

timid saffron
#

Im trying to control this rotation

#

with some public

#

things

swift crag
#

you add fields if you want to store a value

#

figure out what value you actually need first

#

perhaps the rotation speed?

timid saffron
swift crag
#

yes, because there isn't literally a RotationSpeed type

ivory bobcat
# timid saffron what goes here
public Vector3 direction;
public float speed = 1f;``````cs
transform.rotation *= Quaternion.Euler(direction * speed * Time.deltaTime);```
swift crag
#

speed is a number. so, float.

timid saffron
#

okay but someone said not to use vector3 with rotation so I was confuesd

swift crag
#

many kinds of things are all numbers

#

length, speed, weight

verbal dome
timid saffron
#

okay works. sorry i took so much of ur time

scarlet skiff
swift crag
#

Prove it by logging the variable immediately before you use it.

#

it's also possible that something else is null

#
if (foo.bar.baz.buz && a.b.c.d.e.f.g)
ivory bobcat
swift crag
#

lots of places for a NullReferenceException here

polar acorn
brittle rune
#

how to make the code recognize the height? please provide the code if possible

ivory bobcat
verbal dome
polar acorn
#

!code

eternal falconBOT
brittle rune
swift crag
#

oh dear

timid saffron
polar acorn
swift crag
#

direction and speed are both clearly being used there

brittle rune
timid saffron
swift crag
#

you can't just declare a pile of variables and hope Unity puts meaningful values in them

timid saffron
polar acorn
brittle rune
polar acorn
#

you literally made them

swift crag
#

they're fields on the class

rich adder
swift crag
# brittle rune camera?

okay, so there are several major problems with your code:

  • y is declared as an object, which is incredibly vague. this can store anything.
  • you've got several lines of code just...sitting there outside of a method
    • y -= -6;
    • y += 2;
#

this doesn't make any sense whatsoever

ivory bobcat
swift crag
brittle rune
swift crag
#

are you following a tutorial here

#

or are you just winging it

timid saffron
#

I see direction var being used there now

polar acorn
#

and provide where

timid saffron
#

mine was like this the first time i copied but its ok now 👍

swift crag
#

no, you didn't copy the rest of the code

timid saffron
#

yeah my bad. I just realized it wasnt edited

#

I couldnt copy it properly 😄 but anyway happy learning see you till next time 🙂

ivory bobcat
timber tide
#

I would have just linked a c# video and called it a day but you guys are too nice

swift crag
#

you've declared like three variables named variations of "height offset"

rich adder
#

good way to know for sure their IDE is not configured ontop of everything else

rich adder
#

They prob using Notepadd++

ivory bobcat
#

Maybe a printscreen of GDL space

rich adder
#

Oh yeah for sure thats the one, unless its a theme

#

also object type 😵‍💫

swift crag
#

it's very messed up

rich adder
#

the longer I stare the worse it gets UnityChanLOL

verbal dome
#

private readonly object y is my personal favorite

polar acorn
scarlet skiff
polar acorn
scarlet skiff
#

and these i have ste in the inspector

queen adder
#

(IN A HURRY) Hello! How can I quickly check if an object exists in the scene using GameObject.Find()?

rocky canyon
#

"QUICKLY, CHECK THE DOCS!!"

polar acorn
# scarlet skiff

After setting the player in this code (which you're doing twice by the way for whatever reason) add this log:

Debug.Log($"{gameObject.name} is passing the player value of {player} to {archer.gameObject.name}, which is now {archer.player}", this);
queen adder
#

wait lemme see

modest dust
rich adder
#

why is this object finding itself

ivory bobcat
polar acorn
#

It is, without a doubt, definitely going to be finding an object in that case

#

You can absolutely ignore that entire else block it is physically impossible to happen

queen adder
rich adder
#

Learn the proper way to make a singleton please

scarlet skiff
polar acorn
polar acorn
#

So what's the problem

scarlet skiff
queen adder
scarlet skiff
#

sometimes somehow its null

polar acorn
summer stump
queen adder
rich adder
#

I sent two links

summer stump
rich adder
#

did u even look

queen adder
summer stump
queen adder
scarlet skiff
#

happened again

ivory bobcat
scarlet skiff
#

the player is always in the scene

queen adder
ivory bobcat
scarlet skiff
#

so is the spawner

polar acorn
# scarlet skiff

So then it seems that UpdateTargetPos is being called on a different archer than the one that got the value set. Let's add in another log there as the very first line:

Debug.Log($"{gameObject.name} is updating target pos. Player is {player}", this);
scarlet skiff
summer stump
polar acorn
#

now what does it say before the error occurs

scarlet skiff
#

if error occurs

#

if it doesnt

#

seems that i try to spawn in the archer too fast after the scene is laoded, thats when it happens i think

polar acorn
#

Show full !code

eternal falconBOT
scarlet skiff
polar acorn
#

You have an invoke, a couroutine, and an Update timer

rare basin
#

imagine you have 10 arrows

polar acorn
#

My guess is the Invoke is to blame for this

#

You should probably stick to one kind, and if you're willing to do Update timers it's probably that one

brittle rune
rare basin
#

did you read the error?

brittle rune
rare basin
#

then learn the c# basics first

#

dont throw yourself on deep waters

summer stump
#

Still read, because there is a lot more to it than that one line

rich adder
polar acorn
rich adder
#

newPipe.GetComponent<PipeMoveScript>(); this probably trying to get it from newPipe that was destroyed

brittle rune
scarlet skiff
summer stump
#

And a poorer understanding that will harm you in the long run

polar acorn
quasi rose
scarlet skiff
polar acorn
rich adder
summer stump
#

That is entirely my point... but ok....

polar acorn
#

and an update timer

rich adder
#

😮

rare basin
rich adder
#

I dont see they spoon fed though

#

writing Instance == null by itself isn't a spoon feed lol

#

they would have to know what Instance is and why its assigned null

ivory bobcat
# scarlet skiff but they each have their own thing

There's a bit of a difference between invoke and a coroutine: https://www.codinblack.com/how-to-run-a-method-at-certain-time-intervals-in-unity/

The last difference between Invoke and Coroutine which we will cover is the execution condition after the deactivation of the object. Invoke and InvokeRepeating do not stop after the game object is deactivated. On the other hand, this not true for coroutines. They stop after the game object is deactivated or destroyed. Therefore, you should use Invoke or InvokeRepeating, if you would like your method to continue running, even though the object is deactivated after the method is triggered.

brittle rune
eternal falconBOT
#

:teacher: Unity Learn ↗

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

scarlet skiff
#

ok so my thought process is this:

i use invoke cuz id want the position to be updated once every 0.8sewc rather than in update cuz thats too often, i suppose i could avoid it by using a float name;
set it to Time.time in start()

and in update, i update the position inside a if (name + 0.8 <= Time.time)
and inside it i det name back to current Time.time

i thought the invoke would be cleaner tho

as for the croutine, its cuz the archers attack is a bit unique, he choses 3 random palces around the players position and spawns targets, and only does the actual attack part after a second, so the player has time to dodge.

i could avoid invoke but i wouldnt know how to do it in any other way than it is rn with the 1 sec delayed part of the attack

#

Invoke and InvokeRepeating do not stop after the game object is deactivated
i assume deactivated means destroyed (cuz says "deactivated or destroyed" later on), which means that it will keep updating the position of the player for the dead arche,r but since the archer is no longer there it causes an error?

ivory bobcat
#

I'd avoid using invoke unless what you're doing has no dependency on any other objects in the scene.

scarlet skiff
#

👍

ivory bobcat
rich adder
rare basin
#

what if you have 10 arrows?

#

terrible architecture

scarlet skiff
#

i was thinking once i got everything right, i can try to make this work as a loop

#

or at least the basics of the archer

summer stump
buoyant knot
#

yeah, you might have a max of a number 2, for non alloc stuff maybe.

craggy oxide
#

just a quick hypothetical

if you've coded something and it works fine
but then you want to hook it up to UI so that it comes with visuals in some way
would you need to rewrite the original code in any way
or would you just add new lines to it

#

if the answer is "depends" then just give any examples you can think of where you would need to do so

buoyant knot
#

depends.

#

if you did your code well, then no.

craggy oxide
buoyant knot
#

and if you did your code poorly, then yes

buoyant knot
craggy oxide
buoyant knot
#

In object-oriented programming, the open–closed principle (OCP) states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification";
that is, such an entity can allow its behaviour to be extended without modifying its source code.
The name open–closed principle has been used in two ways. Both ...

#

If you did your code well, then it will follow the open closed principle. And therefore require no modification to the source code

#

if you need to modify the source code to extend it, then you’ve been a very naughty boy

craggy oxide
#

ahh i see

#

thank you

rich adder
ivory bobcat
# rare basin

It wouldn't be that different using a list... the process/migration that iscs for(int i = 0; i < targets.Count; ++i) { var arrow = Instantiate(...); arrow.archery = archery; arrow.targetsPosition = targets[i].transform.position; Destroy(targets[i]); } targets.Clear();

ivory bobcat
#

I meant, having to change too much

buoyant knot
#

i think xaxup’s code was trying to illustrate the architecture being bad

rare basin
#

what if they have 10 arrows?

ivory bobcat
#

Not referring to acceptance UnityChanLOL
Definitely not acceptable.

buoyant knot
#

ie “use a list dumbass”

#

by showing the consequences of not using a list

ivory bobcat
#

Ah, thought that was the OPs code.

burnt mantle
#

How can i simulate a push to a character controller ? like a push from an explosion or something like that

wintry quarry
polar acorn
#

You get movement super easy with a CC but it means you have to do the math for physics manually

ivory bobcat
burnt mantle
#

Thx for help

brittle rune
# rare basin !learn

new versions doesnt have microgames for the tutorial session, should I download the old version??

summer stump
brittle rune
summer stump
#

If you google "unity asset store" it will come up

rare basin
#

are people really that lazy

#

lol

rich adder
summer stump
#

I think it might be assets.unity.com or something
I always just google it though lol

rare basin
rich adder
#

perfect time for that meme "First time ? "

polar acorn
rare basin
#

or maybe i missed it 😄

silent thorn
rare basin
#

!code

eternal falconBOT
summer stump
#

Edit: actually, looking at the video, maybe it's an issue with being grounded
How do you check if you're grounded?

silent thorn
#

just to an oncollisionenter check and if it enters on grounded is set to true

summer stump
teal mantle
#

Good Afternoon, I have a little question i think. I want to make an Attack move. While the Player is attacking he cant move. But how do i do that. Like where can i see or check when the played Animation is over?

raven kindle
#

Need some help with my 2d endless runner game. I have enemiesmovement script attached to each enemy, inside my update function i have this:

silent thorn
#

I don't have a tag set for it so is grounded should be set to true no matter what

raven kindle
#

But when i call this function, the enemies don't freeze

raven kindle
#

I check on the inspector and the tickbox is not ticked.

teal mantle
summer stump
silent thorn
summer stump
silent thorn
#

hold on I'll try now

silent thorn
rich adder
raven kindle
raven kindle
silent thorn
summer stump
raven kindle
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{

    [SerializeField] float EnemySpeed;
    private Rigidbody2D rb2d;
    [SerializeField] private bool frozen = false;
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        EnemySpeed = 1.5f;
    }

    // Update is called once per frame
    void Update()
    {
        if (!frozen)
        {
            transform.Translate(-1 * (EnemySpeed * Time.deltaTime), 0f, 0f);
        }  
    }

    public void SetSpeed(float speed)
    {
        EnemySpeed = speed;
    }

    public void Freeze()
    {
        Debug.Log("Enemy Frozen");
        frozen = true;
    }
    public void Resume()
    {
        frozen = false;
    }
}

This is the whole class

raven kindle
#

from my player class, which is triggered once the pause key is pressed

rich adder
#

does Debug.Log("Enemy Frozen"); work ?

raven kindle
#

it does, i put debugs inside

#

yes

rare basin
#

btw are you aware the EnemySpeed will always be 1.5f no matter what you set in the inspector

rich adder
raven kindle
rich adder
raven kindle
#

I want the speed to always be 1.5

rare basin
#

then why do you expose it to the inspector

#

might be misleading later

raven kindle
#

no reason really, just to change it mid game i guess

#

I have this for my classes

summer stump
wintry quarry
# raven kindle

where does your player get a reference to enemyMovement? Is there only ONE Enemy in the game?? How would this work for multiple enemies?

raven kindle
raven kindle
#

That spawn randomly

wintry quarry
#

Seems like you're probably calling Freeze/Resume on the prefab and not an any actual enemies in the scene

silent thorn
wintry quarry
raven kindle
#
 public EnemyMovement enemyMovement;

This is my reference

wintry quarry
#

they each have their own frozen variable

raven kindle
summer stump
wintry quarry
silent thorn
raven kindle
#

I have an enemyspawner gameobject

wintry quarry
#

Could probably be the same thing that spawns the enemies

raven kindle
#

yeah

summer stump
raven kindle
#

I will try, thanks

silent thorn
#

but weirdly enough it does seem to slightly affect the rotation of the parent object

honest trench
#

lets say I have a game object. and I want an if statement that checks if the gameobject has 1 child. how would i do that

uncut dune
#

how can I get a few references of scripts and thru the inspector choose a method from those scripts like a unity event?

rich adder
meager sentinel
#

Why does OnTriggerEnter work even if the script is disabled?

honest trench
#

whats the formatting for sending code in discord

eternal falconBOT
honest trench
#

thank you

rich adder
meager sentinel
raven kindle
uncut dune
honest trench
#
    public Animator animatorVariableName2;
    public GameObject Player;
    

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

    }

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

        if (animatorVariableName2.GetCurrentAnimatorStateInfo(0).IsName("New State")) & (Player.transform.childCount == 1)
        {
            if (Input.GetMouseButtonDown(0))
            {
                StartCoroutine(BallMelee1());
            }
        }
honest trench
#

the issue is the player transform part

uncut dune
rich adder
#

& is something else

honest trench
#

ahhh okay

#

well now it says the && is an invalid expression term

uncut dune
#

it should work after

rich adder
#

well closed early )

teal mantle
#

I tried using the AnimatorStateInfo.IsTag but it seems to not work? Do I miss something? My Tag i gave my Animation is called Attack. Anyone have an Idea?

rich adder
#

instead of (animatorVariableName2.GetCurrentAnimatorStateInfo(0).IsName("New State"))

honest trench
#

alright let me try that

scarlet skiff
#

am i missing something? shouldnt this destroy both the thing that interacted with the gameobject that has this script and the gameobject itself?

uncut dune
rich adder
#

you cannot use the inspector

#

use a singleton or the unity basic Dependency Injection

uncut dune
honest trench
#

alright that worked thanks so much :)

rich adder
uncut dune
meager sentinel
rare basin
#

dont do it

rich adder
meager sentinel
rich adder
rare basin
meager sentinel
scarlet skiff
#

i could check with tag as well actually, idk why i didnt do that

rich adder
#

I think disabling script only gets rid of the Unity events but not sure on the physics one

scarlet skiff
#

should i do that instead?

verbal dome
rare basin
#

you can literally check for Fireball component here instead of checking name == "fireball"

uncut dune
meager sentinel
# rich adder make a bool?

I did that, but this trigger gets HP out of the player. And it somehows get 2 or even 4 HP out of the player instead of 1

uncut dune
#

because getting the reference itself isnt the problem

rare basin
#

I mean you can

meager sentinel
rich adder
#

whats the point of putting a method in the inspector

#

i dont get it

uncut dune
rare basin
#

he probably mean

#

subscribing a method from the singleton to unity event

#

via inspector

meager sentinel
rich adder
#

= is for assignment

#

== is for comparison

meager sentinel
uncut dune
rare basin
#

try it and see youroself?

meager sentinel
#

tysm

uncut dune
#

like it didnt work

#

maybe I need to make it public

rare basin
#

i have no clue what do you mean at this point

rich adder
# meager sentinel tysm

also I prefer not to nest my bools when possible in something like that its cleaner to do

if(wasTriggered) return;
//rest of the code inside OnTrigger```
uncut dune
# rare basin i have no clue what do you mean at this point

OK so Im trying for each powerup to do something different one can access the player health, other can access the player controller etc. So what I want is to have like a unity event so once you pick up the powerup it calls a method from one of the scripts

rare basin
#

no need for the <Fireball> tho

scarlet skiff
#

makes sense

rare basin
#

PerformPowerup() method inside

#

then when you interact with the IPowerup, execute it's PerformPowerup() method

#

and each powerup can have different logic inside PerformPowerup()

scarlet skiff
#

how do i destroy both the fireball and the object that his this script tho?

rare basin
#

the object that his this script?

scarlet skiff
#

has this script*

#

mb

rare basin
#

but wdym

#

you already destroy the collision.gameObject

scarlet skiff
#

this is part os a script attached to a game object

scarlet skiff
#

none of them get destroyed

rare basin
#

then its not getting called

polar acorn
teal mantle
#

Can I prevent that my Trigger can be buffered?

distant slate
#

How to count the direction of the perpendicular from hit point of ray?

cunning rapids
#

How do i create an animation parameter for my script?

scarlet skiff
#

also i have this, maybe somehow it causes that? but i mean even if isReflected is true, it still doesnt destroy em

rare basin
scarlet skiff
polar acorn
scarlet skiff
polar acorn
#

I feel like that shouldn't need to be explained

scarlet skiff
#

it still ignores

cunning rapids
rare basin
#

no clue tbh

polar acorn
scarlet skiff
polar acorn
summer stump
teal mantle
#

In my Game you cant Attack while walking but if you try to it will happen right after you stopped running. Can I prevent that? I use a Trigger for this

cunning rapids
scarlet skiff
rare basin
summer stump
cunning rapids
#

Just asking because I'm trying to make his condition for my walking anim

cunning rapids
scarlet skiff
polar acorn
rare basin
teal mantle
polar acorn
cunning rapids
distant slate
#

How to count the direction of the perpendicular from hit point of ray?

rare basin
rich adder
cunning rapids
#

I literally posted it in animation I just thought this could be relevant to code as well 💀

teal mantle
cunning rapids
#

I did...

rare basin
#

what did you google

#

how to add parameter to animator in unity

#

literally first 5 links

teal mantle
# rich adder Im not sure then what ur asking lol

I want that when te Player decides to Attack the Full Animation is played and you cannot cancel it with anything. I use a Trigger for that. The problem is while you run i diasbled it so the animation will not play while moving. BUT after you stop moving it works like a bufered attack and will come out after you stand still. I dont want that. I want to like deactivate the buffer.

cunning rapids
#

I literally have the param it just doesn't recognize it

cunning rapids
#

More screenshots if you'd like

rare basin
#

then what do you not understand from this warning

#

pure english

rich adder
cunning rapids
rare basin
#

no it's not

#

it's isWalking

#

"dude"

cunning rapids
#

Fuck

#

Nevermind

#

My apologies for being obnoxious

teal mantle
cunning rapids
#

Thanks for pointing it out