#💻┃code-beginner

1 messages · Page 248 of 1

rocky canyon
#

take it with a grain of salt

#

you do any translations in the coroutine?

#

that may be the issue to all of it

swift crag
#

it'll matter if anything else moves your transform

rocky canyon
#

but i would figure a coroutine is frame independent

swift crag
#

if your transform is getting moved by anything else, then you'll get different behavior

tender stag
rocky canyon
tender stag
#

its fps dependent

rocky canyon
#

if anything else is tweaking the transform.. its gonna throw off the smooth damp

#

unless u calculate it independently

ivory bobcat
#

It's just managed data that's updated every time you call it.

swift crag
#

coroutines in general?

rocky canyon
#

isLaddering lol

#

i dig it

swift crag
#

yes, they'll run every frame if you always do yield return null

tender stag
swift crag
#

consider doing what spawncamp did: instead of smooth damping from transform.position, store your position in a variable and use that

#

and then assign the result to trasnform.position

swift crag
# tender stag

this person is expecting coroutines to run more than once per frame

#

of course that doesn't work

tender stag
rocky canyon
#

i concur with u.. when I isolated (as you did) zero issues.. but his code is involved to say the least

swift crag
#

yield return new WaitForSeconds(...) tells Unity to resume this coroutine as soon as possible after that much time passes

rocky canyon
swift crag
#

Yes, it sounds very plausible to me

ivory bobcat
rocky canyon
#

this guy see's in slow motion 😆

ivory bobcat
rocky canyon
carmine turret
#

Does anyone remember how to turn on raycast/spherecast debugging in unity 2023?

rocky canyon
#

youd have to ask Mniszeko

carmine turret
#

I definately remember it being a setting but cant remember where it is ahaha

rocky canyon
carmine turret
#

Nah in 2023, there is 100% an option for it ^^

rocky canyon
swift crag
#

you mean the physics debugger?

carmine turret
#

I used to use it a bunch

swift crag
#

it's under Analysis

carmine turret
rocky canyon
#

ohh yea i forgot that exists

swift crag
#

window -> analysis -> physics debugger

#

go to Queries and uhhh

#

smash the "everything" button

ivory bobcat
rocky canyon
#

you owe me a keyboard

rocky canyon
carmine turret
#

thaanks

rocky canyon
#

i was trying to throw my boy nomnom a bone too 😄

north kiln
#

I have a page containing all the options lol

#

I should add Handles and Gizmos here perhaps...

rocky canyon
#

don't you also have a physics visualizing asset too?

carmine turret
#

😄

north kiln
rocky canyon
#

ahh cool 👍

swift crag
swift crag
carmine turret
#

I dont see why it shouldnt work though since its the same render enging 😦 oh well thank you

#

enging

#

new word

swift crag
#

they're completely different physics engines

#

PhysX for 3D, Box2D for 2D

#

they have nothing to do with each other

carmine turret
#

Does a raycast count as physics?

rocky canyon
#

ofc

swift crag
#

Yes. But it's 2D physics, not 3D physics.

carmine turret
#

I see, oke

#

thank you

carmine turret
#

riiip

#

oh well

polar acorn
#

Nothing is stopping you from just putting a 3D collider on a sprite

rocky canyon
carmine turret
#

Im basically wanting to make a game with grappling and want the player to be kinematic when grounded, and rigidbody when not ^^

#

