#💻┃code-beginner

1 messages · Page 748 of 1

fervent bramble
#

oh

wintry quarry
#

you wrote IPlayerLocomotionActions

fervent bramble
#

thanks

#

i didn't see that

#

now i am getting this Assets\Adam O'Keefe\FinalCharacterControler\Scripts\PlayerLocomotionInput.cs(16,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

wintry quarry
fervent bramble
#

oh ok

wintry quarry
#

Note that this: PlayerLocomotionInput.cs(16,13) is telling you the filename, line number, and column number of where there is an issue

#

that's a good place to compare your code to what is in the video

fervent bramble
#

thanks

#

sorry i am new

wintry quarry
#

(I know )

fervent bramble
#

lol

nova saffron
#

Hello how are you I don't know English but I need help

radiant voidBOT
# rich adder 👇

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

nova saffron
#

It's that the problem doesn't come out on yotube is that I get that unity doesn't have permission

fickle plume
#

@nova saffron Don't cross-post on the server and this is unrelated channel as well.

jovial sentinel
#

Hi, I'm trying to make an object appear at mouse position (At the point a raycast hits another object),
(In a 3d, first person controlled project)
I know I need the point hit by the raycast, and to transform the object to the position (accounting for its dimensions), and to get the side the raycast hits (wich also probably implies rotating the object to match the face I'm looking at)
(Like this, https://www.youtube.com/watch?v=1ecYZXNneu0, but in first person)
I don't really have much experience on Unity and I'm trying to learn, without using AI (As it's wrong most of the time), where could I learn how to do so?

rich adder
desert temple
#

I'm having some trouble creating a script that just seamlessly loops the background for an endless sidescroller. Does anyone have any advice?

using UnityEngine;

public class BackgroundScroller : MonoBehaviour
{
    public Rigidbody2D rb;
    public float scrollSpeed = -2f;

    private float width;

    void Start()
    {
        // Get collider and rigidbody
        BoxCollider2D collider = GetComponent<BoxCollider2D>();
        rb = GetComponent<Rigidbody2D>();

        // Get width of the background tile
        width = collider.size.x;

        // Disable collider if it’s only used for measuring
        collider.enabled = false;
    }

    void FixedUpdate()
    {
        // Move the background left each physics frame
        Vector2 newPos = rb.position + Vector2.right * scrollSpeed * Time.fixedDeltaTime;
        rb.MovePosition(newPos);

        // Check if background has scrolled off-screen
        if (transform.position.x < -width)
        {
            // Move it to the end of the loop (seamless reposition)
            Vector2 resetPosition = new Vector2(width * 2f, 0);
            transform.position = (Vector2)transform.position + resetPosition;
        }
    }
}
#

I can get it moving, but the process of getting the first background to move to the second isn't working.

cosmic dagger
desert temple
#

Because that's what the tutorial I was following told me to do. The script uses it too.

cosmic dagger
#

If you're only moving the GameObject and it doesn't interact with anything else, I see no reason to put a Rigidbody on it. That's all . . .

desert temple
#

Should I start with the process of scrolling in some other way?

cosmic dagger
#

When I did this, I placed a trigger collider off-screen. When the background hits the trigger, I reposition it on the other end . . .

rich adder
cosmic dagger
desert temple
#

I'll probably just reset everything and try a different scrolling background tutorial.

cosmic dagger
rich adder
desert temple
prime oriole
#

Tiny thing but is there a way to use ContextMenu if the function has a parameter?

cosmic dagger
misty grotto
#

hi im trying to change my first person camera to where i can look down and around to where i can see my shoulders with out my body turning with my camera but then if i look past that then my body turns. if you dont know what i mean, rust has this type of camera in their game. if someone can help me out or show me a tutorial that has this it would be very helpful.

rocky canyon
#

any camera setup/script would work.. i dont have a character mesh here.. but same concept.
if u wanted to make the arms follow the camera you'd use something like unity's animation rigging package i believe

#

to take control of the hands/ make them follow the camera's up and down rotation

#

or if its only arms/hands could just parent them to the cam

misty grotto
#

i used the unity animation rigging package so that my head and top body would follow what im looking at but realized its pointless if i the body is always following the camera

misty grotto
rocky canyon
#

yea same..

  • Root (the actual CC/Collider/Movement)
    • Camera
    • Graphics
#

Controller moves Left and Right (making the cam follow that axis automatically)
The camera moves Up and Down (relative to the roots rotation)

#

common way to do first person cams

rocky canyon
# misty grotto i used the unity animation rigging package so that my head and top body would fo...

make the body follow the roots rotation
make the arms follow the cameras rotation
edit: ahh, i see, ya to have the body moving in one direction and the arms moving in another direction you'd end up needing to change the way the movement works
to make the camera and body seperate you'd have to change it so the player moves like a top-down controller like when left is always west and so on

-# clamp so u can't twist ur character like a pretzel

#

u could also have the body just twist to the direction ur moving.. (so instead of strafing ur running sideways w/ ur torso facing the cam)

#

but in my opinions those type of animations always look ackward to me

#

u'd just use ur input to change the animation rigging ik target or w/e

misty grotto
#

okay this is what my project looks like, its my first one and i know its messy. but i dont understand all the terms your using, what should i do?

misty grotto
rocky canyon
#

not sure how you'd make the camera follow along w/ the head and still have ur camera code work..
because the camera code is in control of the rotation. so the animation rigging stuff wouldn't matter to it unless it was parented beneath the head-bone
and u changed the movement code to work differently.. (maybe controlling that ik target instead?) not sure to be honest

#

in the scheme of things u would probably only want the camera to track the position (doing the head bobs and stuff) and ignore the rotation of the head..

it would conflict with ur mouse look code... unless u were to make the mouse code rotate relative to the head-bone's rotation which i figure would look and feel strange

#

and/or don't have the IK system affect the head at all.. only the shoulders and torso
ur camera code would rotate the camera and the head.. (maybe a seperate ik)

#

and anythings possible.. rotations can be relative or combined w/ other rotations to achieve more complex camera scripts

misty grotto
#

do you have any tutorials or terms i can search on youtube to help, im still figuring out unity and it would be very hard for me to even try what your talking about lol, either way i appreciate the help thank you.

rocky canyon
#

Having a first-person controller with a disembodied character is not very immersive, even with all the bells and whistles of procedural camera animation and tricks that we've been adding so far. Let's see how to add a proper character to our first-person controller, and do it with the available characters and animations from Mixamo without requi...

▶ Play video
#

you'd might have to change ur movemnet/camera code

desert temple
#

So. I have a scrolling background working fine, and my main controller working fine, but now I'm trying to create some random obstacles generated in the way. I'm trying to get my random objects to be generated, but so far they're not quite happening.

 private Renderer bgRenderer;

 void Start()
 {
     ResetObstacle();
 }

 // Update is called once per frame
 void Update()
 {
     bgRenderer.material.mainTextureOffset += new Vector2(speed * Time.deltaTime, 0);
 }

 void ResetObstacle()
 {
     transform.GetChild(0).localPosition = new Vector3(0, Random.Range(-3, 3), 0);
 }```
It's just supposed to create a new random object, with the asteroid childed to the background in the inspector.
slender nymph
#

i don't see any code that would create a new object here

#

also why are you offsetting the texture every frame instead of just moving the object?

desert temple
#

I had the texture cycling through to give the illusion of the background moving, but I think I may have figured out what I need to do.

rocky canyon
#

for obstacles u need to use real objects.. (move its transform <-) over time to match the speed of ur scrolling background.. (spawn them off to the side) can reuse them.. once they go off the other side of the screen you just reuse it and move it to the other side (can randomize where they spawn using a min-max range)

#

if ur scrolling a texture nothings actually moving

near thicket
#

How come I can't drag and drop the "pointsource" gameobject on the left hand side to the script's field on the right?

misty grotto
near thicket
cosmic dagger
#

What you're looking at is the actual script file (asset) in the project folder. This will only set default values. If you have a prefab, you can place it as the default PointSource, but then you'd need to set it correctly when gameplay starts . . .

fervent bramble
#

Parameter 'Hash 46624491' does not exist.
UnityEngine.Animator:SetFloat (int,single)
AdamOKeefe.FinalCharacterController.PlayerAnimation:UpdateAnimationState () (at Assets/AdamOKeefe/FinalCharacterController/Scripts/PlayerAnimation.cs:41)
AdamOKeefe.FinalCharacterController.PlayerAnimation:Update () (at Assets/AdamOKeefe/FinalCharacterController/Scripts/PlayerAnimation.cs:29)

https://paste.mod.gg/xkwrbkzeqvci/0

wintry quarry
#

but your code is looking for one

#

so you get an error

fervent bramble
#

oh ok

#

i am following this tutorial https://www.youtube.com/watch?v=PIFQbxMgT0c

In part 2 of this series, we go through animations for running, sprinting and idling states. Additionally, we make a basic enum state machine to keep track of our player's movement state.

In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topi...

▶ Play video
#

thanks

wintry quarry
fervent bramble
#

thanks

#

i had just copied the suroce code thats why

fervent bramble
#

i know

cosmic dagger
fervent bramble
#

i know i just keep messing up and then coming here cuz i misspeld if or some shit and then feel more dumb

#

Plz help

slender nymph
old iris
#

https://apps.apple.com/vn/app/this-is-blast/id6738323233
hi guys I am trying to clone this casual game but I don’t know where to start. Could anyone give me some clue so I could Google it later. Tysm :unity: :unity:

App Store

‎Dive into This is Blast!, the ultimate color-matching block shooter! Line up your shots, tap to aim, and blast away blocks of matching colors. With simple controls and challenging levels, it’s a game that’s easy to pick up and hard to put down.

From the very first level, This is Blast is easy to pi…

sour fulcrum
#

:/

slender nymph
radiant voidBOT
slender nymph
#

oh and don't crosspost

old iris
#

I crosspost by mistake I thought I was on different sever

hot wadi
wary orchid
lunar axle
# fervent bramble

id recommend just hiding the player (deactivate it). if you provide 3rd person views too and when the player decided to switch the camera views, u can simply unhide it (activate it).

kindred iron
#

Guys, I made a state machine for my character, but the issue is that I can’t jump and walk at the same time. It’s a really big problem. I searched on YouTube — I think it’s called an advanced state machine — but unfortunately, I didn’t understand it. Can someone explain it to me easily?

kindred iron
#

its a State pattern

lunar axle
kindred iron
#

no you dont use animator

#

its a coding pattern

#

the way how you code

lunar axle
#

so you control the animation based on code?

kindred iron
#

to code cleaner and more readable

kindred iron
#

its a coding pattern

naive pawn
kindred iron
naive pawn
#

well there's your issue lol

#

if they're separate states, they can't happen at the same time

#

could just make them the same state

#

a state of no active action, so free movement

kindred iron
#

yeah so i asked myself how people solve this problem and they usually use hierarchical state machine for this problem

naive pawn
#

you asked yourself...?

kindred iron
#

yeah

naive pawn
#

how do you know that's the actual answer then lol

kindred iron
#

I told you that i found this on youtube and it works but i couldnt understand it

lunar axle
naive pawn
#

the state machine, or the hierarchical state machine?

kindred iron
#

can i send links here?

naive pawn
#

sure

#

but answer my question first

kindred iron
#

Learn how to program a Hierarchical State Machine in Unity with this new video break down and tutorial!

Want to learn how to program state machines in Unity? This video will help get you there! Today we'll go over important concepts of the State Pattern and refactor our overly-complex code into a clean hierarchical state machine! With a detaile...

▶ Play video
#

if there is another way to solve this problem then im all ears

naive pawn
#

if you're a beginner, i'd say this is just overkill for getting into unity and making something to start

kindred iron
#

then it would see messy because at this point i would have to the same thing for swimming too and for swimming i would have to write walk and like eating state at the same time

hot wadi
#

Yeah, just use Animator and set trigger for jump

kindred iron
#

and i have experiences on roblox coding

hot wadi
#

Do u have experience with state machine in prior?

kindred iron
#

no its my first time using it with jump state

naive pawn
#

imma be real, time spent coding doesn't really say much

kindred iron
#

i coded state machine before without jump state for 2d

hot wadi
#

If u want to get into more advanced coding, u can start with what u are doing. But it's not recommended for simple movement logic.

kindred iron
kindred iron
#

like imagine im using the easy method for that every time and i woulnt be able to better methods

hot wadi
#

Easy =/= messy. Optimization is the key

kindred iron
#

methods

hot wadi
#

U can write clean code without using complex methods, as long as it meets the requirement of the project

#

It's just readable code

lunar axle
naive pawn
kindred iron
kindred iron
rocky canyon
#

pfft.. more like 3 years u still a beginner imo 😄

kindred iron
naive pawn
#

considering you said you're a beginner, i'd recommend just making it work before making it good

rocky canyon
#

make it work.. figure out why it works (in and out) then make it good

#

extra step i added there @naive pawn

kindred iron
rocky canyon
#

use multiple sources always

kindred iron
kindred iron
#

i know how to make character controller like the basic stuffs

rocky canyon
#

coding better and learning good code structures/syntax/and patterns just comes from experience

#

like trial and error

kindred iron
rocky canyon
#

ya, you'll just find basic blanket tutorials

#

like SOLID

lunar axle
#

thats a disadvantage for u

rocky canyon
#

how u apply it is almost always relative to you and ur project

#

and learning how to apply it is what comes from experience

kindred iron
kindred iron
#

if I dont try i will never be able to collect experiences then

lunar axle
rocky canyon
kindred iron
# rocky canyon what patterns or concepts u trying to learn?

state machine. I can do it its easy for me but the issue is i cant jump and walk at the same time i cant swimm and walk at the same time i cant eat and swimm and walk at the same time you know what i mean? but normal state machine is easy to code

eternal needle
#

Movement really doesnt need to be a state machine unless this actually solves something in your system. Separating things into states when you really dont have separate states just makes things more difficult

rocky canyon
#

start with enum learn it in and out
then u can go into the more advanced state machines.. then u got ur boss level: stateless state machines

hot wadi
#

Especially if u are using animator, then u just create more overhead

eternal needle
#

A state machine by itself is a simple concept. Youre just seemingly overcomplicating it by having 2 states that really arent separate in the first place

kindred iron
rocky canyon
#

messy code is part of the process 😄

#
  1. else-if chains
  2. switch statements
  3. state-machine
#

thats how i progressed ^ atleast

eternal needle
#

Compare the two, either a system that doesnt work (your current setup) or a system thats messy. Which one will be playable?

rocky canyon
#

eating doesn't seem to me like it'd need to be a state..
just check the state

kindred iron
rocky canyon
#

canEat? areswimming? Drown

hot wadi
#

"Running, walking, jumping" are all part of Moving state just to be clear

rocky canyon
#

this is me day to day ^

kindred iron
rocky canyon
#

i just find something that i dont think is nice.. and refactor it..

#

and then move on.. rinse and repeat

#

it kinda cleans up organically

eternal needle
hot wadi
rocky canyon
#

you can break the code into pieces many different ways.. (without even needing a statemachine) thats not really the purpose of a statemachine

kindred iron
rocky canyon
#

a statemachines purpose is lock the thing into a single state... and run code accordingly

rocky canyon
eternal needle
#

The one who makes it simple seemingly makes it faster already

rocky canyon
#

ya, and also dont even think about performance until u need to

#

gonna shoot urself in the foot and not realize it

hot wadi
#

If u really want to pratice the concept, it's better to use for other cases like game states

eternal needle
kindred iron
kindred iron
eternal needle
#

Idle wouldn't matter. Thats just moving with input of 0

hot wadi
kindred iron
rocky canyon
#

a statemachine for a cc
would be like

walking / swimming / flying

#

when eating you'd allow that in the walking and flying state but not the swimming state for example

#

but eating wouldn't be a state

eternal needle
#

Eating itself yea its hard to say what to do there. There are definitely designs where you could make it a state like if it slows you down, doesnt allow jumping etc

rocky canyon
#

also true..

#

statemachines will take a while to get good at ..
you'll get enough experience to know later on when and how to use them more properly

hot wadi
#

while (eating) defecate = false;

kindred iron
#

shouldnt i be able to walk when i swimm? but playing another animation and slower

rocky canyon
#

pfft.. watch me

hot wadi
rocky canyon
hot wadi
kindred iron
eternal needle
rocky canyon
#
  • You can’t be both Walking and Swimming at the same time — you’re in one environmental state.
  • But you can be Walking and Eating — those are actions, not global states.
kindred iron
#

then i should change the state name walking something different because now it contains jump and maybe other things

rocky canyon
#
void HandleMovement()
{
    switch (currentMovement)
    {
        case MovementState.Walking:
            HandleWalking();
            break;
        case MovementState.Swimming:
            HandleSwimming();
            break;
    }
}

void HandleActions()
{
    if (isEating && currentMovement != MovementState.Swimming)
        HandleEating();
}```

heres an example.. (the states of movement are *exclusive* its either one or another.. thats when u could use a state machine)
for something like eating.. (even if it based on which state ur in it doesn't necessarily need to be part of the state handling..
u could just consider which state ur in when attempting to eat..
rocky canyon
#

lol

kindred iron
#

xd

kindred iron
# rocky canyon lol

What do you think?
What should i name it instead of walking because it contains jump

rocky canyon
#

wasn't a joke.. just silly naming..

#

dry state = on ground
wet state = in water

lusty pivot
slender nymph
#

!code

radiant voidBOT
lusty pivot
# slender nymph !code

//Unityの基本クラス(MonoBehaviour, Rigidbody2D など)を使うための宣言です。
using UnityEngine;
//新しい「Input System」APIを使うための宣言です(従来の Input.GetAxis() ではなく)。
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
//Class 名はファイル名と同じにする必要があります。

{
[SerializeField] private float speed = 5.0f; // 横移動速度
[SerializeField] private float jumpForce = 10.0f; // ジャンプ力
[SerializeField] private float groundCheckDistance = 0.1f; // 設置面判定の距離
[SerializeField] private LayerMask groundLayer; // 地面レイヤー(Tilemap用)

private Rigidbody2D rb;
private PlayerInput playerInput;
private bool isGrounded;


// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
    rb = GetComponent<Rigidbody2D>();
    playerInput = GetComponent<PlayerInput>();
}

// Update is called once per frame
void Update()
{
    //移動処理
    Vector2 move = playerInput.actions["Move"].ReadValue<Vector2>();
    rb.linearVelocity = new Vector2(move.x * speed, rb.linearVelocity.y);

    // ジャンプ処理
    if (playerInput.actions["Jump"].triggered && isGrounded)
    {
        rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
    }

    // 接地判定
    CheckGrounded();
}

private void CheckGrounded()
{
    // 下方向にRayを飛ばして、地面に当たったら接地中
    //RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, groundLayer);
    //isGrounded = hit.collider != null;

    Vector2 checkPos = new Vector2(transform.position.x, transform.position.y - 0.3f);
    isGrounded = Physics2D.OverlapCircle(checkPos, 0.2f, groundLayer);
}

// SceneビューでRayを可視化(デバッグ用)
private void OnDrawGizmosSelected()
{
    Gizmos.color = Color.red;
    Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundCheckDistance);
}

}

lusty pivot
#

I suppose the gap between BoxCollider2D and Rect tool might be one of causes.

oak mountain
#

This is my knockback code, how it works is basically it just applying force onto a direction from the source (aka you the player who hit the enemy)
in the tutorial, they increased the mass of the object, and the object in the video was a cube instead of a cillinder, so maybe that could have something to do with it

using UnityEngine;

public class EntityKnockback : MonoBehaviour, IHitable
{
    private Rigidbody rb;

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

    public void Execute(Transform executionSource)
    {
        KnockbackEntity(executionSource);
    }

    public void KnockbackEntity(Transform executionSource)
    {
        Vector3 dir = (transform.position - executionSource.transform.position).normalized;
        rb.AddForce (dir, ForceMode.Impulse);
    }
}
keen dew
lusty pivot
keen dew
#

You should consider following a course or a tutorial instead so that you'd know what your own code does

keen dew
oak mountain
keen dew
#

Is having it fly off the map any better? Fix the fall-off-the-map problem properly and the knockback issue solves itself

oak mountain
#

damn you right

hot wadi
#

It's basic physics

oak mountain
#

bruh the fucking gravity works now??

#

it doesnt fall of the map i just ticked it on

#

well its working now, if it aint brokey, dont fix it

#

😭

#

now another issue

#

since its a bean, it just falls instead of being like pushed

hot wadi
oak mountain
keen dew
#

Freeze the rotation

earnest wind
#

is there some event when Time.timeScale gets changed?

oak mountain
#

cuz their animation will be all sorts of weird if they can't rotate around

rocky canyon
#

you'll still be able to rotate it w/ code and anims..

#

it just stops the physics from affecting it

oak mountain
rocky canyon
#

just lock axis's that are needd

keen dew
#

You can keep the Y rotation unfrozen, X and Z are what make it tip over

rocky canyon
#

axi..

oak mountain
hallow acorn
#

hey i made a marching cube algorithm implementation and i tried interpolating it but i get this error: "Mesh '': abnormal mesh bounds - most likely it has some invalid vertices (+/-inifinity or NANs) due to errors exporting.
Mesh bounds min=(-nan(ind), -nan(ind), -inf), max=(-nan(ind), -nan(ind), -nan(ind)). Please make sure the mesh is exported without any errors.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)"

i think it has something to do with the result of value2 - value1 as it could be 0 and i would be dividing by it. i can provide the full code if needed, heres the most important snippet:

Vector3 edgeStart = position + MarchingTable.Edges[triTableValue, 0];
                Vector3 edgeEnd = position + MarchingTable.Edges[triTableValue, 1];

                float value1 = GetDensity(edgeStart.x, edgeStart.y);
                float value2 = GetDensity(edgeEnd.x, edgeEnd.y);


                Vector3 vertex = edgeStart + (heightThreshold - value1) / (value2 - value1) * (edgeEnd - edgeStart);


                vertices.Add(vertex);

GetDensity is just providing me with my height value igenerated with my noise

umbral pond
#

should i keep my movement script in Update or FixedUpdate most tutorials i see is Update but since update called per frame would movement be diffirent on diffirent devices (faster or higher jump at better fps)

cosmic quail
#

we dont know anything about your movement script

#

so we can't say

umbral pond
#

its with invoke unity events new input system
rb.linearvelocity = new Vector2(moveX * moveSpeed , rb.linearvelocity.y)

#

this kind of script

grand snow
hallow acorn
grand snow
#

its better to just add an if statement for such things as conditional breakpoints can slow down execution a lot

grand snow
#

@hallow acorn add something like this and then attach your IDEs debugger to unity

if(Single.IsNaN(vertex.x) || Single.IsNaN(vertex.y) || Single.IsNaN(vertex.z))
{
  Debug.Log("Found NaN!");
  Debugger.Break(); //make the debugger break here without a breakpoint
}
grand snow
#

If this is confusing then you need take the time to learn about debuggers before trying to implement a complex algorithm

naive pawn
cosmic quail
#

i think if you're setting velocity directly then it can't be different depending on the fps

hot wadi
#

They usually keep Input value in Update() and anything physics-based in FixedUpdate()

umbral pond
#

Thanks

umbral pond
#

i wanna make my player jump shorter on light tap but i still jump in same jumpForce

#

anyone knows solution?

frail hawk
thorn holly
#

is using animator.GetStateInfo to keep track of state bad practice?

frail hawk
#

it depends

polar acorn
thorn holly
polar acorn
#

The animator should be mostly an independent system. You should pass data to it, rather than reading from it

thorn holly
#

to keep track

polar acorn
#

Or make a code based state machine and have that state machine drive the animator

frail hawk
#

or use event keys inside your animation

thorn holly
thorn holly
frail hawk
#

still you can do that

polar acorn
thorn holly
#

its a different game object

#

i could use another script to bridge the gap but that feels inefficient

frail hawk
#

i´d say do what works best for you

thorn holly
#

thank you

frail hawk
#

you are cross posting

umbral pond
#

which one should i remove

frail hawk
umbral pond
#

aight

#

can you help me tho

hot wadi
umbral pond
#

ill try

plush rampart
#

Can anyone help me make a game

polar acorn
radiant voidBOT
# polar acorn !collab

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

tacit prism
#

I’m so glad I started learning about them, they’re so fucking cool

twilit ocean
#

What do you think would be the most appropriate way to create a health/damage system for enemies in a game and why?

rich adder
polar dust
#

If something directly hurts an enemy, you only need to tell that enemy how much damage you are doing. And then the enemy itself can determine whether it should be killed or not

rich adder
#

unless you use an Interface , that doesn't scale very well

twilit ocean
twilit ocean
true pine
#

what's the point of this global volume entity that ends up here whenever I create a new project? is it safe to delete it?

rich adder
#

an interface at least creates a "common" functions/properties they all share...say a IDamageable etc..
like, similar to a dedicated component i mentioned before..

twilit ocean
rich adder
twilit ocean
rich adder
#

Left could be okay too but it really depends also on the game and design

#

Some games use a centralized system and some let components handle their own thing

twilit ocean
# rich adder Left could be okay too but it really depends also on the game and design

I just thought that left one would be easier to scale up if I got the system running, like creating a new enemy would be as easy as putting some stats here and there and let the system take care of the rest instead of turning knobs for each enemy.

I don't know much of what I talked about because I'm experimenting with ideas, but it is similar to the idea of creating a centralized system that handles a general function of the game.

Just wanted to be sure it wasn't some terrible idea that a new game dev might have.

#

Might also be useful if I wanted to dive deeper in that function in the future?

rich adder
twilit ocean
#

I'm not sure how I'll modify them in the future, but the current plan is that.

rich adder
#

If I want to Damage a Player or Bullet or Enemy, how will you tell which I can damage

#

hence why I suggested , using a separate component to handle that or an Interface

#

if you used a POCO and if they all had the same HealthStats stored you need a way to know you can access and Damage/Heal that..

twilit ocean
#

As far as health interactions go, that's it

rich adder
twilit ocean
rich adder
#

image you had IDamage
it has a method Damage(int amount)

in your public class Enemy : MonoBehaviour, IDamage
Like that..
Now you dont care to damage Enemy, but you care you can damage anything with the Idamageble because it has a Damage method

twilit ocean
polar dust
#
public interface IEnemy {
    float Health { get; set; }
    float MaxHealth { get; }
    void Heal(float amount);
    void Damage(float amount);
}```This ensures that your Enemy would always have all of this stuff
rancid ingot
#

Any clue why an overflow occurs?

rich adder
rich adder
twilit ocean
rich adder
twilit ocean
rich adder
#

they are useful for many things besides health ofc

polar dust
#

If you did something like this, it ensures the Enemies always have a max of 100 health, and the only thing youd need to do is Enemy.Heal(5f) or Enemy.Damage(20f) there isnt so much you have to worry about, because the Enemy itself handles something like checking if it ran out of health

public class Enemy : IEnemy {
    float _hp;
    public float MaxHealth => 100f;

    public float Health {
        get {   return _hp; }
        set {   
            _hp = value;
            if( _hp <= 0f ) { Die(); }
            if( _hp >= MaxHealth ) { _hp = MaxHealth; }
        }
    }
    public void Damage(float amount) {
        _hp -= amount;        
    }
    public void Heal(float amount) {
        _hp += amount;        
    }
}
twilit ocean
polar dust
#

written in notepad so it might not compile

rancid ingot
# rich adder what do mean "overflow"

“overflow” means that a numeric value has exceeded the maximum (or minimum) limit that the variable type can hold, causing unexpected behavior or a crash.

twilit ocean
rich adder
twilit ocean
rich adder
#

gamedevbeginner.com usually has pretty decent blogs on these unity things, but theres plenty of video formats too anyway and Unitys own site I sent, though their example code is a bit gringe lol

twilit ocean
#

I like text because it's easier to reference and look back into

polar dust
#

a convenient thing you get for interfaces is that you can have different classes for your enemies like this

public interface IEnemy {
    float Health { get; set; }
    void Squashed();
}
// each Enemy gains a "Health" property and a "Squashed" method
class Goomba : IEnemy {
  public Health { get; set; }
  public void Squashed() {}
}
class Bowser : IEnemy { ... }
class Koopa : IEnemy { ... }```
The benefit of this is if Mario jumped on an enemy, it doesnt exactly matter what the enemy is, like whether its a Goomba. Theyre all Enemies, so Mario is able to squash any of them
rich adder
#

the major benefit is you're not relying on inheritance which can be very limiting

twilit ocean
polar dust
#

you could have List<IEnemy> and thats just a collection of various enemies.
otherwise you might need List<Goomba> List<Koopa> if you needed to know all the enemies in the level

rich adder
#

@twilit ocean you will lean more with all the resources out there, but just a quick example why some times "inheritance" doesnt work and interfaces are preferred ```cs
public class Character{
public virtual void TakeDamage(int amount){
Debug.Log($"Character took {amount} damage.");
}
}

public class Player : Character{
public override void TakeDamage(int amount){
Debug.Log($"Player took {amount} damage.");
}
}```

now what if we want a non-character to Take Damage?
we certainly wouldn't want a Box to inehrit Character

so we do interfaces instead


public interface IDamage {
void TakeDamage(int amount);
}

public class Player, IDamage{
    publicvoid TakeDamage(int amount){
        Debug.Log($"Player took {amount} damage.");
    }
}

public class BoxObstacle , IDamage{
    public void TakeDamage(int amount){
        Debug.Log($"Box took {amount} damage.");
    }
}```
keen summit
#

guys i have a question about lobbies, im creating this lobby system and whenever i try to join a lobby i get a null reference because my lobby code is null, is this because the lobby code is hidden outside of the lobby?

rugged beacon
#

i mean you can just change the name from character to idamageable right, they are the same,
the main different that with class inheritance you can only have one

rich adder
#

interfaces you can have as many as you need

twilit ocean
rich adder
#

public class Player : MonoBehavior, IHurt, ISprint, ISaveStats
etc.

twilit ocean
#

Don't interfaces aim to minimize the amount of script files created and aggregate? Why would I create a new interface for so many different interactions?

wintry quarry
#

the aim is to reduce duplicated code for dealing with similar objects

rich adder
twilit ocean
rich adder
#

the requirement for interface is, whatever methods/properties are inside the class that Implements this Interface has to have defined all those methods

#

@twilit ocean if you had

interface IHealth{
void Damage(int amount);
void Move();
void Jump();
}```
```cs
public class Box : Monobehaviour , IHealth {
private int health = 100;
public void Jump()  { }  // why
public void Move()  { }  // why -- we are forced to implement them because they are in IHealth
public void Damage(int amount) {
health -= amount ;
}

why would you want this ?

#

you wont be able to just "ignore" the other things in the interface, you are forced to implement them, normally called a "forced contract"

twilit ocean
#

Thought maybe we oculd somehow fetch only the specific needed method from a list that would be the interface and apply it to the desired class that needs it.

rich adder
#

the interface itself cannot and doesn't store anything

#

all the implementations are inside whatever class has this interface

#

the interface says " you should have Hurt method as a requirement, how you run and what you do inside of it is up to you in the class"

twilit ocean
#

Annd I'm confused again UnityChanThink

#

Lemme read all the guide all the way before I start yapping more

rich adder
worthy gale
#

Howdy, I need help properly incorporating jumping into a 3D platformer, I have jump working, but Im struggling to attach the proper flags to trigger the jump->airborne->land sequence

worthy gale
#

My code is a mess, forgive me in advance, Ive been stitching it back and forth for a while:

rich adder
#

!code

radiant voidBOT
worthy gale
rich adder
#

what is the exact question ? are you trying to do animation / jump through code ?

#

whats happening vs what you expect to happen

worthy gale
#

Ok heres my deal: I want to add proper jumping, my character can currently jump, but no animation plays. I have the logic of the animator mostly settled, my goal is to have the character jump, be able to smoothly jump on landing, and also enter a fall state if walking off a ledge thats big enough/falling, I have Landed/isJumping/isFalling bools for it, but I feel like im going in circles because I cant seem to nail it down,

#

my character currently freezes in the 'spiderman' midair pose until I start walking backwards/rotate when still, and break the pose back to the idle selection

rich adder
rocky canyon
#

i also would think blendtree's would help here

#

also not sure if slapping all that stuff on a any state transition will work out exactly how u wish

#

might want to consider re-doing the flow of that animator

rich adder
#

the only time I've used anystate tbh is like a Hurt event or something

worthy gale
rocky canyon
worthy gale
#

I decided to use a asset store dummy with advanced animations to try and make it look good but now this is proving to be a challenge, given this is the first time Im using unity

rich adder
devout flint
#

i know that with particle systems you can change the mode to sprites so you can select a random image out of a set list of sprites, but is there a way to select a set image based on an animator’s parameter from a list of sprites?

rocky canyon
#

yea?

devout flint
#

how then lol

worthy gale
#

the animations arent part of any grade req, so in your vetted opinion, should I focus on making the three levels we were asked, that have moving platforms/rudimentary puzzles, and just leave the jump as a jump with no animation?

rocky canyon
#

same way u'd set an animator parameter..

#

only u read it..

#

then use that to change out the image

rich adder
#

if you mean picking a specific image in a slicesheet, I know this is easier done in visual effect graph

devout flint
#

o shoot this is the scripting channel wrong spot lol

worthy gale
#

we basically have to make a 3 level platformer, with enemies/platforms, and a basic UI, and movement, and a start screen, basically a baby intro to unity

devout flint
#

i meant within the particle system itself - not any scripts >.>

#

ill ask elsewhere

rocky canyon
#

unless "visuals" is an aspect of the grading

rocky canyon
marble hemlock
#

Does anyone have any suggestions for how to do a status effect system?

Rn im thinking about using scriptable objects in a list but is it possible to hold an equation or function in a scriptable object to trigger when needed?

rocky canyon
#

good luck tho, might see u back here to script it 😄

devout flint
#

cant use scripts for this - vrchat stuff

rocky canyon
#

ohh oka

devout flint
#

asking the vrc server instead lol

rocky canyon
worthy gale
#

I went really overkill with the animation logic to showcase my enthusiasm

rocky canyon
#

nothing wrong with that tho

#

if u were having fun.. roll with it

rich adder
#

SOs included

worthy gale
#

this is worth like 30% of our final grade and I wasn't sure how best to demonstrate my interest, so I stapled a complicated-ish animator for a dummy off the asset store

rocky canyon
#

i would branch off of running, walking, and idle for jumping and landing and transition to anystate to return

worthy gale
#

the class assets we were given dont even have turning, jumping, or backwards walking animations, so the bar is quite low but Im not sure if thats for a base passing grade or a full 100%

#

basic movement, basic UI and HP, enemies that hurt you, obstacles and moving platforms, basic basic puzzle jumps, and 3 total levels

rich adder
#

what is assignment for ? isn't this overkill lol

worthy gale
#

Its a basic intro to game dev

marble hemlock
worthy gale
#

I got carried away with my character animations and I wanted to make it look real good but now its becoming an issue

marble hemlock
#

I've never tried using them for anything more than basic data

#

Strings, int, sprites, etc.

rich adder
#

also this is why you should keep it in 1 channel..

grand snow
#

😠

rich adder
#

does it need to do jumping all that? make it a walking sim where you can interct with a button or something

worthy gale
#

Assuming I add clean sounds, and make the levels visually cool and traversable, and tweak my physics to be comfortable to play, think its worth 100%?

#

Yeah it needs to have jumping

#

but screw it, I removed it and simplified it, no jumping animation is a small sacrifice

rich adder
#

for an intro class you'd probably get 100 even if it was pong lol

#

aesthetic is good, but a good understanding of the basics systems is probably more than enough

worthy gale
#

it needs to be 3D, basic platformer, 3rd person

#

Im debating attaching cinemachine once Im done the meat to give clean camera transitions

#

looks simple enough

rich adder
#

yes It was more of an example i don't mean it literal

worthy gale
#

just like a pan from facing forward, to the 3rd person, and yeah lolol nw I gotcha, Im just pressed because of how open ended it is for an assignment

rich adder
#

at least I would simplify the animator a bit

#

well its usually based on what you learned in class, if you included all those concepts in it , you're pretty much scoring 100

#

if you're doing interactions, would probably score some decent points

worthy gale
#

we learned how to move with delta time, basic camera attachment and basic cinemachine stuff, and basic interactions

#

I plan to have a button over which you walk, and it causes platforms to drop down

#

for a level

rich adder
#

ya that would probably be simpler

worthy gale
#

he demonstrated some more fancier stuff but it was moreso exploratory and less assignment related because the example which he showed us in class of a finished sample game which scored full points, was pretty simple

rich adder
#

yes cause teachers got like 5-10 min a student to glance over usually

worthy gale
#

but Im still sketched so I plan to put as much possible polish before submission in 5 days

#

Im 100% finishing by then, the hard part of character controls and animation is done, levels will be much easier and UI and start screen should be super easy too given Im not doing anything crazy

#

with leftover time Il toy around with extra additions

azure glade
#

hey, can any admin look into the course Junior Programmer from Unity Learn? the videos are downloading very slow, and remain stuck if I leave them to download ahead. I don't have any networking issue, my down speed is 200

astral basin
#

!help

sly hollowBOT
#
​No Category:
  help Shows this message

Type !help command for more info on a command.
You can also type !help category for more info on a category.
#
​No Category:
  help Shows this message

Type !help command for more info on a command.
You can also type !help category for more info on a category.
radiant voidBOT
# astral basin !help
<:emote:1416393040439939103> Available commands

Use !help <command> to get more information

!collab
!code
!logs
!bug
!screenshots
!cs
!vc
!dots
!vrchat
!vscode
!blender
!vs
!forums
!learn
!install

astral basin
#

!code

radiant voidBOT
astral basin
#
    public Slider musicSlider;
    public Slider sfxSlider;

    public Dropdown qualityDropdown;
    public static int qualityLevel = 5;
    public static float sfxVolume = 0f;
    public static float musicVolume = 0f;
    public static bool postProcessing = true;

    public void setQualityLevel()
    {
        QualitySettings.SetQualityLevel(qualityDropdown.value);

        qualityLevel = qualityDropdown.value;
        PlayerPrefs.SetInt("qualityLevel", qualityLevel);
    }
    public void setMusicVolume()
    {
        musicMixer.SetFloat("MyExposedParam", musicSlider.value);

        musicVolume = musicSlider.value;
        PlayerPrefs.SetFloat("musicVolume", musicVolume);
    }
    public void setSfxVolume()
    {
        sfxMixer.SetFloat("MyExposedParam", sfxSlider.value);

        sfxVolume = sfxSlider.value;
        PlayerPrefs.SetFloat("sfxVolume", sfxVolume);
    }
    public void setPostProcessing()
    {
        postProcessing = !postProcessing;
        UniversalAdditionalCameraData cameraData = cam.GetComponent<UniversalAdditionalCameraData>();
        if (cameraData != null)
        {
            cameraData.renderPostProcessing = postProcessing;
        }
    }
    void Start()
    {
        if(PlayerPrefs.HasKey("qualityLevel") == false)
        {
            PlayerPrefs.SetInt("qualityLevel", qualityLevel);
        }
        if(PlayerPrefs.HasKey("musicVolume") == false)
        {
            PlayerPrefs.SetFloat("musicVolume", musicVolume);
        }
        if(PlayerPrefs.HasKey("sfxVolume") == false)
        {
            PlayerPrefs.SetFloat("sfxVolume", sfxVolume);
        }
        
        qualityLevel = PlayerPrefs.GetInt("qualityLevel");
        musicVolume = PlayerPrefs.GetFloat("musicVolume");
        sfxVolume = PlayerPrefs.GetFloat("sfxVolume");

        qualityDropdown.value = qualityLevel;
        musicSlider.value = musicVolume;
        sfxSlider.value = sfxVolume;
    }
}

this is my options menu, it doesnt save btwn scns

#

it saves from the main menu to the level, but when i set it in the level and go back to the main menu it doesnt change at teh main menu

wintry quarry
astral basin
#

this script is on the optionsMenu gameobject, this object exists once in every scene, i handle the menu by clicking a button to open it, then the user is shown a dropdown, and some sliders to change the settings

wintry quarry
astral basin
#

no

#

would a video showing the problem help you visualise it

wintry quarry
#

have you done any debugging to make sure the code is actually running?

#

Also - is there a good reason for these variables to be static?

astral basin
astral basin
wintry quarry
astral basin
#

everything saves except at the end where i go back to the main menu scene, where it doesnt save the changed i made in level0 scene

wintry quarry
#

add Debug.Log statements in all the places. I know for a fact there will be at least some unintentional things happening in this code

wintry quarry
#

For example, assuming setQualityLevel() is hooked up as the value changed listener on the dorpdown (is that correct)? Then calling qualityDropdown.value = qualityLevel; in Start is actually going to cause setQualityLevel() to run too

astral basin
#

let me share what i found weird mayube you can figure it out

astral basin
#

why does it call setqualitylevel

#

i dont understand

wintry quarry
#

because the value changes

astral basin
#

ohhhh

#

so how do i override that

wintry quarry
#

Another issue with your code is you basically have 3 sources of truth

#

you have:

  • The dropdown.value value
  • Your static variable
  • The PlayerPrefs variable
#

and at different tiems in your code you treat each of them as the source of truth

astral basin
wintry quarry
#

For example here:
QualitySettings.SetQualityLevel(qualityDropdown.value); You use the dropdown value as the source of truth
Here:
qualityLevel = PlayerPrefs.GetInt("qualityLevel"); PlayerPrefs is the source of truth
and here:
PlayerPrefs.SetInt("qualityLevel", qualityLevel); the static var is the source of truth

wintry quarry
#

you only put things in Update that you want to happen every frame

grand snow
#

Doesnt TMP_Dropdown replace Dropdown now?

wintry quarry
#

yes

#

but their code is using the legacy one

astral basin
wintry quarry
#

the same principles apply to either

wintry quarry
wintry quarry
astral basin
#

as such?

#

oh i made a function for no reason but same functionality right

wintry quarry
#

there's no need for you to make an extra function yeah

#

but yes this is correct

astral basin
#

yeah my bad

#

ok let me try that

wintry quarry
#

it might not be the issue, and might not be the only issue

#

that's just what jumped out at me

#

I still recommend debugging

astral basin
#

yes ok thats one thing fixed

#

one other thing i noticed

#

i put a debuglog in the start function

#

but instead of being called at the start of the scene

#

it gets called only after i open the options menu

#

should i move the script to a different object thats always enabled?

#

its weird beacuse i read that the start function works regardless of wether the object is enabled or not

astral basin
#

so its the other way around

astral basin
#

i see

#

but when i set start to awake

#

the problem still persisted

#

it doesnt matter this doesnt cause any issues thanks

#

i figured it out thanks dlich and huge thanks to you praetorblue

astral basin
marble hemlock
#

I can't test it right now but its been haunting me the entire shift because my game kinda heavily uses status effects as a mechanic. Not a core mechanic but it influences the game pretty majorly.

#

Trying to look up tutorials but everyone has their own thing that perhaps im too uneducated for my brain to properly process.

eternal needle
#

You need to define what a status effect is. What can it do in your game, when does it act?
Thats how you start building a system around it

spice heart
#

Hello (I'm a beginner in programming) My question is in what contexts is time.deltatime used? I've seen that they say it works with certain things and that it improves performance, but it's still not clear to me what I should use it for.

magic slate
#

Hi

spice heart
#

hi yo know about that?

cosmic dagger
teal viper
dreamy marsh
#

Hey guys i am trying to make a 2d endless side runner game and i had a question regarding my enemy spawn script

The above 2 scrensshots show how the enemies are being spawned and in theory i think the enemies should get spawned quickly so that it is challenging

#

but that's not the case and the eemy spawn is taking too long

thorn holly
#

Oh wait spawning slower?

dreamy marsh
#

so i have 3-4 enemies in the beginning that have a spawn speed of 2f so that i can give the player a tutorial

#

after that the spawn speed should go down to 0.2 which i dont know if it is happening

thorn holly
#

!code

radiant voidBOT
thorn holly
#

Can you post the full script

#

And formatted correctly

dreamy marsh
#

plus i want that the enemy spawn to be challenging - the next enemy should already be on the screen while the player is jumping over the current one bu that is not the case - there is only 1 enemy on the screen at a time

#

sure

#

done

thorn holly
sour fulcrum
dreamy marsh
#

yes

dreamy marsh
dreamy marsh
thorn holly
#

Ah I see the problem

#

At the top of EnemySpawnTimer you’re waiting for 3 seconds

#

Not sure why

sour fulcrum
dreamy marsh
#

but i still dont understand why is there just 1 enemy on the screen at a time when i theory, considering the enmy spawn rate is so quick - there should be atleast couple of enemies lined up already

thorn holly
#

Because you have that wait for seconds for 3 secs at the top

thorn holly
#

The issue is after the first few enemies spawn

dreamy marsh
sour fulcrum
dreamy marsh
sour fulcrum
#

yield return new WaitForSeconds(3f);

dreamy marsh
#

oh shit i see

thorn holly
dreamy marsh
#

omg yes how did i not see that

#

okay let me try it out

sour fulcrum
#

In the future if you want to solve this problem independently I would

  1. Add additional debug logs in all related steps that this code involves, potentially with more detailed information inside of them
  2. Think about the problem more methodically. The issue is enemies are taking too long to spawn. What code here could cause that? What code here makes things wait? Narrow down the amount of suspects you need to look at
dreamy marsh
#

okay perfect - thankyou so much guys !!

sour fulcrum
dreamy marsh
#

sure

wind brook
#

trying to do something I feel like should be very simple, want to change the game speed when animation state of player is a certain state but it's just not working, the if statement doesn't trigger. I think it's because I'm getting the name wrong, but I've tried every possible permutation I've found and nothing seems to work

thorn holly
#

Also

#

!code

radiant voidBOT
wind brook
thorn holly
sour fulcrum
# dreamy marsh sure

So in your EnemySpawnTimer() function you have a lot of repetitive code going on here, I point this out because it's a good example of where you can think about what here is shared between all these outcomes and what isn't

When we look at what that loop is actually doing logically, we can actually reduce that loop down to

        if (initialSpawn == false)
        {
            Enemies[] initialEnemies = new Enemies[] //This could even be a array or list you configure in editor!
            {
                Enemies[0], Enemies[0], Enemies[1], Enemies[2];
            }

            foreach (Enemies enemy in initialEnemies)
            {
                Instantiate(enemy, transform.position, transform.rotation);
                yield return new WaitForSeconds(2f);
            }

            initialSpawn = true;
        }

Furthermore, you might even want to make a little function that handles the creation of all enemies, so that way you know it's all happening the same way, like. This is just an example though 😄

    private IEnumerator SpawnEnemy(int enemyIndex, float waitTime)
    {
        yield return new WaitForSeconds(waitTime)
        Instantiate(Enemies[enemyIndex], transform.position, transform.rotation);
    }
thorn holly
dreamy marsh
fast heron
dreamy marsh
fast heron
#

free assets ❤️

dreamy marsh
fast heron
#

one day I may have money for assets, but today is not that day 😛

untold shore
#

Hey - currently having a problem. Its less code, more of a general idea, but I don't know how to apply it.
Currently, I have code of npcs/ai that see the player and attack them; however, i want the enemy to be able to attack other npcs. Right now, Im having issues of thinking of how the ai enemy will see multiple groups of enemies and only attack the closest one. Im guessing it will do something with a collider, but Im not familiar enough to think about how to properly implement it.
Here is the state machine code that this will go into, particularly the function "Chasing": https://paste.ofcode.org/Cb9vQ3piFmzi52JNpVrPDx
Is there any way more experienced coders would go about this? Would they find the transform of all the npcs, then find the closest one relative to the current enemies transform? You dont have to write the code, just say general terms like "oh find the transform" or smth. Sorry, I know this is difficult to answer, so I apologize if this is confusing. If you respond, please @ me. Thanks!

thorn holly
#

Raycasts would also be needed if for example walls block line of sight

wintry quarry
untold shore
#

Also good to see you here, you helped a ton on a previous project of mine!

wintry quarry
untold shore
#

Gotcha, Ill try it out. Thank you!

sour fulcrum
# dreamy marsh great, i will apply both these things, thankyou!

No worries! One last thing is a tiny nitpick but is easy to get in the habit of and will really help the readability of your code,

It's worth making slight adjustments to what you name things in order for it to be more clear what it does do and also help you decide what it should do.

some examples of this

Enemies might be better as enemyTypes, enemyPrefabs or typesOfEnemies etc. Just Enemies could also refer to enemies that have been spawned or etc.

initialSpawn would be better as hasInitiallySpawned, hasInitiallySpawnedEnemies or initialSpawningComplete. Specifying the tense in the naming helps ensure you or anyone else understands what this bool specifically represents.

EnemySpawnTimer() as it's currently named to be implies the sole job of this function is to wait but currently this function is largely responsible for the actual spawning of the enemies. If your happy with this function doing the job of waiting and spawning you may want to rename it to something like SpawnEnemiesWithDelay(). It can also be worth considering that maybe you want to split this function up into smaller separate functions with specific names and tasks like EnemySpawnCooldown(), SpawnInitialEnemies() and SpawnEnemy().

You by no means have to act on any of this advice and it's certainly not critical but it's worth thinking about when your in the mood for it 😄

dreamy marsh
#

no, this is great advice - i will definitely look into it + make a note of it next time i am coding. I appreciate you taking out the time

bright zodiac
untold shore
# wintry quarry I would give all of them a "threat" level and just find the highest threat level...

Hey - sorry to bother you again with this. Currently Im having a little trouble with the finding the highest threat level from the list of nearest npcs. Here is how I was thinking of going about it (most likely unoptimized, but slowly getting through it:

 foreach (GameObject enemy in enemiesList)
{       
  if(sphereCollider.bounds.Contains(enemy.transform.eulerAngles))
  {
    currentEnemy = //enemy with highest level threatlevel of enemies in sphere collider
   }
}

Where would I go from there though? If i set currentEnemy = enemy in list with highest threat level, it'll go to the one with the highest threat level even if they are not inside the sphere collider. Is there another method to find a variable from a list in certain bounds?
(Please @ me if you respond. Thanks!)

marble hemlock
#

does anyone know why there seems to be some sort of delay with the testing for clicking e?

#

like it doesnt seem to be registering all the times i press it.

#

invisible cooldown...?

teal viper
marble hemlock
#

ahh i see, thank you

#

i should prob put a bool on like trigger enter and then tell it to check in update

ripe shard
tender mirage
#

Why are my rows not even, and why is there an extra 10th colum or even worse as i increase the rows it becomes extra wide

private int LevelRows = 4;
private int LevelColums = 9;

//-------------------------------------

//Start Pos
Vector3 SpawnPos = StartPos;

for (int i = 0; i < LevelColums * LevelRows; i += 1)
{
  
    //Spawn Target
    GameObject ClonedTarget = GameObject.Instantiate(TargetObject, gameObject.transform);

    //Apply offset
    ClonedTarget.transform.position = SpawnPos;




    if (SpawnPos.x < LevelRows)
    {
        SpawnPos.x += 1;
    }
    else
    {
        SpawnPos.x = StartPos.x;

        SpawnPos.y -= 0.25f;
    }



}
grand snow
patent wedge
#

is there a transform equivalent of Rigidbody.GetPointVelocity? as seemingly the velocity is the forces applied to it rather then the current speed.

tender mirage
#

tiles go down by -0.25f;

keen dew
#

-5 to 4 is 10 in total

#

as is 0 to 9

#

you also have rows and columns mixed up

rocky canyon
# patent wedge is there a transform equivalent of Rigidbody.GetPointVelocity? as seemingly the ...

it'd give the velocity of a specific point on the rigidbody which includes both linear and angular motion..
(say u had a cube moving forward and spinning around its pivot.. if u used a corner of that cube you'd get both that forward velocity.. but you'd also get the angular velocity of that point, making that number greater than its normal speed you'd call it)

you might could just use rb.linearVelocity.magnitude

or u can just make ur own speed calculations

    Vector3 lastPos;
    Vector3 velocity;

    void Start() => lastPos = transform.position;

    void Update()
    {
        velocity = (transform.position - lastPos) / Time.deltaTime;
        lastPos = transform.position;
    }```
keen dew
# tender mirage Why are my rows not even, and why is there an extra 10th colum or even worse as ...

That code only works by accident because the row count happens to be about half of the column count. The "standard" way to do this would be:

int LevelRows = 4;
int LevelColums = 9;

for (int x = 0; x < LevelColums; x++)
{
    for (int y = 0; y < LevelRows; y++) 
    {
        GameObject ClonedTarget = GameObject.Instantiate(TargetObject, gameObject.transform);
        ClonedTarget.transform.position = StartPos + new Vector3(x, y * -0.25f, 0);
    }
}  
tender mirage
#

thank you so much

tender mirage
#

since it was being annoying.

keen dew
#

The main thing is that don't start counting from the StartPos coordinates because they aren't really related to how many rows/columns there are in total . If the x position is -5 and total columns is 9, if you count from -5 to 9 you'll get 14 or 15

rocky canyon
#

just remember 0 is the first loop
so ur row and col count would be (desired Amount - 1)

patent wedge
rocky canyon
#

well velocity is the speed + direction
magnitude is just the speed

#

"Give me how fast this thing is moving, regardless of direction."

#

so if u were moving backwards at 10m/s
ur velocity would be -10 however the magnitude of that velocity would just be 10

patent wedge
# rocky canyon "Give me how fast this thing is moving, regardless of direction."

ok when i meant speed i still meant a vector3, because i have a floating character controller that follows moving platforms using

rb.linearVelocity += hit.rigidbody.GetPointVelocity(hit.point);
```which works fine for kinematic moving platforms but if a have a rigidbody any time it changes direction its velocity at that point increases more than it should, it seemingly gets the force rather than the actual velocity at that point.
rocky canyon
# patent wedge ok when i meant speed i still meant a vector3, because i have a floating charact...

ahh, ya you'll get higher values like that when you get forces or impulses..
it'll spike b/c it hasnt had time to settle yet (using friction, dampening etc)

if u want a smoothed velocity you should probably just track ur own velocity over time instead of using unity's raw physics output

(like that code example i sent up above)

        (currentPosition - lastPosition) / Time.fixedDeltaTime;
        lastPosition = currentPosition;```
#

^ if ur calculating it urself and using the Transform it'd work regardless of if its a rigidbody, kinematic, or just a transform

#

that would give u a Vector3 with each axis showing its speed

patent wedge
rocky canyon
#

(2, 0, 1) would be moving 2 units/ second to the right and 1 unit/second forward

rocky canyon
#

is that the intention there?

#

rb.linearVelocity += a is the same thing as rb.linearVelocity = rb.linearVelocity + a

#

❔ let me ask this.. cuz im a bit confused..
"whats the purpose of this mechanic"
like.. whats the game-plan..

#

i think that will help clear it up

patent wedge
rocky canyon
#

ohhh

rocky canyon
#
        // you could optionally try to add some smoothing in the mix to avoid those big spikes
        pointVelocity = Vector3.Lerp(rb.linearVelocity, pointVelocity, 1f - smoothing);

        // Apply platform velocity to player (overwrites velocity, prevents explosion)
        rb.linearVelocity = pointVelocity;```
patent wedge
rocky canyon
#

you could *grab it's velocity (without the platform) and + the platform velocity on top

#

that would keep w/e momentum and movement u already have going on

#

platforms are tricky..
(pretty simple to get them to work w/ a player that doesn't move)
but once u start walking and jumping on them.. it gets complicated

patent wedge
rocky canyon
#
// players existing velocity
Vector3 currentVel = rb.linearVelocity;

// platform contribution at teh contact point
Vector3 offset = hit.point - platformRigidbody.worldCenterOfMass;
Vector3 platformVel = platformRigidbody.linearVelocity + Vector3.Cross(platformRigidbody.angularVelocity, offset);

// Combine them
rb.linearVelocity = currentVel + platformVel;```
#

u can also make the rotation affect that platform vel u would add to the player ^

#

i'd have to test myself for anything more than this tho..
im just assuming it'd work but u know how assumptions go..
let me fire up my editor and see if that ^ works out on a platform..

(been putting off platforms myself for a while now)

patent wedge
rocky canyon
#

ahh fudge.. sorry thats about all i got

#

it is super early still tho.. so my brains a bit foggy still

#

could u share ur code?

patent wedge
rocky canyon
#

the platform + player movement.. the relevant bits?

rocky canyon
#

maybe u could smooth just the direction changes somehow..

#

altho im not 💯 sure how

patent wedge
real thunder
#

At this point I almost gave up on this approach to make a rigidbody fps controller work, but before trying next one I would appreciate if anyone can figure out what's wrong with what I got so far, specifically:
Why is my camera stuttering only while I am strafing and turning camera around? Just strafing is smooth (rigidbody interpolation is on), just looking around while standing is smooth (also there is no friction on anything)

camera (nothing crazy, worked flawlessly with character controller basic movement, assume smoothing is 1)

void LateUpdate()
    {
        if (!isCameraLocked)
        {
            mouseinput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
            mouseinput = Vector2.Scale(mouseinput, new Vector2(sensitivity, sensitivity));

            smoothdelta.x = Mathf.Lerp(smoothdelta.x, mouseinput.x, 1f / smoothing);
            smoothdelta.y = Mathf.Lerp(smoothdelta.y, mouseinput.y, 1f / smoothing);

            mouselook.x += smoothdelta.x;
            if ((mouselook.y + smoothdelta.y) > 90f)
            {
                smoothdelta.y = 90 - mouselook.y;
                mouselook.y = 90;
            }
            else if ((mouselook.y + smoothdelta.y) < -90f)
            {
                smoothdelta.y = - (90 + mouselook.y);
                mouselook.y = -90;
            }
            else
            {
                mouselook.y = mouselook.y + smoothdelta.y;
            }
            playerPosition.localRotation = Quaternion.AngleAxis(mouselook.x, playerPosition.up);
            cameraPosition.localRotation = Quaternion.AngleAxis(-mouselook.y, Vector3.right);
        }
    }
#

and rigidbody (shortnd)

xInput = Input.GetAxisRaw("Horizontal");
yInput = Input.GetAxisRaw("Vertical");
desiredMovementVectorNormalized = transform.TransformDirection(xInput, 0, yInput);
desiredMovementVectorNormalized = desiredMovementVectorNormalized.normalized;
Vector3 targetVelocity = desiredMovementVectorNormalized * MaxSpeed;//Set a target velocity
Vector3 velocityChange = targetVelocity - movementVector;//Find the change of velocity needed to reach target
Vector3 acceleration = velocityChange / Time.fixedDeltaTime;//Convert to acceleration, which is change of velocity over time
acceleration = Vector3.ClampMagnitude(acceleration, MaxAcceleration);//Clamp it to maximum acceleration magnitude
body.AddForce(acceleration, ForceMode.Acceleration); 
#

I wanted to use physics but keep perfectly controlled speed

rocky canyon
#

b/c ur player is moving with physics Fixedupdate() and your camera (that i assume is a child of the rigidbody) is being modified in Update()
these two functions don't run at teh same rate...
so u basically get sync issues

real thunder
#

player get movement forces at fixed update but turns with the camera at update through transform, would that still cause desync?

rocky canyon
#

if ur using a rigidbody doesn't matter where u call the code.. it gets applied in the FixedUpdate()

#

but the Camera is gonna update in Update() which happens much more often

real thunder
#

oh well...

rocky canyon
#

soo thats why u have that happen

#

unity learn has a tutorial that shows how they solve the camera jitter but i can't find it off-hand

real thunder
#

does charactercontroller move at update btw?

rocky canyon
#

yes

real thunder
#

now it making so much sense

rocky canyon
#

CC uses Update() b/c its a Faux Physics object

#

doesn't actually use physics

real thunder
#

that answers my "why" and I will find "how", thanks alot

rocky canyon
rocky canyon
#

the most common fix for it tho is

  • Use LateUpdate(); for the camera logic
  • Use Interpolation/smoothing for Rigidbody

also you can use Cinemachine (it has settings for changing how the camera logic works... you can set it to Update(), LateUpdate() or SmartUpdate <-- where it does magic and figures out things on its own..

#

Cinemachine is really useful for later on in ur game too, like to change cameras, transitions to cutscenes, camera shake, all that good stuff built in

tender mirage
#

i'll try to repeatedly write it until i remember it

keen dew
#

It'd be more useful to understand what it does instead of just memorizing it

real thunder
rocky canyon
#

you do turn ur character in Update() ircc
edit: or maybe u don't im thinkin of someone elses code.. but either way thats why i mentioned LateUpdate().. if it doesn't help
I still linked that Discussion's link that has multiple solutions

real thunder
#

🤔

shell sorrel
#

you want late update because without it its possible the camera runs its update, then something the camera is tracking updates after throwing it off by a frame and making it always play catch up

real thunder
#

I mean I know I want lateupdate, I missed the part saying I meant to detach camera for it to work

#

anyway that should work ima stitch something working

shell sorrel
#

what do you mean by detach the camera?

#

was it a child of your character before?

real thunder
#

yep...

real thunder
#

I will have to spend some time thinking on details on WHY does it work

edgy sinew
edgy sinew
stuck palm
#

does unity have an object pooling system or will I have to make that myself?

grand snow
stuck palm
#

seems easy enough, I thought I'd have to start from scratch but this looks good

#

cus my game spawns a lot of hitsparks so this will alleviate it a bit

rocky rock
#

I got a character composed of different layered sprites and I want to set the whole composition transparent but going through each sprite and setting the alpha means that parts that would be hidden now become visible
any tips on how to fix this? I was thinking I should merge all the sprites together into one, but that doesn't seem so straightfoward to do

wintry quarry
rocky rock
#

not possible with all parts combinations

wintry quarry
#

what's the end goal here?

rich adder
wintry quarry
#

I think thye're basically having a blending issue. They want the fully composite image to be alpha faded but instead when you set the alpha of individual renderers you get the thing where you see all the sprites under the other sprites

rocky rock
#

having a character display with different visual parts (e.g. clothing pieces, face, hair, body, etc.) then being able to manipulate that composition with alpha masks, flipping, etc.

rich adder
#

ahhh this is like a modular character

slender nymph
#

sprite masks should help with that i would think

wintry quarry
#

one option is rendering to a RenderTexture
Another option is to use a custom shader

rocky rock
#

sprite masks might work, I think..? like, each layer applies a mask to all layers behind it? might get heavy if I got a lot of layers? 🤔

rendertexture sounds promising but I've only ever used it with Camera.targetTexture. Is there a way to directly "write" a sprite to it?

never used shaders before so no idea where I'd start on that one

thorn holly
#

When would one want to use physics.overlap box over a collider with isTrigger enabled?

cosmic dagger
wintry quarry
thorn holly
cosmic dagger
#

If you want to check what is inside of a box at that moment in time (immediate), then you'd use an OverlapBox check . . .

wintry quarry
thorn holly
#

I’d imagine being forced to use a rigidbody is pretty expensive even if it’s kinematic/statoc

thorn holly
wintry quarry
#

performance is almost never a concern for these decisions unless you are dealing with very large numbers of objects

thorn holly
#

Alr good to know

#

Thanks

hot wadi
#

Do u guys usually use a single CoroutineHandler to manage all the coroutines?

wintry quarry
#

I would only do something like that if I have some special requirements

eternal needle
hot wadi
# wintry quarry No. To what end?

I see some projects use that as a to provide helper functions that help start coroutines, ideally from other singletons
I'm not sure if that is a thing in common. Most I have seen only about few dozen lines of code

wintry quarry
#

it could be useful to you if you are running into that issue

#

otherwise it doesn't add much value

astral basin
#

hi, im trying to add ads to my game and it seems to work, but when i try to build the game to test it i get this

ivory bobcat
astral basin
#

ok sorry i sent here cuz im also a begginer

real scroll
#

Is this the right place to ask about Unity Learning problems for beginners?

cosmic dagger
#

Also, check out the other channels if your problem fits a specific topic . . .

real scroll
#

So I am learning how to build the "Tanks" game. And when I go to my prefab>levels> and selct the levels and load it, both the preview, and the loaded level, are all pink, and do not show me the assets, just their wireframe location

#

Should I snip a picture for reference?

slender nymph
#

that doesn't sound like a code issue

cosmic dagger
hot wadi
real scroll
#

So I went to Window>Rendering>Render PipelineConvertor

And that worked. I can see my beautiful level now...
My beautiful prefab learning tutorial level that is

hallow acorn
#

hey i made this marching cubes algorithm and i also tried interpolating it but i always get these weird artifacts idk how well you can see the in the image. i dont know how to fix it or whats wrong but its very annoying

these are the most important pieces of my code:
https://paste.mod.gg/lueynfznykew/0

rancid surge
#

Hey! Quick question
I’m setting up my Unity project with Git for a university assignment, and I’m a bit confused about the .gitignore.

My Git repo has a subfolder for the Unity project (for example: repo/Project1/).
Should the .gitignore go in the main repo folder or inside the Unity project folder?

I saw this one from GitHub:
👉 https://github.com/github/gitignore/blob/main/Unity.gitignore

Can I just use it as is, or do I need to change anything for this setup?

GitHub

A collection of useful .gitignore templates. Contribute to github/gitignore development by creating an account on GitHub.

hallow acorn
rancid surge
#

Thank you I will try it and I had some issues the first time

real thunder
rancid surge
hallow acorn
slender nymph
rancid surge
rancid surge
keen dew
#

Show another screenshot but the git tab open

hallow acorn
keen dew
#

Show the graph at the bottom of the page

rancid surge
keen dew
# rancid surge

In this one click the X in the orange box so that it doesn't cover the top

hot wadi
#

Git is definitely ignoring the correct files

slender nymph
#

ideally change the view mode in the git view to organize the changes by folder then it will be more obvious where these changes are coming from and if they are from folders that should be ignored

rancid surge
#

I got a GitLab repo from my professor (it was empty — no README or anything).
I cloned it, and then I created my Unity project directly inside that repo folder.

After making a few quick changes in Unity, I opened the repo in VS Code to commit.
Then I downloaded the Unity .gitignore from this link 👉 https://github.com/github/gitignore/blob/main/Unity.gitignore
and placed it in the repo.

But even after adding the .gitignore, Git still shows around 10k changes (mostly Library, Temp etc.), which is super confusing 😅
Did I maybe put the .gitignore in the wrong place, or should I have set it up before creating the Unity project?

GitHub

A collection of useful .gitignore templates. Contribute to github/gitignore development by creating an account on GitHub.

#

oh but now it says only 96 changes maybe I just needed to wait 🥲

umbral hound
#

Can anyone help me? My camera position does not reset when I stop moving, and yes, I set m_OriginalCameraPosition to m_Camera.localPosition on the first frame

public void Bob(float magnitude, float speed)
{
    if (magnitude > 0f && (PlayerInput.Instance.Horizontal() != 0f || PlayerInput.Instance.Vertical() != 0f))
    {
        m_Camera.localPosition = DOHeadBob(magnitude + speed);
    }
    else
    {
        m_Camera.localPosition = Vector3.Lerp(m_Camera.localPosition, m_OriginalCameraPosition, 0.2f);
    }
    m_CurrentCameraPosition = m_Camera.localPosition;
}
umbral hound
slender nymph
#

show more context

umbral hound
#

Okay

ivory bobcat
umbral hound
slender nymph
#

if you're going to use pastebin, at least have the courtesy to select the correct language so there's syntax highlighting.
anyway, where is Bob being called

hot wadi
ivory bobcat
#

My camera position does not reset when I stop moving
Assuming you're referring to else not ever occurring

umbral hound
umbral hound
#
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class Player : ODSingleton<Player>
{
    [Header("References")]
    [SerializeField] private CharacterController m_CharacterController;
    [SerializeField] private Transform m_CameraContainer;

    [Space]
    [Header("Extensions")]
    public PlayerMovement m_PlayerMovement = new PlayerMovement();

    [Space]
    public PlayerLook m_PlayerLook = new PlayerLook();

    [Space]
    public PlayerHeadBob m_PlayerHeadBob = new PlayerHeadBob();

    [Space]
    public PlayerFOV m_PlayerFOV = new PlayerFOV();

    private void Awake()
    {
        m_CharacterController = GetComponent<CharacterController>();
        m_PlayerMovement.Setup(m_CharacterController);
        m_PlayerLook.Setup(transform, m_CameraContainer);
        m_PlayerHeadBob.Setup(m_CameraContainer, 8f);
        m_PlayerFOV.Setup(m_CameraContainer);
    }

    private void Update()
    {
        UpdateInput();
    }

    private void UpdateInput()
    {
        if (m_PlayerMovement != null)
        {
            m_PlayerMovement.UpdateMovementInput();
            m_PlayerMovement.UpdateMovement(transform);
        }
        if (m_PlayerLook != null)
        {
            m_PlayerLook.GetInput();
            m_PlayerLook.Rotation(transform, m_CameraContainer, (m_PlayerMovement != null) ? m_PlayerMovement.HasGravity : false);
            m_PlayerLook.UpdateCursorLock();
        }
        if (m_PlayerHeadBob != null)
        {
            if (!m_CharacterController.isGrounded || m_PlayerMovement == null)
                return;
            float magnitude = m_CharacterController.velocity.magnitude;
            float speed = m_PlayerMovement.CurrentSpeed;
            m_PlayerHeadBob.Bob(magnitude, speed);
        }
        if (m_PlayerFOV != null)
        {
            m_PlayerFOV.CheckStatus(m_PlayerMovement != null ? m_PlayerMovement.IsRunning : false);
        }
    }
}
slender nymph
#

!code 👇 use a bin site for large blocks of code

radiant voidBOT
umbral hound
sudden pollen
#

Hey guys! I'm Jaylan. I'm having a bit of trouble with my Senior Project. You see, I imported an asset called Demo City by Versatile Studio and I successfully added a day/night cycle to it. When I tried to get my spotlights to dim and brighten with my day/night cycle, I noticed that they weren't dimming at all.

I thought it was an error in my script (I have two scripts, one called TimeManager that rotates a Directional and the other called SpotlightManager), but I'm not sure if it's a coding issue. I think it has to do with the fact that the spotlights are GameObjects inside a larger GameObject called LIGHTING and that I'm struggling to connect them inside of Unity Hub.

Is someone able to assist me? I'll send over my scripts, assets, or whatever I need to as long as I'm able to figure this out.

umbral hound
#

Why do you care if it's in the bin or not @slender nymph ? Not being rude just curious. IT all fit in discord

slender nymph
#

because it's easier to read when formatted properly on a bin site and doesn't flood the channel. it's also just common courtesy to follow server guidelines

umbral hound
#

Oh okay

hot wadi
#

Yeah, u can’t really read that code on mobile

umbral hound
#

Well can anyone tell me what's wrong?

slender nymph
#

if you're going to use pastebin, at least have the courtesy to select the correct language so there's syntax highlighting.
- Me, 5 minutes ago

umbral hound
#

Bro, you told me to use pastebin, why say "if you're going to use pastebin"

#

people are so picky, but I'll do it

ivory bobcat
#

Try placing some logs to see the value of the if statement

slender nymph
#

i never said use pastebin specifically, i just said use a bin site and called up the bot which links several that have automatic language detection

umbral hound
slender nymph
umbral hound
#

Okay well I made it use syntax highlighting like you wanted

fervent bramble
#

I am having a problem with my game i have a character model with player movement and animations it is first person and the problem is that when i run or move the camera shows the back of the players head because the animation makes the player lean forward a bit when moving how can i fix this

slender nymph
ivory bobcat
umbral hound
#

That's how AAA studios do it

fervent bramble
#

ya but i might add thrid person or make it multiplayer so there needs to be a head

hot wadi
fervent bramble
umbral hound
#

Okay well Unity has layers. Maybe in first person, disable the head by giving it a layer, then in third person, enable the layer

fervent bramble
umbral hound
fervent bramble
umbral hound
slender nymph
umbral hound
#

I know

fervent bramble
umbral hound
#

But like you never messaged again

hot wadi
slender nymph
fervent bramble
# hot wadi Are u using cinemachine?

no i don't think so i am following this tutorial https://www.youtube.com/watch?v=cGLByetxC00

In this part, we'll cover slope handling, wall handling and steps. Slopes are a difficult part of any player controller, and we make use of our state machine and antibump parameters to ensure near perfect edge detection and amazing ground detection.

This is part of a free complete course for making a player controller, I hope you enjoy it!

·...

▶ Play video
umbral hound
#

@fervent bramble

using UnityEngine;
using System.Collections;

public class ObjectVisible : MonoBehaviour
{
    public LayerMask MyMask;
    void Update()
    {    
        foreach(GameObject g in FindObjectsOfType(typeof(GameObject)))
            if (g.layer == MyMask)
                g.renderer.enabled = false;

        RaycastHit[] hits = Physics.RaycastAll(transform.position, transform.forward, Mathf.Infinity ,MyMask);
        
        foreach(RaycastHit hit in hits)
            Renderer renderer = hit.collider.renderer;    
            if (renderer)            
                renderer.enabled = true;    
    }
}
polar dust
#

Its a slight change, but you can tidy part of the code up

bool AllowUpdateInput {
  get {
    if( m_PlayerMovement == null ) { return false; }
    if( m_PlayerLook == null ) { return false; }
    if( m_PlayerHeadBob == null ) { return false; }
    if( m_PlayerFOV == null ) { return false; }
    return true;
  }
}

void Update() {
  UpdateInput();
}

void UpdateInput() {
  if(!AllowUpdateInput) {
    // make sure all the components exist so you are allowed to continue
    return;  
  }
  // now you dont need all the if statements inside this method
  m_PlayerMovement.UpdateMovementInput();
  m_PlayerMovement.UpdateMovement(transform);
  ...
}```
fervent bramble
umbral hound
fervent bramble
sudden pollen
umbral hound
umbral hound
#

Oh it's because you need to put closing parenthesis on the foreach

fervent bramble
#

ok thanks

fervent bramble
umbral hound
fervent bramble
umbral hound
#

Learn like the rest of us

#

That's what I'm TRYING to do but boxfriend wants to be a dick

fervent bramble
#

i am trying to that is why i ask for help becasue that is how i learn

fervent bramble
hot wadi
fervent bramble
hot wadi
#

Yeah we do not recommend it. It can fix other stuff especially if u don’t pay attention to your code

fervent bramble
wintry quarry
fervent bramble
#

oh ok so like this foreach (RaycastHit hit in hits)
{
Renderer renderer = hit.collider.renderer;
if (renderer)
renderer.enabled = true;
}

umbral hound
#

shit

wintry quarry
fervent bramble
umbral hound
wintry quarry
fervent bramble
fervent bramble
#

oh wait

#

nvm i think i got it

umbral hound
# fervent bramble dude chill

Sorry I'm just... I hate boxfriend because he told me what I needed to do, I did it, then he went "Uhm, not my problem" like wtf

fervent bramble
#

Wait no wi get this error

"MissingComponentException: There is no 'Renderer' attached to the "[Debug Updater]" game object, but a script is trying to access it.
You probably need to add a Renderer to the game object "[Debug Updater]". Or your script needs to check if the component is attached before using it.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <41b87322553648a1a76174c5109c71f9>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <41b87322553648a1a76174c5109c71f9>:0)
UnityEngine.Renderer.set_enabled (System.Boolean value) (at <41b87322553648a1a76174c5109c71f9>:0)
ObjectVisible.Update () (at Assets/AdamOKeefe/FinalCharacterController/Scripts/HidePlayerHead.cs:11)"

umbral hound
#

to the object

#

a mesh renderer

fervent bramble
#

how?

polar acorn
umbral hound
#

go into the inspector, there's a button that says add a component

#

then type in mesh renderer

umbral hound
#

No that is what he meant

#

because my IDE has highlighting

fervent bramble
fervent bramble
polar acorn
grand snow
#

Indeed, the easier it is to read someones code its then easier to provide aid

umbral hound
#

I apologize for being rude but I literally have a learning disability, like... at least tell me how I'm being rude

#

or annoying

fervent bramble
# umbral hound each

i am still getting the error i don't know what to do now. Both the head and neck have mesh renderers and have the layer set to layer

polar acorn
umbral hound
fervent bramble
umbral hound
fervent bramble
untold shore
#

Hey- current thing I’m working on from some advice yesterday.
Currently, I’m trying to find the highest value (the threat value) of an enemy who is inside a collider. Currently, I’m having trouble figuring this out as I’ve seen how to do it for ints, but not for translating this into game objects.
Here is the current script for this specifically (it’s small, but I’m on mobile currently as my desktop discord is broken)

https://paste.ofcode.org/sidxbtp8fqxR2FRCR9gciz

My main question is this: can enemycollider[].max(value) become translated into a game object, or should I attempt to do this process another way? (Please @ me when you respond, though it may take me a second to respond back due to being occupied with work, thanks!)

dark laurel
#

Dunno if that makes sense, sorta pseudo-codey but might get you on the right track.

#

(note that I sort by threat first since that's cheap - colliders are more expensive, if you're gonna be doing it every frame or whatever)

untold shore
#

That makes so much more sense, I didn’t realize order by descending was a thing! I’ll fix up my code by that. Thank you so much!

umbral hound
#

@fervent bramble

private void Awake()
{
    for (int i = 0; i < gameObject.transform.childCount; i++)
    {
        GameObject _gameObject = gameObject.transform.GetChild(i).gameObject;
        if (_gameObject.layer == LayerMask.NameToLayer("Cube"))
        {
            Renderer renderer = _gameObject.GetComponent<Renderer>();
            if (renderer == null)
                return;
            renderer.enabled = false;
        }
    }
}
#

Just replace "Cube" with "Head"

#

Idk if the head is separate

dark laurel
umbral hound
#

Thanks

grand snow
#

gameObject.transform?

#

transform is already a property for "our" transform in a monobehaviour

umbral hound
#

yes

grand snow
#

Also id recommend only 1 use of NameToLayer() outside the loop

fervent bramble
fervent bramble
#

does teh head need to have the layer set to the custom layer named "layer" like the old script an ddoes the head also need a mesh renderer

umbral hound
#

It has a mesh renderer, it just needs the "Head" layer

dark laurel
#

maybe simpler:

int layer = LayerMask.NameToLayer("Cube");
foreach (var renderer in transform.GetComponentInChildren<Renderer>(includeInactive: true).Where(x => x.layer == layer))
{
  renderer.enabled = false;
}
grand snow
#

Hangon, is this all to find the head in some model?

grand snow
fervent bramble
dark laurel
#

perhaps but.. fewer lines of code maybe simpler so fewer off by 1 or unrelated bugs

grand snow
fervent bramble
fervent bramble
grand snow
#
[SerializeField]
MeshRenderer head;
#

yay we can drag in the head in the editor and reference it that way

fervent bramble
#

what do you mean

umbral hound
grand snow
fervent bramble
#

wait the script hsould be attached to the whole player right or just the head

dark laurel
#

The whole player - but you can add multiple references to whatever pieces that script needs to reference

grand snow
# fervent bramble ya

Cool then we can use this to define a variable using this and drag in what we want to reference, such as the head mesh renderer

dark laurel
#
public class PlayerGuyThing : MonoBehaviour
{
  [SerializeField] private MeshRenderer Head;
  [SerializeField] private MeshRenderer Butt;
}
drowsy flare
#

Is there a way to find all sprite renderers showing a certain sprite in unity?

wintry quarry
drowsy flare
dark laurel
wintry quarry
# drowsy flare At runtime

yes but it will be slow and inefficient and there are better ways to do what you aretrying to ultimately do

#

what's the actual gameplay idea here?

fervent bramble
#

so wait what should my code be because i don't see any {SrializeField} anywhere in the code

dark laurel
drowsy flare
#

It's a multiplayer game, where I have a spell casting item. All players that have certain spells equipped in different gear slots, should have something happen to that sprite.

fervent bramble
dark laurel
#

with brackets[SerializeField] not braces and misspelled{SrializeField}

drowsy flare
#

I should probably just do it through the equipment system instead, but would be SO easy to call the sprite renderers 😛

wintry quarry
dark laurel
#

putting [SerializeField] before a variable in a script makes the editor show it

compact sandal
#

Does Cinemachine still have the virtualCamera? I can't seem to find it