(I have no clue how I would manually program grappling hook physics otherwise

rocky canyon
#

tilemaps are such a re-occuring issue/ question..

carmine turret
#

You suggested to use a 3d collider, and I asked if that would work with tilemaps since they have rigidbodies

rocky canyon
#

ur tilemaps use rigidbodies?

carmine turret
#

mb

rocky canyon
#

interesting..

swift crag
#

i presume you have a player with a Rigidbody2D and a tilemap with a TilemapCollider

rocky canyon
swift crag
polar acorn
carmine turret
#

ohhhh I see

#

no worries!

rocky canyon
#

i gotta show my boy some love and try out his asset.. im ashamed to say i havent even used it yet

polar acorn
#

Ignore me, I walked in on a conversation in progress and thought we were talking about a completely different thing

carmine turret
carmine turret
#

Whjilst on the topic, is my idea to use kinematic for ground movement, and rigidbody for grappling and gravity a... good idea?

#

or is it horrible and going to set everything ablaze

polar acorn
#

It's not a terrible idea, but it's a bit complicated. Normally you'd either bite the bullet and either deal with the fiddliness of dynamic rigidbody movement or coding in your own kinematic grappling.

carmine turret
#

🥲

rocky canyon
#

either or sounds exhausting tbh

carmine turret
#

if I had to choose one of those two, I would probbaly do rigidbody movement

#

and just try to finetune the settings

#

Gonna try my idea first, see how well it goes.

#

as a side note.. I cant actually figure out how to install the package, I installed it via package manager, but it doesnt work as described haha.

polar acorn
# carmine turret Coding in kinematic grappling sounds awful

Yeah, but if you want total control over the physics you'd need it at some point. I have no idea how good the physics engine will handle transitioning between the two states but if you don't run into any major issues you can probably get away with it

carmine turret
#

Only one way to find out

#

Do I need to import fucntionality in the code?

rocky canyon
#
Open the Package Manager from Window/Package Manager
Click the '+' button in the top-left of the window
Click 'Add package from git URL'
Provide the URL of this git repository: https://github.com/nomnomab/RaycastVisualization.git
Click the 'add' button``` you used this method?
carmine turret
#

Because its definately installed

carmine turret
north kiln
#

Have you added the namespace?

rocky canyon
#

it should be in ur project already.. then..

carmine turret
rocky canyon
#

ya u just need to use the namespace.. and VisualPhysics shuld be avail

carmine turret
#

Ive never really googled it. lemme google quickly and understand

north kiln
#

Though, 0103 might indicate you're using it in a completely invalid place—won't know without seeing code

carmine turret
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class movement : MonoBehaviour
{
public float speed = 200;
Vector2 move;
Rigidbody2D rb;





    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        rb.AddForce(move * speed * Time.deltaTime);
        RaycastHit2D hit = VisualPhysics2D.Raycast(transform.position, -Vector2.up);
        if (hit.collider)
        {
            rb.isKinematic = true;
        }
    }

    // Update is called once per frame
    void Update()
    {
        move = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
    }
}

#

Thats the entire thing.

north kiln
#

yeah, missing namespace looks like it

carmine turret
#

this section is the namespace I assume?

north kiln
carmine turret
#

Not entirely sure where I would find the name of the package

rocky canyon
#

ur IDE should let u just add it

summer stump
rocky canyon
#

but heres the Doc page.. if u'd scroll down

#

wait.. is ur IDE configured 😈

carmine turret
north kiln
#

!ide

eternal falconBOT
carmine turret
#

tanks

#

one momento

rocky canyon
#

you'll be doing urself a favor.. trust

carmine turret
#

egh cant find my vscode install kek

#

Ill do it when I get back, need to walk dog. thanks for the help peeps

thorn holly
#

I’m a bit confused on trigger vs collision, if I have an object that:
Doesn’t pass through walls, but instead bounces off them
Activates a method and passes through the player
How would I do that? I can code the bouncing, I’m just not sure how to make it pass through some objects and make it collide with others

#

Also this is 2d top down and I don’t want physics to apply to anything, other than detecting wall collision, and I stuff to move only explicitly.

#

I believe someone told me how to do part of this, but I just don’t know how to do the different interaction types

rocky canyon
#

trigger you can pass thru.. collision you cant

#

if u want it to pass thru objects. u can set layers.. and in the physics settings u can manually set what layers interact with what other layers

#

called the Layer Collision Matrix

#

you don't have to use Triggers.. just b/c u want something to pass thru it..

#

triggers are meant to be activated(do something in code).. like if u walk thru a metal detector.. it'd Alert.. and tell the code to do something

thorn holly
#

Ah

rocky canyon
#
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            Debug.Log("We collided");
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            Debug.Log("Triggered");
        }
    }```
acoustic sun
#

How did you add Adding a Winner Zone trigger to finish the level? Like when creating a game

rocky canyon
#

^ OnTriggerEnter

#

course you'd want to use something like a tag and CompareTag("PlayerForExample");

#

to know if it was the player colliding with it.. and not just the ground or something

sterile moon
#

Alright, Im tired of messing with this lol, who wants to make like 10 bucks, maybe more, doing some rigging and maybe programming

rocky canyon
#

pfft, I wouldn't open my editor for less than 100

sterile moon
#

lol fair point

rocky canyon
#

you the dump truck kid?

sterile moon
#

Tow truck

rocky canyon
#

yea yea

#

i am interested in ur project tho

sterile moon
#

Hardly a kid though, left that title behind about 10 years ago

rocky canyon
#

yea, just some slang

#

take no offense

sterile moon
#

I could use people who are interested in my project

rocky canyon
#

i like physics.. and mechanical things..

sterile moon
#

WELL I DO TaKe OfFeNsE nOoB lol

primal turtle
#

why does it work when they do it, but not when I do it?

Instantiate(f1, new Vector3(12, 12, 5));``` is it because I use a tilemap and they used a gameobject? Does that change anything?
rocky canyon
#

before coding.. i was a mechanic and a carpenter

sterile moon
#

funny enough, I am a mechanic by day trade. run my own business

rocky canyon
#

i figured

sterile moon
#

its why im willing to pay someone to get this part solved for me lol

rocky canyon
#

or u wouldnt be doing something like ths

sterile moon
#

I fix this shit, I dont build this shit lol

primal turtle
#

ahh

rocky canyon
#

thats a 3D coordinate

primal turtle
#

just got a cs1503 error

rocky canyon
rocky canyon
sterile moon
#

I do not @rocky canyon

rocky canyon
#

i cant memorize 1000s of error codes

primal turtle
#

cannot convert from 'UnityEngine.Vector2' to 'UnityEngine.Transform'

sterile moon
primal turtle
#

was already writing it :)

primal turtle
sterile moon
primal turtle
#

ahh

primal turtle
#

mines just the semicolon error

rocky canyon
#

OB2*

sterile moon
#

P0304, Cyl 4 Misfire

primal turtle
rocky canyon
#

my cars were junk too.. all i had to do is short out the connector with a paper clip.. and count how many times the check engine light flashed

rocky canyon
sterile moon
#

P0301-P0308 (and more for those 10 and 12 cylinder engines of course) are all misfire codes for a specific cylinder. P0420 is catalyst efficience, usually clogged cat

#

Alright, got that package for you @rocky canyon i assume shoot it at you

primal turtle
#

I thought that was clear

#

here it is again

rocky canyon
summer stump
primal turtle
#
Instantiate(f1, new Vector2(12, 12));```
sterile moon
teal viper
rocky canyon
carmine turret
sterile moon
summer stump
primal turtle
sterile moon
#

Package is at your door @rocky canyon

summer stump
primal turtle
#

yes

#

ohhh

teal viper
# primal turtle wdym?

Do you see all the method signatures in the documentation? Which one fits your call according to parameter count?

summer stump
#

There ya go. It is a reference to the transform component you want to be the parent

primal turtle
#

is there any other way to have the instantiated object go to the position I want without doing that in its own seperate script?

summer stump
#

Note it takes a vector3, NOT vector2

#

And it requires a quaternion

primal turtle
#

ok

#

couldn't I move the instiated object afterhand?

summer stump
#

Why not just move it IN the instantiate though?

primal turtle
summer stump
#

So that is a non-issue

#

Just pass the vector2 you had as a vector3 🤷‍♂️

primal turtle
summer stump
#

You have to use a vector3

#

Just pass the vector2 you had AS A vector3

#

As in new Vector3(2,2,0)

primal turtle
#

cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.Transform'

#

then I get this

teal viper
#

The problem is the param count...

summer stump
#

You must include the quaternion as I said above

modest dust
#

Dear lord almighty

#

Just look at the docs and see for yourself that there is no Instantiate method which takes ONLY the prefab and position

primal turtle
#

lar

#

alr

primal turtle
#

this is code-beginner

primal turtle
summer stump
primal turtle
#

Anyways, I'm sorry for my stupidity and, thanks for the help!

carmine turret
#

your profile picture is incredibly annoying (or bugged on my end)

tender stag
#

so basically do that ^?

carmine turret
summer stump
tender stag
carmine turret
#

thank you

summer stump
carmine turret
summer stump
carmine turret
#

I... no?

#

I dont think so aha

tender stag
#

it didnt work

rocky canyon
#

was i summoned?!

tender stag
#

indeed

summer stump
carmine turret
#

Ill get that now

#

vs code

summer stump
#

👍

carmine turret
#

where might one find it, its not on the page vscode actually tells you to go to 😄

#

unless Im blind

#

(equally possible)

rocky canyon
carmine turret
rocky canyon
#

idk, is there anything else modifying the transform?

tender stag
#

holy shit

#

yo

#

i think i figured it out

#

after 3 days

#

YESSSS

tender stag
#

and its interpolate mode was set to interpolate

#

thats why

#

i set it to none

carmine turret
tender stag
#

and its working perfectly

carmine turret
#

same for everyone else ^^

tender stag
#

so i just gotta set the interpolate mode to none whenever im laddering

#

@ivory bobcat @teal viper cause i know u guys helped me over the past two days

#

if your curious why it didnt work

teal viper
tender stag
#

do u know what the funny thing is

#

i changed it by accident

teal viper
#

Well, glad that solves your issue

tender stag
#

thanks guys

#

its fixed the issue for climbing as well

carmine turret
#

How do I figure out the layer of the raycasts return?

#

Currently its triggering on the players capsule which is of course not ideal 😛

teal viper
carmine turret
#

I see

summer stump
#

But different overloads return different things

carmine turret
#

Is there a way to make the raycast ignore the player?

summer stump
#

Pass in one that doesn't include the layer the player is on

carmine turret
#

Yeah the moment I typed that I thought "wait isnt there a layermask argument for raycast"

#

xD

carmine turret
#

nvm I get it.

#

layermask is an array!

#

or something similar. Ill work it out

thorn holly
#

If I disable a collision on the LayerCollisionMatrix, will triggers still activate?

summer stump
# carmine turret layermask is an array!

I mean, that is basically right yeah. Vertx's link explains it well.

But I just wanted to say that yeah, it can become confusing going from layer INDEX to a layermask.

It's best to just create a layermask variable and set it in the inspector
public LayerMask raycastMask;

thorn holly
# summer stump No

Hmm. So I have a projectile, I need it to collide with the map in the sense that the projectile will not move through the map and activate OnCollisionEnter, but I need it so the projectile will pass through players, but still activate OnTriggerEnter on the player and projectile

summer stump
thorn holly
#

Well, I need it to collide with the map but not with the player

summer stump
#

Or do a ricochet logic

thorn holly
#

Yeah, do I have to worry about it passing through the wall?

eternal needle
thorn holly
eternal needle
#

no matter the solution, every wall, floor, or object you want this projectile to hit is gonna have to be a different layer from your player

summer stump
thorn holly
#

Well, it wont be going too fast, so that should be fine then

thorn holly
summer stump
thorn holly
#

I don't want my projectile to simulate physics, just do the OnTriggerEnter

summer stump
thorn holly
summer stump
#

You can then do a layermask to be like the collision matrix too

summer stump
#

Well, sorry. To be clear, it would be the opposite. It would ONLY include the layers you DO want to hit

thorn holly
thorn holly
# summer stump Layers you don't want the raycast to care about

So now for the player, I want it to collide with other players and map objects (as in not go through them), but still not simulate physics and I dont need anything to happen on these collisions. Would I do the same raycast and trigger method, but just make it not move if it detects a collision?

fair steeple
#

Hey, I'm having trouble subscribing to an event. It's CrawlStateEnter in Test.cs https://pastebin.com/swbbDyRk

Oddly it throws null exception in only one of the two events and I can call CrawlStateEnter only once.

Everything is referenced in the editor.

teal viper
fair steeple
#

According to this it's not

covert sinew
#
        if (textboxController == null)
        {
            var _textboxController = FindObjectOfType(typeof(TextboxController));

            textboxController = _textboxController.GetComponent<TextboxController>();
        }

Is there a specific function that finds an object in the scene with a given component, and returns that specifc component, or is this up above the correct way to do that? I'm struggling to find out from what I've been investigating.

fair steeple
#

Seems to be the only game object with CrawlState.cs too

shell sorrel
#

also the one you called does to, you just have to cast the result, but the generic version is the correct one to use

covert sinew
#

Thank you very much for the help. I appriciate it.

shell sorrel
fair steeple
#

Ok, I solved the null error, but it keeps calling CrawlStateEnter only once

fair steeple
#

That the event CrawlStateEnter is being called only once, after that it only calls CrawlStateExit

teal viper
fair steeple
#

Oh, right

#

It was a second Test script being instantiated on a random object

teal viper
#

As for the current issue, add logs to where the event is supposed to be invoked and see if it prints.

lusty flax
#

How would I make a track for a moving platform? I want to be able to display where a moving platform will go, because right now it's really hard to know where you'll end up.

lusty flax
fair steeple
teal viper
fair steeple
#

Thanks for the help

lusty flax
#

Line renderers do that? Cool... I didn't know...

shell sorrel
#

yeah line renderers do that, it can tile a texture along the line on y axis

teal viper
shell sorrel
#

also sprite shape might work for you

lusty flax
shell sorrel
#

first is it just 1 straight line, or a bunch

teal viper
shell sorrel
#

or a path that curves

lusty flax
#

Thank you!

shell sorrel
#

if its always 1 straight line, even just 1 nice sliced sprite would work

carmine turret
#

I thought I might try using just rb for the 2d controller, but my character bounces over the tilemap

#

ive read that this is a limitation of box2d, but that post was from 2016. any ideas?

swift crag
#

i'm not sure what "bounces over the tilemap" means

#

like, you're getting caught on the boundaries between tiles?

carmine turret
#

Yup

#

which forces the player to bounce upwards

swift crag
#

i'm just figuring out 2D physics right now myself, so I haven't had that issue yet

carmine turret
#

If I use a box collider for the player instead, the player randomly just stops

swift crag
#

Maybe your sprites are slightly too small.

#

What if you switch the tiles from Sprite to Grid collision?

#

it's an option on the tiles, not the tilemap collider

carmine turret
#

I havent seen that. Ill give it a try in a sec

buoyant schooner
#

Am I using unity actions correctly?

using UnityEngine;
using UnityEngine.InputSystem;
using System;

public class PlayerInput : MonoBehaviour
{
    GameActionMap S_GameActionMap;
    public static event Action doSomething;

    private void Awake()
    {
        S_GameActionMap = new GameActionMap();
    }

    private void OnEnable()
    {
        S_GameActionMap.Enable();
        S_GameActionMap.Player.A.performed += ActivateButton;
    }

    private void OnDisable()
    {
        S_GameActionMap.Player.A.performed -= ActivateButton;
        S_GameActionMap.Disable();
    }

    private void ActivateButton(InputAction.CallbackContext context)
    {
        doSomething?.Invoke();
    }
}
#

It seems that if I invoke my actions in my input script, I'll have a ton of actions declared

#

Is there a way to declare my csharp public static event Action doSomething;

In the class where I use it?

#

I thought of using a static class instead, but It feels a little weird to make a seperate static class

shell sorrel
#

you declare it in the place you invoke it

#

and sub to it else where, where you want to listen for it

covert sinew
#

In an Abstract Class, I want an if statement that checks if the component is of a specific type or not.

Is there a way I can check which specific inheritor of an Abstract Class is being used, or check if a specific inheritor is on the object in question?

shell sorrel
eternal needle
shell sorrel
#

if you need to check for many types there is also a pattern match with switch you can use as well

#

but yeah it does feel strange for the base class logic to need to care what type extended it

#

normally this would be for something that consumes the abstract type, and need to work differernt based on what extends it for a edgecase

covert sinew
buoyant schooner
# shell sorrel you declare it in the place you invoke it
using UnityEngine;
using UnityEngine.InputSystem;
using System;

public class PlayerInput : MonoBehaviour
{
    GameActionMap S_GameActionMap;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;
    public static event Action doSomething;```

What happens if I want to invoke a ton of actions inside 1 script?
My input script will have like 50 action declarations

My script will start to look like this ^^^
shell sorrel
#

like you can use Action<T> instead

#

then pass data into the Invoke when you call it

eternal needle
# covert sinew I'm using it to throw errors if variables aren't set, but some of the child clas...

maybe make another child class which specifically handles which variables are needed. A layer between the base class and the actual child class. The base class shouldnt care about this at all, you'll never stop editing the base class everytime you need to make a new child class.
Or maybe just throw some extra logic into the base class like some protected bools so it knows what variables to not check for, and child classes can change those bools

buoyant schooner
#

I need a lot because It's my player input script, If I wanted to map every button to something, I would have a lot of actions

eternal needle
covert sinew
shell sorrel
eternal needle
#

🤨

shell sorrel
#

like you can make as many instances of your GameActionMap to map with as you want

#

no need to do it all from 1 place

eternal needle
teal viper
shell sorrel
#

even if i was redirecting it through events, i would use only a small amount of events that have args that are passed

#

such as the enum value or a tiny struct

buoyant schooner
#

I tried doing this:


public class AnotherScript : MonoBehaviour
{
    public static event Action doSomething;

    private void Awake()
    {
        doSomething += SayHi;
    }

    void SayHi()
    {
        Debug.Log("HI");
    }
}

But then I cannot do this:

public class PlayerInput : MonoBehaviour
{

    private void ActivateButton(InputAction.CallbackContext context)
    {
        AnotherScript.doSomething?.Invoke();
    }
}

I can only subscribe events with AnotherScript.doSomething

eternal needle
#

you cannot do that because you cannot invoke events from another class

buoyant schooner
#

hmm, yeah ;/
But some how I can subscribe events from another class

#

It would make sense to me if I could do this above

eternal needle
#

AnotherScript.doSomething += SomeMethod

#

if that wasnt an event, just an action, that should be fine to do. but this all seems very weird to even need to do

shell sorrel
#

if the instance it is on matters its common to keep the event static and pass the instance as the first arg

teal viper
shell sorrel
#

but also makes no sense subbing to a event on the same type that defines it

buoyant schooner
#

hmm, what happens if I want to invoke the same event in different scripts?

queen adder
#

hello! when i set up a camera to make it follow a cube and the cube colldies why does the camera fly all ove the place?

shell sorrel
#

what you want to do feels more like a basic reference and function call

#

like the idea of events is you make it many things can sub to it from all over the code base

teal viper
shell sorrel
#

and they all see when its invoked

tender stag
#

do i multiply it by Time.deltaTime?

#

like this

buoyant schooner
tender stag
#

wait no it doesnt

shell sorrel
teal viper
teal viper
frigid sequoia
#

I can just not use it right now, but I am curious now that I typed it, would something like this result on an endless loop?

swift crag
#

correct

#

unconditional infinite recursion

#

it's worse than an endless loop, I guess

#

Unity just instantly dies when I do that (on macOS, at least)

buoyant schooner
swift crag
#

I very commonly do this by writing

public float Foo => Foo;
buoyant schooner
frigid sequoia
swift crag
#

which is a property called Foo that returns Foo

#

you can see where that's going

eternal needle
# tender stag why when i have lower fps the firerate is slower?

to me it doesnt seem like your solution actually is dependent on fps. Maybe ive missed something. This might just be an issue that the fps is too low, and the game is running too slow.
imagine if you had 1 fps, your game is running Update ONCE per second. No matter what you set the nextFire time to be (lets say in 0.1 seconds from now), update wouldnt run within 0.1 seconds and you would at best shoot 1 second from now.
Similarly if you had a fire rate of 1 million bullets per second, your game would never actually run that fast to get 1 million shots out in 1 second

frigid sequoia
#

I have never seen the "=>" before so I am kinda confused by that XD

swift crag
#

suppose your weapon fires once per second

#

and you're getting 1.1 frames per second

#

frame 0, t=0: fire. next fire at 1.0
frame 1, t=0.9: don't fire
frame 2, t=1.8: fire. next fire at 2.8
frame 3, t=2.7. don't fire

eternal needle
#

why crosspost this to all 3 channels, read the #📖┃code-of-conduct and delete it. This isnt a coding question.
wtf i just noticed you pasted it to literally every channel

swift crag
#

I prefer to do weapons like this

#
[SerializeField] float fireRate;
private float delay;

void Update() {
  delay -= Time.deltaTime;
  while (delay < 0) {
    delay += 1 / fireRate;
    Fire();
  }
}
#

This avoids "losing" time caused by frames and the fire rate not perfectly aligning

#

It can also fire several times per frame, if necessary

teal viper
buoyant schooner
swift crag
#

If you don't actually want events, just don't use events.

event is just a way to ensure that only the owner can invoke the method

#

There's nothing stopping you from slapping a System.Action field on something

teal viper
buoyant schooner
shell sorrel
#

feel you are thinking about the purpose of events backwards

eternal needle
# tender stag so its fine?

basically yea, if you do what Fen said then you can ensure the firerate is accurate. Really though as a user, I wouldnt expect my game to fully function if it was running at 10 fps suddenly. A ton of games have bugs with lag

shell sorrel
#

a event is just a message on a system that something happened, and many things can choose to listen to it

#

its invoked from 1 spot, but listned to by many

swift crag
#

It can be really bad in certain situations

shell sorrel
#

if you do not want this restriction just remove the event keyword

buoyant schooner
buoyant schooner
swift crag
#

of course, making the weapon sound right is another matter (:

#

if you just play a sound every time it fires, it'll sound a tiny bit choppy

#

...then again, I never really noticed that in the games where I've used this strategy

#

so it's probably fine

#

Anything where you fire multiple times per frame probably shouldn't be playing an audio clip for each shot

teal viper
# buoyant schooner Oh,

Why would you want to invoke your events from many places though? Assuming it's still for the input use case.

swift crag
#

switching to Fuller Auto and crashing fmod

buoyant schooner
shell sorrel
#

i feel multiple triggers just makes it harder to follow

#

when i think of my events they are owned by 1 system

tender stag
#

like this?

shell sorrel
#

but if thats what you want use the same code you have, just remove event keyword from those lines

swift crag
# tender stag

Yeah. Just remember to set delay to 0 if you aren't firing and it goes below 0

#

Otherwise you'll bank up a ton of shots

#

achieving Fullest Auto

tender stag
#

wait so where do i set it to 0

swift crag
#

if you aren't firing

swift crag
#

if you are firing, the code already raises delay back above 0 (by firing the weapon)

#

and only if delay is below zero

tender stag
swift crag
#

only if delay is below zero.

#

otherwies, letting go of the mouse will instantly end the cooldown

carmine turret
#

Mmm just a quick query, if I wanted to use 2d physics, can I use 3d models still;?

swift crag
#

Sure.

#

the only important bit is if you use the URP 2D renderer

#

it may not play so nicely with 3D models

tender stag
#

so like this?

carmine turret
#

Hmm I did choose urp mode but I supose I could just make a 3d project, and use 2d code

swift crag
tender stag
#

wait so what did this change

#

i dont understand

tender stag
#

the firerate

swift crag
tender stag
#

the way i was doing it

swift crag
#

before adding the delay = 0 bit?

#

or what you had before?

tender stag
swift crag
#

There were two problems with that logic

#

One: You can't fire more than once per frame. This isn't very likely to come up unless you have a super-fast-firing burst weapon (or the game gets down to a low framerate)

shell sorrel
#

there are ways to fake multiple shots per frame

teal viper
# buoyant schooner Just multiple triggers who want to invoke the same event? I'm just trying to thi...

The best approach is to have a hierarchy in you code. At the very top you'll have something like a game manager, that governs the overall game loop. It would hold the topmost events and you can request it to invoke a certain event for something, like game over or game start. Below it would come some specific systems or managers, like PlayerController or something, it might have events like OnPlayerDied or something. Each of these classes would hold ownership of these events and would be the only one invoking them. Since PlayerController would be the ultimate source of truth for the player live/dead state, it would be the only one that can and need to invoke the event. It wouldn't make sense to call the player died event from a random stone in the scene, even if it was involved in killing the player. Makes sense?

shell sorrel
#

but its much more complicated

swift crag
#

Two: You lose any excess cooldown time. So if the weapon is almost ready to fire on frame 1, it sits around for a long time before frame 2 comes around

#

That time gets lost.

carmine turret
shell sorrel
#

like if its a projectile, you can calcualte how many shots should happen per frame, then adjust starting positions of projectiles to fake it

swift crag
#

By subtracting the time per shot, you get to keep that excess time

teal viper
buoyant schooner
teal viper
#

If you find yourself having an event that many scripts need to invoke, then there's something wrong with assigning responsibilities to your classes

teal viper
swift crag
#

it's not just a dumb bag of function pointers

teal viper
#

If it's a game over event, for example, the game manager would be checking the win/lose conditions on update or on certain events and if they're satisfied, invoke the appropriate event that it owns.

swift crag
#

It's fine for other things to tell the game manager about what's happening

#

like "The player just died"

#

or "This objective was completed"

shell sorrel
#

also you mentioned some of this is your want to reduce coupling

#

events do not reduce coupling it just reverses where it is which can be rather helpful at times

swift crag
#

But you shouldn't be grabbing it by the collar and forcing it to end the game

buoyant schooner
#

Hmm, ok!

I guess it would make sense to only trigger an event from 1 script.

#

I think I need to now look at some example player input script designs

teal viper
buoyant schooner
#

But, shouldn't the logic and the input be separate?

teal viper
#

It is though.

#

The input is handled in the unity input system.

#

All you do is receive and handle the input, which is the responsibility of the game logic.

#

You're trying to add additional layer of abstraction for the sake of adding additional layer of abstraction.

#

Which doesn't make sense.

crisp anvil
#

what am i doing wrong? I setup a list and fill it and when i come to a method inside the same class after the game starts the list is empty.

1
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

Added house: House (3)
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

2
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

Added house: House (2)
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

3
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

Added house: House (1)
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

4
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

Added house: House
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

5
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)

code

    void FindHouses()
    {
        GameObject[] houseGameObjects = GameObject.FindGameObjectsWithTag("House");

        foreach (GameObject houseObject in houseGameObjects)
        {
            House house = houseObject.GetComponent<House>();
            if (house != null)
            {
                houses.Add(house);
                Debug.Log($"Added house: {houseObject.name}");
                Debug.Log(houses.Count());
            }
            else
            {
                Debug.LogWarning($"GameObject with 'House' tag is missing the House component: {houseObject.name}");
            }
        }
    }

    public House FindClosestHouse(Transform npcPosition, Seeker npcSeeker)
    {
        if (houses == null)
        {
            Debug.LogError("houses list is null! Ensure it's initialized.");
            return null;
        }

        // Filter for valid houses
        var validHouses = houses.Where(house =>
                                       house != null &&
                                       house.transform != null)
                                .OrderBy(house => CalculateDistance(npcPosition, house.transform, npcSeeker));

        if (!validHouses.Any())
        {
            Debug.LogWarning("No valid houses found.");
            return null;
        }

No valid houses found.
UnityEngine.Debug:LogWarning (object)
NPCBehavior:FindClosestHouse (UnityEngine.Transform,Pathfinding.Seeker) (at Assets/Scripts/AI/NPCBehavior.cs:63)
NPCBehavior:Determine (MYNPC/npcAction,MYNPC) (at Assets/Scripts/AI/NPCBehavior.cs:168)
MYNPC:DetermineNPCAction () (at Assets/Scripts/NPC.cs:340)
MYNPC:Update () (at Assets/Scripts/NPC.cs:168)

sorry update hit enter instead of shift enter

buoyant schooner
#

Thank you

timber tide
crisp anvil
#

updated. i hit enter early

timber tide
#

Is there a reason you're using Find over serializing it on the editor

shell sorrel
#

so it is seperated you are just handling it in your player code

crisp anvil
#

Wouldn't i have to find the ones that get instantiated after the game starts?

#

oh wait, i guess i could make the list static and add the in the house.cs start or awake method.

timber tide
#

if you're instantiating them at runtime, then yeah you couldn't just serialize them directly, so what you can do is store them somewhere in a container which you can assign on the editor.

#

and then use the container reference to search through for houses

crisp anvil
#

When i make the list public like the other variables which i can see in the inspector the list doesn't show up even with [serializefield] unless im missing something

timber tide
#

static references / singletons is another good idea too

timber tide
#

as well as making the list accessable

north kiln
#

Also, please don't use Count() when Length or Count exists, Count() may iterate over the entirety of the collection to calculate the length

shell sorrel
north kiln
#

I wouldn't trust shit in Unity's ancient version of .NET, but yes, it's just bad practise and I hate to see it

shell sorrel
#

still would be a cast you dont need

crisp anvil
#

can dictionaries show up in inspector?

shell sorrel
#

unity does not know how to Serialize them

crisp anvil
#

ah

shell sorrel
#

are a few work arounds

#

what are you wanted key and value types?

#

could have a list of structs, then in Awake loop it and make a proper Dictinary from it

crisp anvil
#

I was using a dictionary before i moved to a list for the simplicity. I got the list to show up and i figured i'd ask if they would too.

eternal needle
crisp anvil
#

Ty bawsi

nimble apex
#

i have a UI that is made up by 3 parts, upperhalf , video canvas and bottom part
all 3 UIs have vertical layout group and layout element enabled

im now trying to make a resize algorithm for 3 of them using the min height and preferred height

basically upper half height : video canvas height : bottom part height will be 1 : 0.6 : 0.1 , something like this

#

but , as you see, it seems that the height i obtained with getrectheight() is not correct

#

like upper group is 1012, but the actual height is 1596

#

i think i gonna work on it more first

#

aight i think im good lol

primal turtle
#

is there a line of code that checks whether the gameobject attached to the script is a game object or not?

#

sorry,

#

a prefab or not

shell sorrel
#

if talking runtime code there is not

#

Instantiate does not really care if something is a prefab or justa regular GO in the scene it can make a instance of either

#

for editor code its a different story there are a lot of methods for working with prefabs

primal turtle
#

ok,

#

what about a clone?

#

is there a way to see whether an object is a clone?

#

with a script attached to the clone?

shell sorrel
#

Why?

#

Generally when you instantiate you would just hold on to the returned instance

primal turtle
#

I'm trying to create an endless runner and I have code I want to run only if the game object with the script is a clone

shell sorrel
#

So keep track of the clones as you make them

#

Or set some data on the script

#

Or set a tag

primal turtle
#

yeah

#

but only if it's a clone and not the actually thing because I use the not cloned version as the start.

shell sorrel
#

When you instantiate it returns a reference to the new clone

#

You can use that to set data on it or modify it

primal turtle
#

can you send me the documentation?

honest vault
#

hello my intellisense in vscode isnt working any help

woven crater
#

why is the center of the game object is off with the spirte? how to fix it

timber tide
#

sprite editor when you import the sprite

slender nymph
eternal falconBOT
honest vault
honest vault
slender nymph
#

that's probably due to that being the instructions for Visual Studio not vs code

honest vault
#

so its not needed for vs code?

slender nymph
#

why not follow the instructions for vs code and find out?

honest vault
#

icl i thought they were both the same thing

honest vault
slender nymph
#

did you install the unity extension

honest vault
#

yep

slender nymph
#

did you look for relevant error messages in the vs code console?

honest vault
#

the only error

woven crater
honest vault
slender nymph
#

there it is. regenerate project files in unity. if the issue persists then restart your pc

slender nymph
#

did you try regenerating project files first?

honest vault
#

yea it didn't work

#

restarted vs code after and still same error

woven crater
#

can i have a game object with a custom fuction like being hited and place it as a tile in tile map?

honest vault
covert sinew
#

How the heck do I access these variables, AS THEY ARE, in code? offsetMin and offsetMax do NOT return these values, and I don't know what function of RectTransform does.

#

Documentation doesn't seem to help, the doc for RectTransform doesn't seem to list any specific ways to get at these numbers.

radiant glen
#

Dialogue.cs(29,24): error CS1503: Argument 1: cannot convert from 'method group' to 'string' getting this error, anyone know why?

north kiln
#

!ide

eternal falconBOT
radiant glen
#

Yeah... I know okay thanks

nimble apex
#

have the code inside a function

#

when you spawn out new object, the clone, call that function as well

#

so the function can be called on clones only

covert sinew
#

So, this struct:

    [System.Serializable]
    public struct NamedRectTransform
    {
        public Vector2 offsetMin;
        public Vector2 offsetMax;
    }

is being used in this method:

    void Start()
    {
        startLocation.offsetMin = rectTransform.offsetMin;
        startLocation.offsetMax = rectTransform.offsetMax;

        upDelta = (Mathf.Abs(endLocation.offsetMax.x - startLocation.offsetMax.x)) / transitionSpeed;

        rightDelta = (Mathf.Abs(endLocation.offsetMax.y - startLocation.offsetMax.y)) / transitionSpeed;
    }

But when the Start method is ran, startLocation.offsetMax is getting set to a negative number, (I.E, 10 in the editor window becomes -10 in the script)

Why on earth is this happening? Shouldn't offsetMax return the values for Top and Right, as seen in the below picture? The actual number it's spitting out is -349 and -251

carmine turret
#

Ehhh little confused, Im trying to make a rigidbody jump script, but it only "sometimes" runs. any ideas?

#
    void Jump(){
        if(Input.GetKeyDown(KeyCode.Space)){
            rb.AddForce(Vector2.up * jumpForce * Time.deltaTime, ForceMode2D.Impulse);
        }
    }

This function is being called within the FixedUpdate() method

carmine turret
#

Guess it should be in update then 😛

#

Does the actualy force script need to be in fixedupdate? or is it fine since it is * time.deltatime

north kiln
#

You should not be using deltaTime at all

#

and it should be in FixedUpdate

woven crater
#

can i have a game object that can be set indivitually and place it as a tile in tile map?

#

like a button that can activate certain target

carmine turret
radiant glen
#

making dialoge and getting this error, trying to make the dialoge start when the UI is set to active, anyone have a function I could use or know how to fix this one?

rich adder
radiant glen
#

Okay, any other way I can delay the function for like .5 seconds, its starting just a bit too fast, also thank you so much

rich adder
#
private IEnumerator Start(){
...
}```
radiant glen
#

Dude! Thank you so much!

carmine turret
#

Okay, soooo got my movementy decent, but for some reason my character can like "grip" onto the sides of walls 🥲

#

Otherwise, making good progress!

rich adder
summer stump
covert sinew
#

What editor works best for editing the Ink Json Files?

carmine turret
wild laurel
#

can someone reccomend me a book for learning coding in unity , i already have the basics of c#. need somehelp with vector and unity engine module

rich adder
sour ruin
#

hi is it possible to get structs to display in the inspector?

rich adder
sour ruin
rich adder
#

nah it goes above you class/struct definition

#
[Serializable]
public struct IKNode{
...
}```
sour ruin
#

ah

#

champion

#

thank you

sterile moon
#

No matter what I do, my object is moving left and right on the screen, and not moving along its local y axis. My code will follow this message, followed by an image

#
            // Slider Out
            if (Input.GetKey(KeyCode.P))
            {
                float sliderMoveValue = sliderArm.transform.localPosition.y;

                sliderMoveValue--;

                Vector3 sliderNewPosition = new Vector3(sliderArm.transform.localPosition.x, sliderMoveValue, sliderArm.transform.localPosition.z);

                sliderArm.transform.localPosition = sliderNewPosition;

                //sliderArm.transform.localPosition -= Vector3.up;

            }

            // Slider In
            if (Input.GetKey(KeyCode.O))
            {
                float sliderMoveValue = sliderArm.transform.localPosition.y;

                sliderMoveValue++;

                Vector3 sliderNewPosition = new Vector3(sliderArm.transform.localPosition.x, sliderMoveValue, sliderArm.transform.localPosition.z);

                sliderArm.transform.localPosition = sliderNewPosition;

                //sliderArm.transform.localPosition += Vector3.up;
            }
#

The commented out part was a different attempt

timber tide
#

start throwing in some logging

sterile moon
#

I dont even know what to log at this point, like, i see it going the wrong way when it shouldnt be lol

rich adder
#

Gizmos.DrawSphere(sliderNewPosition, 0.22f)

#

etc.

sterile moon
#

should Sphere be an option because I dont have that

rich adder
#

oh sorry is Gizmos..

sterile moon
#

no worries, had me think there was more broken here than just my brain

rich adder
#

draw some lines too

timber tide
#

nothing is broken, you may be offseting position without taking account of rotation

#

well, as far I can tell by the image

sterile moon
#

im telling it to move positive and negative on the local y, which should follow that green arrow perfectly

timber tide
#

but yeah, gizmos a good idea

rich adder
#

maybe just do transform.up * amount

sterile moon
#

Is that relative to global or local

rich adder
#

that takes rotation in account

#

is local

sterile moon
#

so

sliderArm.transform.localPosition += transform.up * 1;

#

same thing

#

No matter what I do I tell it move and it moves, the wrong way

#

when I try telling it to move on the local y it moves towards the front and back of the truck only, versus up at the angle its supposed to, and even that the transform gizmo shows it should

sterile moon
#

Im in pivot, and local yes

dim brook
#

How do i load this sprite?

#

I want to call the poisonsprite

sterile moon
#

You making a Pokemon game?

dim brook
#

ya

sterile moon
#

Dope af

rich adder
rich adder
sterile moon
#

nope, doesnt seem so

dim brook
rich adder
stuck jay
dim brook
#

unless i make an image for each individual sprite

stuck jay
#

Why does it have such a bad rep?

rich adder
teal viper
dim brook
#

nope

#

ill take a look at that

rich adder
#

the image is called status

stuck jay
# dim brook nope

The basic jest is that you make a folder called Resources and place the sprite there

#

Depends on the path you chose

#

But everything has to be under Resources

dim brook
#

ah

#

well i have all of those sprites under an art folder

rich adder
sterile moon
#

I have to step out for a bit but if anyone has any other ideas on why this object refuses to move along its local y axis, tag me

stuck jay
#

Well to be fair, linking the 7th script in the inspector gets annoying when you have many objects

#

Especially if you're going for a heavy component based system where one object could have 20 or so scripts

rich adder
#

20 scripts??

#

also events ..

#

and simple DI

stuck jay
# rich adder 20 scripts??

If you do it right, you'll be able to implement systems easily in the future by just attaching scripts instead of having to hardcore every action

#

You'll actually end up with less duplicate code this way since you won't have to rewrite your health system on every single thing

rich adder
#

not everything has to be a monobehavior

stuck jay
#

True, but a lot does

dim brook
#

ok so ive put the sprites into the resources folder

#

and ive called them

#

but theyre still a white box

static bay
#

Pokemon?

stuck jay
#

Having a DamageOnCollision script instead of hardcoding it to enemies and players means you can easily make another GameObject damage the player on collision, so maybe you want to make a wall damage you in the future

dim brook
#

for reference

#

yea

rich adder
static bay
dim brook
#

what

rich adder
dim brook
#

like field as in

stuck jay
#

Public Variables

teal viper
# dim brook

I think spliced sprites are accessed via the parent sprite name. It kinda acts as a directory. Might be wrong though.

stuck jay
#

Or, SerializeField private variables

#

That's probably better

woven crater
#

how do i edit layers property to include or remove specific layer inside a script?

clever oar
#

Hello, how to add libraries of sensors into unity? They arent in git. They are only downloadable from their web

woven crater
#

by index or by name and how

rich adder
nimble apex
#

can you override the fields of certain component and make them unchangable?

woven crater
#

ah yes i know that. but i wonder i can just include layer or remove one from a property of a component.... i guess like this?

timber tide
topaz thistle
#

!code

eternal falconBOT
sterile moon
#

now idk if its ACTUALLy moving it along the global z or not, but thats the axis its moving in the directions of, whether by coincidence or actually following it idk

topaz thistle
languid spire
sterile moon
#

Hey Steve, maybe you have an answer to this weird one I got

topaz thistle
languid spire
topaz thistle
languid spire
#

then why this?
if (sprintInputButton.text == "Awaiting Input")

topaz thistle
#

So there's a button next to the sprintInputText

#

(sprintInputText is "Sprint:" btw)

#

And when that button is clicked

#

It is set to "Awaiting input"

#

Once you have clicked a key

#

It is set to that key

#

It's not currently working right now either, but that's a different issue

hot wave
#

https://www.youtube.com/watch?v=3BOn2gs7z04 when I apply this on my character controller and when i touch rigidbody objects, I get launched upward with rigidbody, why UnityChanThink

In this Unity tutorial we're going to look at how we can push obstacles around using a Character Controller and Unity’s physics system.

We'll start by adding a box for the character to collide with. We'll add a Rigidbody component to it so that it reacts to physics,

Next, we'll create a script to apply a force to the box every time the charact...

▶ Play video
languid spire
topaz thistle
# languid spire I'm confused. In start you do sprintInputButton.text = PlayerPrefs.GetString("Sp...

In this video I will be showing you how to create a simple custom keybind system for your unity game! If you have any questions, or need help comment down below and I'll get to you when I can.

Need a login system for your game/application?
Check out KeyAuth! https://keyauth.cc

Need help with code or just want to share your code?
Check out ...

▶ Play video
languid spire
#

I'm not going to watch a video on your behalf

topaz thistle
#

No lol, that's the video I used, and if you skip to the end you can see the code I used

#

Besides, this isn't the issue I'm asking about

#

I've fixed the issue, thanks for your help anyways!

languid spire
topaz thistle
hot wave
#

when I use character controller, and followed the code, it pushes the rigidbody upwards at extreme speed :x why
https://www.youtube.com/watch?v=3BOn2gs7z04

In this Unity tutorial we're going to look at how we can push obstacles around using a Character Controller and Unity’s physics system.

We'll start by adding a box for the character to collide with. We'll add a Rigidbody component to it so that it reacts to physics,

Next, we'll create a script to apply a force to the box every time the charact...

▶ Play video
#

sorry for repost, if ok UnityChanOkay

hot wave
#

UnityChanOkay it is ok now

neon ivy
#

don't mind me just need a link

#

!code

eternal falconBOT
timber tide
brazen canyon
#

What the heck is this error ?

burnt vapor
#

If no, ignore it

candid tree
#

a way to retrieve all objects without having to add "public float" in the script because it would be very complicated if you had to add them all one by one

brazen canyon
burnt vapor
brazen canyon
#

Thank you

candid tree
ruby python
#

Mornin' all,

So, I have this ship controller (it's very basic atm, just trying to get the basics working), but I think I have order of operation or something wrong.

Idea being that when you hold a movement button, the rcs thrusters fire for that given direction of travel.

https://pastebin.com/tG7X3tP2

The issue I'm having is that for some reason the forward/backward thrusters don't fire unless I also hold down either the left/right key. It's very odd.

eternal needle
candid tree
woven crater
#

oof make a new shader graph and everything changed

tulip cliff
#

Guys I have a quick question, I’m trying to make an open world game with different characters and every character has its own abilities. Basic movement is on the ground and there are abilities like “dash” or “sprint” etc, but also abilities like “fly” or “levitation”. I used a CharacterController to move until now but should I switch to a RigidBody addforce / velocity to better control the movement ?

eternal needle
visual hedge
#

noob question:

    [SerializeField]
    [Range(1, 10)] [Min(1)] protected int targetCount = 5;
    public int TargetCount { get => targetCount; protected set => targetCount = value; }

    //pseudocode:
    TargetCount = 3;

based on this pseudocode on top: what is targetCount now? 3 or 5?

#

I am not understanding the get set thing yet

ruby python
#

In the pseudo code you're overriding everything that came before it, so 3.

eternal needle
languid spire
ruby python
visual hedge
ruby python
eternal needle
ruby python
#

Oh the movement code isn't in what I posted (it's in FixedUpdate()) Wasn't relevant to the issue.

brazen canyon
burnt vapor
#

Editor

eternal needle
eternal needle
# candid tree how bro, im newbie sorry

If you dont know how to use a list I suggest you do some c# basics first, or really just find an example on google. There isnt much more I can do other than write the code for you

candid tree
#

oke bro thank u

visual hedge
errant canopy
#

I'm getting back into Unity and working on a simple player controller script: https://paste.mod.gg/hmctgecldcgq/0

I'm having a problem with the player "phasing" through objects and I believe I kno why.
Under my PlayerMove() method I'm translating the transform based on the movement direction and speed. If look straight forward I can go through objects pretty easy but if I look down it's just jittering. So I believe there is something going on there causing me to have this issue.

warm flame
#

i will paypal anyone 10 pounds if they help me with my problem (My problem is that when i pull out my gun the gun doesnt want to shoot ive been following a tutorial from a guy called HawkesByte and when i am this part where i cant shoot when i take out my gun its quite useless please help lmao)

eternal needle
visual hedge
ruby python
errant canopy
#

Right yeah, JUST noticed that haha, but I don't think that'd be the reason for the issue

visual hedge
#

is there a way to make that initial variable not being able to be modified even by existing and child classes?

timber tide
#

you shouldnt be using transform.translate either if you're using rb, no?

languid spire
ivory bobcat
#

You can explicitly teleport with transform though.

errant canopy
languid spire
#

yes, that will respect physics. rigidbody also has a position property

fleet breach
#

Hello this aint a code question but i cant find the "On click" section

#

the left side is a YT tutorial but i aint got it on my inspector

errant canopy
rare basin
fleet breach
#

Thanik you !

ruby python
#

Ah crap, my bad, was looking at the image wrong.

languid spire
errant canopy
#

Yeah, but I'm moving based on the camera direction

#

Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;

languid spire
errant canopy
#

It's just setting the player y to 0

languid spire
# errant canopy

yes, of course

cameraZ.y = 0;
        cameraX.y = 0;

        Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;

movementDirection.y will always be zero

errant canopy
#

Yeah

#

So I'm not sure how I can use the MovePosisiton

#

if y is 0

languid spire
#

but it was 0 before when you used Translate, nothing has changed there

errant canopy
#

It was working before since I wasn't using the Y in translate?

languid spire
errant canopy
#

Sorry I'm really not the most experienced and I've forgotten most I knew, how would I do that 😅

languid spire
#

seriously?

Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;
movementDirection.y = rb.position.y;
errant canopy
#

Ah, sorry misunderstood, thought you meant to the equation

#

But still seems to be doing it 😅

languid spire
# errant canopy But still seems to be doing it 😅

Ah, yes, you probably want transform.forward.y rather than rp.position.y as you are calculating a direction.
or

 Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;

        Vector3 pos = new Vector3(moveSpeed * Time.deltaTime * movementDirection);
        pos.y = rb.position.y
        rb.MovePosition(pos);
ruby python
#

Ooookay, I think I'm monumentally stupid, but I can't see why this isn't working.

I've split my controller script up to make things a little easier to read and a little more 'direct' (I know it's not overly 'elegant' lol.).

Annoying thing is that I had this working a couple of minutes ago, but it suddenly stopped behaving.

The forward/back rcs thrusters no longer fire at all.

https://pastebin.com/QYQdkELM

Any ideas anyone? 😕

#

I know that the values are working correctly because the ship moves (the 1, -1, 0 values get passed to my movement section just fine.

languid spire
#

Again, the thrusters will only work if both key sections are pressed

ruby python
#

Yeah, was literally just about to type that I think that was the issue. Think I should take a break to clear my head a little. lol.

languid spire
ruby python
hot wave
#

in interactor script when i try to access interactable script public Interactable interactable;when doing this itemDictionary[interactable.itemType] I get null exception, why?

#

i know it has a value, by why cant it find the value

#

difficult UnityChanThink

languid spire
#

either itemDictionary or interactable is null. So debug them to see which one

hot wave
#

Debug,Log(itemDictionary[interactable.itemType])?

languid spire
#

no, that tells you nothing

hot wave
#

how do i debug them?

#

if ok UnityChanOkay

#

that is how I check if they have value, but they cant find the value

languid spire
#

if (itemDictionary == null) Debug.Log "itemDictionary is null";
and the same for interactable

hot wave
#

ah okok, I will try UnityChanOkay

#

but I go cook rice first, I go back in a bit ok UnityChanSalute

errant canopy
languid spire
errant canopy
#

But if you do this, the player only moves a tiny bit and goes back to 0 when let go

modest dust
#

probably because you set the position elsewhere

errant canopy
#

Don't believe so

keen dew
#

The MovePosition parameter is a position, not a direction

#

so it should be Vector3 pos = transform.position + moveSpeed * Time.deltaTime * movementDirection;

errant canopy
#

Ah perfect

#

Thanks for the help 👍

hot wave
#

I have public Interactable interactable; and has the interactable = hit.collider.GetComponent<Interactable>(); but only on the bottom/after this thingy itemDictionary[interactable.itemType], and not before, is that what is causing it?

#
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, itemDictionary[interactable.itemType], interactableLayermask)) //when raycast finds something
        {
            
            var selection = hit.transform;
            selectionRenderer = selection.GetComponent<Renderer>(); // Assign selectionRenderer here
            if (selectionRenderer != null)
            {
                selectionRenderer.material.SetInt("_enableFresnel", 1); //enable fresnel when in sight
                ///Debug.Log("logging");
            }

            _selection = selection;

            if (hit.collider.GetComponent<Interactable>() != null)// if it find that interactable is in, used to be false instead of null
            {
                if (interactable == null || interactable.ID != hit.collider.GetComponent<Interactable>().ID)
                {
                    interactable = hit.collider.GetComponent<Interactable>();
                    currentInteractTimerElapsed = 0f;
                    Debug.Log("New Interactable");``` it is kind of like this, but ``itemDictionary[interactable.itemType]`` is null
#

not sure why UnityChanThink

keen dew
#

Well obviously there's not going to be anything in the variable before you put something in it

#

Why are you using it in the raycast anyway?

hot wave
#

so that it can find an interactable item and it could be interacted, not sure if right, itemDictionary[interactable.itemType] is for itemtype, different items have different ranges to be interacted

#

like if it is broom (itemtype 1), it will have a range of 2, and if it is car (itemtype 2), the range is 6

keen dew
#

You can't select the distance of the raycast based on the thing that the raycast might hit, that makes no sense

hot wave
#
    {
        /*rotationDictionary.Add(1, (new Vector3(-30, 0, 0), new Vector3(30, 0, 0))); // Example values for item type 1
        rotationDictionary.Add(2, (new Vector3(20, 0, 0), new Vector3(0, 0, 0))); // Example values for item type 2
        rotationDictionary.Add(3, (new Vector3(0, -10, 0), new Vector3(0, 0, 0))); // Example values for item type 3*/
        itemDictionary.Add(0, 12f);
        itemDictionary.Add(1, 2f);
        itemDictionary.Add(2, 6f);

    }``` i made a dictionary for them
keen dew
#

You have to make the raycast without the max distance, then after it has hit something check the distance

hot wave
#

ah okok, I thought it would work simultaneously UnityChanOkay

#

but i have to check the item type of interactable for the range, how would that work?

#

and how would no range work? leave it blank or no

keen dew
#
if(hit.distance <= itemDictionary[interactable.itemType])
#

itemDictionary is a bad name for it btw and using a dictionary for this purpose is questionable

hot wave
#

I want to add other elements for the item also, but not sure which to use

#

I only know dictionary and enum atm UnityChanDown

#

it is like, I want to make itemtype, but it will have their own characteristic, and it would only be called by their number

#

or maybe rename it to rangeDictionary?

keen dew
#

Variables don't usually have their type in their names. I'd call it maxInteractionRange

hot wave
#

i still get NullReferenceException: Object reference not set to an instance of an object

#

interactable is still null, but interactable not being null is dependent on the raycast

keen dew
#

...show the code

hot wave
#

!code

eternal falconBOT
hot wave
#

I want to learn how to stop null exceptions UnityChanThink also,if there are other tips, if ok

#

I always have a difficult time when trying to use codes that arent declared yet, but needs to be put in an area before the declared code, maybe why it is null

hidden sleet
#

I'm about to work on an inventory system for a shooter type game, so the npcs and player would have stuff liek grenades, guns, ammo and whatnot. For this inventory, what might the best approach be? I'd want said inventory to just be of one type, so would making a 'slot' class that just holds the name of the item and maybe some ID from an item database be a good approach? In that case, how could you track individual details like the ammo in a weapon etc? I'm not too sure what the general class structure for a system like that might look like

keen dew
#

The check is too early

fleet breach
#

question can we make a shopping app on unity ?

charred spoke
#

Yes

hot wave
# keen dew The check is too early

but it wont work as intended if the check is later, or is it ok?, can i move interactable = hit.collider.GetComponent<Interactable>(); up?

charred spoke
#

But why would you use an entire game engine to make a shopping app is another thing

loud python
keen dew
# hot wave but it wont work as intended if the check is later, or is it ok?, can i move ``i...
if (hit.distance <= itemDictionary[interactable.itemType])
{
    interactable.isHighlighted = true;
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Debug.Log("Toggled");
        targetObject.SetActive(true);
    }

    if (Input.GetKey(KeyCode.E))
    {
        //Debug.Log("it works");
        // Perform radial interaction here
        PerformRadialInteraction();
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            currentInteractTimerElapsed = 0f;
        }
        UpdateInteractProgressImage();
    }
    else
    {
        currentInteractTimerElapsed = 0f;
    }
}
#

this is the only place where you need to check it, if I read the intention correctly

weary finch
#

How are you handling the mouse click?

hot wave
#

item type have different ranges for both fresnel and interaction

keen dew
#

Do you want the fresnel shown on any object, interactable or not?

hot wave
#

only on interactable

keen dew
#

Then you need to move that code lower, where it checks if the object is interactable or not

hot wave
#

okok UnityChanOkay so it goes like main update code-> itemDictionary (or max range)-> fresnel code?

weary finch
#

(cache your get components pls)

hot wave
weary finch
#

I mainly see this code, at line 108

if (hit.collider.GetComponent<Interactable>() != null)// if it find that interactable is in, used to be false instead of null
{
    if (interactable == null || interactable.ID != hit.collider.GetComponent<Interactable>().ID)
    {
        interactable = hit.collider.GetComponent<Interactable>();
        currentInteractTimerElapsed = 0f;
        Debug.Log("New Interactable"); //something
        // Access the itemType property of the Interactable component
        // Add your logic based on the itemType here

    }
  .
  :
}
keen dew
#

You'll have to learn to read what the code does. It runs one line at a time, from top to bottom. If you just read out loud what the code does you can see if it's sensible or not ("Enable fresnel. If the item is interactable, check keypresses..." oops)

loud python
weary finch
hot wave
weary finch
hot wave
#

wait I go eat UnityChanSalute thank you for the help so far

#

go eat also ok?

loud python
#

is it?

weary finch
#

Mmm, i don't think so, but i might be wrong, it was a long time since I worked with UI but normally I had to implement it myself the click, raycast, find object, move and snap to mouse position

loud python
#

because ive noticed when I have the button click logic in, it doesnt click the one I want,

loud python
#

and I think its in there somwhere the drag component

#

weird...Icant find anything

#

it was just automatically applied when I created the button

#

So its a behavior the is part of scroll view.

#

so wtf is wrong with my thing lol

#

ohhh these item prefabs are all child of the scroll veiw, could this be the reason?

#

and if so, how to fix?

woven crater
#

what is secondary texture?

wintry quarry
#

In what context?

woven crater
# wintry quarry In what context?

im following this tutorial by Brackeys. but idk whats the use of secondary texture
https://www.youtube.com/watch?v=WiDVoj5VQ4c

In this video we create an awesome Glow effect for extra flare!

► Check out Popcore! https://popcore.com/career

● Download the project: https://github.com/Brackeys/2D-Glow

● Get Gothicvania Church Pack: https://assetstore.unity.com/packages/2d/characters/gothicvania-church-pack-147117?aid=1101lPGj

● Learn more about 2D Shader Graph: https:/...

▶ Play video
#

at 9:30

wintry quarry
woven crater
#

nvm i think i got it

swift crag
#

you can use textures to store much more than plain color data