#💻┃code-beginner

1 messages · Page 52 of 1

green copper
#

Random.Range(lowerBound, higherBound);

polar acorn
green copper
#

but that's very easy to google

summer stump
#

That will go up to 4
Ints are max exclusive

fringe pollen
#

Yes, but with integers, maximum is exclusive so if you want the number 5 to also show up you have to do a range from -5 to 6

rich adder
#

because you're passing a vector3 as the Transform also written wrong (missing comma)

fringe pollen
#

First off, the obvious thing, you have forgotten a coma between 'pipePrefab' and the vector

rich adder
#

!ide

eternal falconBOT
fringe pollen
#

Also, I'm not sure if that is even a valid way to instantiate an object, as I believe you need to pick one of these (picture) declarations

rich adder
#

so get learning

#

start with a configured code Editor to actually show the correct parameters and underline errors

fringe pollen
#

What exactly don't you understand? The declaration part?

snow abyss
#

Gotten this warning message on console,
Is this something I should be worried about?

#

I went through the forums, and it's looks like it's related to something called "unmanaged code" such as NativeArrays

#

not sure what are those but I did not touch any of those functions

gaunt ice
#

if you are not using any of native or unsafe stuffs then not you problems

snow abyss
#

I just looked what native arrays are and It's something related to memory management unity's using?

#

what's "unsafe stuff" in this context?

gaunt ice
#

similar to native

snow abyss
#

ah anything related to memory management?

gaunt ice
#

but can crash the editor directly

snow abyss
#

the internal stuff?

#

oh dang, I think I understand now & thanks for the clarification

eternal needle
mellow shuttle
#

and also why my character is not moving forward yet it seems to me to have done everything well

rich adder
minor viper
#

what game should i make

zealous geyser
#

Hi Guys! I started my very first project in Unity and need little help (If I wroted on wrong channel then please let me know!). I have 3d model, animation and unity project. Any tips how to implement walk animation to game (any simple good tutorial but not 2hours long😅 ) ?

minor viper
#

I just finished my cube runner game

rich adder
summer stump
rich adder
zealous geyser
#

I mean by that when you press "w" then animation will start

rich adder
#

not sure how this is relevant to this dc at all ?

rich adder
#

Input.GetKey or Input.GetAxis respectively

silver lagoon
#

Saw someone create a polygon like this in a video. Is this not possible anymore?

zealous geyser
#

Thanks

rich adder
#

also not a code question

#

no? just pointing out the irrelevance of your post and its clutter

#

a mods gonna tell you the same thing lol

summer stump
#

You've been warned so many times... why do you keep doing it?
This is a community and Nav is doing their part to keep it healthy and productive
Signal to Noise ratio bro

rich adder
short hazel
#

Didn't say what "this" was referring to lol, but yup doesn't seem like a code problem

rich adder
#

could be from postprocessing to lighting 🤷‍♂️

#

Ima guess they mean that big square of grass glowing lol

noble rover
#

Apolgies Ill switch to a different channel

unique laurel
wintry quarry
# unique laurel

You can't use variables that don't exist in the current context

#

your first screenshot is clearly not the same context as the second

#

this is an algebra question not a C# question

#

x is 1000, always

#

not sure what that has to do with C#

unique laurel
#

what is the diffrent between

Public and Private int?

wintry quarry
rich adder
unique laurel
#

seems to be working now

summer stump
dry tendon
#

why do i get this log trying to acces to the JSON?

slender nymph
#

the SunData class does not have a sunset variable

#

the SunData.Results class does though

unique laurel
summer stump
dry tendon
short hazel
#

You can do it in roughly one line

dry tendon
rich adder
#

prob wanna use JSON.net and cut the middle man class

#

but hey if i t works no worry

short hazel
#

Why you need another class is because of how your API returns data

wintry quarry
rich adder
#

you don't even need to map all the fields lol

#

if they aren't used

swift crag
short hazel
#
{
  "status": "stuff here",
  "results" : {
    // the actual data
  }
}

Something like that

dry tendon
dry tendon
swift crag
#

So there are two types here: the top-level object that holds status and results, and the type that will hold the contents of that results object

dry tendon
#

but here i'm not doing public GameData gameData;...

swift crag
#

well, yes, it would make no sense for GameData to contain a GameData

short hazel
# dry tendon hehe i always do that even if i don't want it

Here:

DateTime d = DateTime.Parse(hereAMPM, System.Globalization.CultureInfo.InvariantCulture);

Then you can access everything you want on d. I pass the invariant culture in the second argument, so it does not fail if someone who uses a different system language plays your game

swift crag
rich adder
#

I don't think they understand json objects and nesting

swift crag
#

You.

#

I think the most useful way to learn this would be to look at what happens when you serialize a simple class

wintry quarry
swift crag
#

Then look at how things work when you serialize a class that contains a reference to another class.

#

You will get nested objects.

#
{
  "foo": {
    "bar": 1
  }
}

This is equivalent to

[System.Serializable]
public class ClassOne {
  public ClassTwo foo;
}

[System.Serializable]
public class ClassTwo {
  public float bar;
}
dry tendon
#

oh, i getted it... But it's true, i don't really know how JSON files works... I'm trying to learn it... i've watched a few tutorials of how to do it... But i think they are just showing me how to do what they want... And my head is being broken...

#

Thank you everyone for your help 🙂

wintry quarry
swift crag
#

Start from the top. Create a class that has a field for every entry in the JSON object.

Every time you encounter a new kind of object, create a new class that has fields for all of its entries.

#

If there is an array, create a list of whatever the array contains

eternal needle
#

Json is just a format, a way to represent data. Stuff like jsonutility or Newtonsoft already handle reading and writing it, so it's really just a matter of running a few tests to see what it does

dry tendon
swift crag
#

No.

#

Show us example of the JSON you get back from the date-and-time website.

swift crag
#

Okay, so, starting from the top

#

This is an object with two members.

#

The first member's name is "results". Its value is another object.

dry tendon
#

and status

swift crag
#

The second member's name is "status". Its value is a string.

#

So, the class you deserialize this into must have two fields in it.

#

The "status" field will just be a string, so that's done.

#

The "results" field is another JSON object, so we need to make a second class

#

This object has a bunch of members that have strings for values, and one value that's a float

unique laurel
#

i tried to make a invetory system and ended up making a canculator

swift crag
#

It contains no other objects, so we won't need to create any other classes.

unique laurel
#

a pretty bad one

dry tendon
#

Do you care?

obtuse oar
#
public class Button_Controller : MonoBehaviour {
    public List<GameObject> lights;
    private List<Light_Controller> light_Controllers;

    private void Start() {
        foreach (GameObject light in lights) {
            light_Controllers.Add(light.GetComponent<Light_Controller>());
        }
    }

    private void OnMouseDown() {
        foreach (Light_Controller light_Controller in light_Controllers) {
            light_Controller.changeState();
        }
    }
}

am I using lists wrong here? the lights list has one light object in it, that object does indeed have a Light_Controller component on it but I am getting a null reference on the line in the first loop. The first inspector is the light object, the second inspector is the object with the script in question on it

#

huh, discord just said fudge those pics

slender nymph
#

where do you initialize your light_Controllers list?

#

here's a hint: you don't

obtuse oar
#

haha

#

one day i'll remember that

#

hey good news is it works perfectly after that

wintry quarry
#

just do public List<Light_Controller> light_Controllers; and abandon the GameObject one

obtuse oar
#

how do i grab the components?

wintry quarry
#

same way you did before

#

drag and drop in the inspector

obtuse oar
#

whattt

wintry quarry
#

you can then delete your Start() function too

obtuse oar
#

i always thought comonents were only accessible through the GetComponent method

slender nymph
#

yeah you almost never need to reference the GameObject directly

obtuse oar
#

2 years unity experience btw lmfao

#

that would have been very useful to know in the development of my last game at college haha, so many lines wasted on grabbing components

slender nymph
#

wait until you learn you can pass a component reference to Instantiate and it will return the instance of that component that was created on the gameobject you spawn

wintry quarry
obtuse oar
#

i really wish i could see how many lines in my old projects reference GameObject when it wasnt necessary

wintry quarry
#

I blame all the tutorials

wintry quarry
obtuse oar
wintry quarry
#

where MyScript is a script on the root object of the prefab

obtuse oar
#

so it's fetching the component of a new gameobject created?

#

the parameters for Instantiate say it needs to be an object passed to it, how does it work with a component reference

slender nymph
#

this is using the generic version of Instantiate which is lower on the docs page. it returns the same type you pass to it

#

obviously it would still need to be a UnityEngine.Object though

obtuse oar
#

ohhh, i see now

#

so this is a method of creating duplicate objects and grabing the same component again in one line?

slender nymph
#

yep

obtuse oar
#
public class Bullet_Controller : MonoBehaviour {
    private int speed = 10;
}

public class Gun_Controller : MonoBehaviour {
    public Bullet_Controller bullet;

    private void Start() {
        Bullet_Controller bulletCopy = Instantiate<Bullet_Controller>(bullet);
    }
}

really simple example but is this like the proper use of it?

#

basically just ripped their example on the docs but with a component instead

#

unless their example of "Missle" is just a poorly named controller lol

slender nymph
#

you don't need the generic type parameter on the Instantiate call, it's implied from the parameter you pass to it, but yeah that's how you would do it

obtuse oar
#

that's sick
noted for future use, thank you

green copper
#

!code

eternal falconBOT
green copper
#

how can I make this camera following code smoother? It technically works, but it's really jerky

slender nymph
#

use cinemachine instead

#

you are also moving in a frame dependent way. your code will move the object faster at higher framerates

green copper
#

The object is the camera, so it doesn't matter at faster framerates

slender nymph
#

lol yes it does

#

imagine you're playing your game and suddenly it starts running very well at a few hundred frames per second instead of like 30 or 60. suddenly your camera is moving much faster. then later on it drops back down to like 30 frames per second. now your camera is moving much slower than it was

green copper
#

I moved the function to FixedUpdate, I need help with smoothing now

#

what's cinemachine?

obtuse oar
#

for that stuff would FixedUpdate be the way to go or something else

green copper
#

Okay this is a basic 2D follow cam cinemachine seems like massive overkill

slender nymph
#

just throwing it in FixedUpdate isn't a great idea either. they should be scaling the movement by deltaTime to make sure it moves consistently no matter the framerate since they are just incrementing the position

slender nymph
polar acorn
#

You don't have to even use all of the wonderful features

summer stump
#

I third using cinemachine. It almost should just be the default camera in unity

But I guess there are some uses for the normal camera still

rich adder
#

cinemachine is 🐐

green copper
#

that was surprisingly easy, the way the first five results were done up like "Cinemachine won five cinematography engneering awards" made it seem like a whole process to learn

#

so, problem

#

I need the camera to be able to pixel perfect teleport 10.24 units when the space texture edge is reached

#

can cinemachine still do that with the tracking?

#

I also need to reimplement a barrier the camera cannot track past

grim ether
#

yo how to make this code work

#

if (collision.collider.CompareTag("Blue") || collision.collider.CompareTag("Blue"))
{
Destroy(collision.gameObject);
Debug.Log("Worked");
}

slender nymph
slender nymph
eternal falconBOT
grim ether
#

nope because it used to work

slender nymph
#

what about that is not working then

grim ether
#

checking the object that has the script own script

sturdy lintel
#

Quick question. I am facing an issue where If I create a new quad, It's having this blue tinted color. It has default material only. how do i fix it?

polar acorn
slender nymph
polar acorn
grim ether
#

ok so there a hammer and this hammer has this script then it checks for collision then it check for the tag of object collided with and the its own tag but checking its own tag doesnt work

polar acorn
#

there could also be color in the default material

grim ether
slender nymph
#

where

#

not in that code you are currently asking about you're not

polar acorn
sturdy lintel
polar acorn
grim ether
polar acorn
sturdy lintel
grim ether
#

yes

#

thank you

polar acorn
# grim ether yes

So you should probably do that instead of checking the collided object twice

grim ether
#

ok but idk how i dont remmber how to

polar acorn
grim ether
#

ye using compare tag

slender nymph
#

do you know how to get the tag on an object?

polar acorn
grim ether
#

how? because compare tag compare the tag you right the name of to the actualtag thats on the object how do i change it to compare the object you collided to with the object that has the code

polar acorn
#

Get the tag of the other object, pass it to compare tag

polar acorn
#

You know how it works, go do it

grim ether
#

yo i actually can figure it out

#

if (collision.collider.CompareTag(gameObject.CompareTag("Red")))

#

blanking so hard so tired

slender nymph
#

you need to get the tag from the gameobject

grim ether
#

Finnaly i stopped blanking and remmebered

#

if (collision.collider.CompareTag(gameObject.tag))

#

bro so tired that i blanked so hard that i forgotcoding

#

thank you @slender nymph and @polar acorn

sturdy lintel
green copper
slender nymph
green copper
# sturdy lintel I don't understand

check to see if shining a light on it makes the colors what you expect, and if that doesn't work, ask in the channel for lighting or other graphical stuff

subtle hedge
#
 if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
 {
     if(Vector3.Distance(currentPlacement, hit.point) > stepDistance && !isMovement)
     {
         lerp = 0f;
         newPos = hit.point;           
     }
 }
 if(lerp < 1)
 {
     Vector3 pos = Vector3.Lerp(currentPlacement, newPos, lerp);
     pos.y += Mathf.Sin(lerp * Mathf.PI) * stepHeigh;

     lerp += Time.deltaTime * stepSpeed;
     currentPlacement = pos;
 }
 else
 {
     currentPlacement = newPos;
 }``` the object is not lerping, why ?
slender nymph
#

where are you using the currentPlacement variable

polar acorn
polar acorn
#

What is stepSpeed, add that to the log

subtle hedge
#

or maybe i'm setting lerp to 0 constantly

polar acorn
#

Probably

green copper
#

What's the best way to tell the main game manager script when to increment the score from an instanced laser destroying an instanced asteroid?

#

I tried adding public mainGameManager and attaching the root, but it claimed Type Mismatch

slender nymph
#

sounds like you've tried dragging a scene object into a prefab which you cannot do

strong wren
slender nymph
summer stump
feral palm
#

can anyone help me get breakpoints working with vs code/ unity?

#

installed the unity extension

slender nymph
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

feral palm
#

bro i still need help ice had a look at it

short hazel
#

Did you install everything required, and did you modify Unity's configuration so it uses what was just installed?

feral palm
#

Unity's configuration so it uses what was just installed

#

i didnt do this

slender nymph
#

why not? didn't you say you had a look at the guide the bot linked?

feral palm
#

i tried

#

could find what im looking for

short hazel
#

Everything mentioned in that link should be enough to make it work

#

If it's not the case, then start checking that you did the steps correctly, then double-check
Then explore what could be wrong, looking at the VSC console should be a good start to see if the project is detected, compatible, and loaded

tropic olive
#

I need help with a grounded function for jumping using rays. I'm casting a ray downwards on a composite tilemap collider but it seems to not detect it at all. Works fine on other objects.
Here's the code for the jump function:

public float minFloorDistance;
public Vector3 raycastOriginOffset;

if (Input.GetButtonDown("Jump")
    && Physics2D.Raycast(this.transform.position + raycastOriginOffset, -Vector2.up, minFloorDistance))
{
    body.AddForce(Vector2.up * jumpForce * 10); 
}```
slender nymph
#

are you sure you aren't perhaps starting the raycast too low?

#

if you start the cast inside the tilemap's collider it likely won't detect it

tropic olive
#

oh

feral palm
#

idk how i did

#

but i did it in the end

#

hol on

#

it worked

#

then it stopped

#

what is suppost to be in my launch.json file

#

i tihnk i done something to it

raven trench
#

i was wondering if theres a way to put the money variable into the text so it says how much i have in the text instead of 0 yknow idk why i cant find stuff online

#

nvm im dumb i got it

grim ether
#

good

tropic olive
slender nymph
#

sounds like you did it wrong

feral palm
#

yo it still aint working

#

this is the error im getting

#

Unable to determine debug settings for project 'C:\Users\Vas\treasure game v1.0\Assembly-CSharp.csproj'

silk night
#

VSCode has some problems with it if I remember correctly

feral palm
#

ok

copper perch
#

Can anyone help?
I am trying to make crazy zombie boss do a head spin dancing animation.
It is in 3 parts from Mixamo, the 3 animations make one complete dancing animation.
It was working before but I went to settings and I increase exit time to a larger number and Crazy zombie boss stopped doing the headspin dance animation.
I sent the script and what is going on in the inspector

#
using UnityEngine;
using UnityEngine.AI;

public class CrazyZombieBossAnimationControl : MonoBehaviour
{
    private NavMeshAgent navMeshAgent;
    private Animator animator;
    private bool isAnimationPlaying = false;

    // Define normalized time thresholds for animations that should stop movement
    private float animationStartThreshold = 0.0f;
    private float animationEndThreshold = 1f; // Adjust this value based on your animation's length

    private void Start()
    {
        // Get references to the NavMeshAgent and Animator components
        navMeshAgent = GetComponentInParent<NavMeshAgent>();
        animator = GetComponent<Animator>();
    }

    private void Update()
    {
        // Check if any of the specific animations are currently playing
        if (animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie hip hop dancing") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie taunt") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie hip hop robot dance") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie fall flat") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie dancing running man") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie arm wave") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie cross punch") || // Added
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie headspin start") || // Added
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie headspinning") || // Added
            animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie headspin end")) // Added
        {
            // Pause the NavMeshAgent's movement
            navMeshAgent.isStopped = true;
            isAnimationPlaying = true;
        }```
#

2

   else if (isAnimationPlaying && animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= animationEndThreshold)
        {
            // Resume the NavMeshAgent's movement if the animation has reached the end threshold
            navMeshAgent.isStopped = false;
            isAnimationPlaying = false;
        }
    }
}```
teal viper
#

Anyways, it sound like the problem is with the animator setup, not the code..?

copper perch
copper perch
sour fulcrum
#

First of all, your going to have a far better time having condensed and simplier names for those animation paramaters

teal viper
copper perch
copper perch
# teal viper Why?

not sure I just tried it withoyt has exit time the animation did not do start

#

im lost

#

any help i appreciate

#

my brain hurts

teal viper
#

Just return it to how it was before..?

copper perch
#

I did and its still not working

#

can i call you and you walk me through it with discord screenshare

#

im lost

#

been on this for like 3 days

teal viper
#

I'm at work. I can only help via messages when I have some free time. This is true for most people here, so don't expect someone to hop in a call.

That being said, your issue is complex and really hard to debug for anyone that doesn't have access to your project.
To solve it you'll need to learn to debug such issues. Start from figuring out what's going on first. Watch the animator live, while the issue happens. Does it enter the state at all? Does it enter and then exits it? Why? Are the parameters changing? Where are the parameters set? Etc...
You need to learn to ask these questions and explore them on your own.

copper perch
#

ok ill try to do it myself but if i fail can you help me?
in return ill help you with anything in your game

teal viper
#

We can only help you with specific questions. If there's something specific during your debugging, that you don't understand, feel free to ask. It might not be me, but someone would definitely help. Just don't let the other person do all the work for you without even having access to your project.

sturdy lintel
#

how do we disable shadows on a gameObject via code?

shell sorrel
#

shadowCastingMode on its renderer

copper perch
polar acorn
teal viper
copper perch
edgy prism
polar acorn
sour fulcrum
#

The general vibe of a server like this, respectfully, is beggers can't be choosers.

The best way to get help here is to make it as easy as possible for people to understand your problem and what you need as a solution

sour fulcrum
#

If you need active screenshare/call time then your not going to have many people available to assist you

copper perch
#
using UnityEngine;

public class CrazyZombiesDanceAnimationActivator : MonoBehaviour
{
    private Animator animator;
    private float danceTimer = 5f; // Time interval for dancing
    public string[] danceAnimations = {
        "Crazy zombie hip hop dancing", "Crazy zombie taunt", "Crazy zombie hip hop robot dance", "Crazy zombie fall flat", "Crazy zombie dancing running man", "Crazy zombie arm wave", "Crazy zombie headspin start", "Crazy zombie head spinning", "Crazy zombie headspin end" // Add the names of your dance animations here
    };

    private void Start()
    {
        animator = GetComponent<Animator>(); // Get the Animator component attached to this GameObject
    }

    private void Update()
    {
        danceTimer -= Time.deltaTime;

        if (danceTimer <= 0)
        {
            PlayRandomDanceAnimation();
            danceTimer = 8f; // Reset the timer for the next dance
        }
    }

    private void PlayRandomDanceAnimation()
    {
        if (danceAnimations.Length > 0)
        {
            int randomDance = Random.Range(0, danceAnimations.Length); // Select a random dance animation name
            Debug.Log("Triggering " + danceAnimations[randomDance] + " animation");
            animator.SetTrigger(danceAnimations[randomDance]); // Set a trigger with the animation name
        }
    }
}```
#

had to add the names of the animations in the inspector and in the script

frosty hound
#

In the future, if you plan on chaining animations, you may want to use a timeline.

edgy prism
teal viper
# copper perch i fixed it

That's great and I hope you learned something in the process. Regarding a call/screen share, if you were fine with waiting untill my weekend and when I feel like making a call(which I usually don't, at least not with random people on discord), then sure.

Besides, there's nothing you can't share in a video or screenshot. I feel like this is just a lazy way to get your issue solved for you without putting any effort. If you have went through learning the basics, you wouldn't have a problem with sharing the relevant pieces of information for people to help you.

copper perch
#

i was out of luck

#

I tried joining a C# club to learn near me but no reply yet

#

my demo is almost compete its just im stuck on ammo pick up

#

I am available any day for screenshare if you can help me with this

teal viper
#

There are plenty of learning materials online.
If you haven't gone through any basics yet, you should really do it.

#

And if it wasn't clear enough, I(and most people here would say the same) really don't feel like joining a call regardless of the time.

chilly socket
#

Hi all, I was trying to add a method for downloading a set of 3 png's (or just a zip file of them) to the users computer. I don't need to generate these images at runtime or anything, it's just a set of icons that I've made for a user to upload into their twitch dashboard. I want to include them in the build, rather than having to host them online somewhere. I guess ideally I would use a native explorer/finder dialogue to choose a location to save them. Its a bit hard to google this one, if anyone could point me in the right direction that would be much appreciated 😊

#

I guess I could just include them in the download and point users there, maybe i'm overcomplicating it...

teal viper
#

Google "unity file explorer" there are plenty of assets that implement it.

chilly socket
#

Thanks this was it, I just needed the right keywords! ❤️

raw hamlet
#

how do you get the rotation angles for an object

#

not local but global angles

#

my inspector says z is -84

#

but my console is printing out 0

#
Debug.Log(transform.localRotation.eulerAngles.z);
#

wait

#

i am so confused

#

i am using

#
Debug.Log(transform.localRotation.eulerAngles);
#

to print this out to the console

#

why are the values flipped for the x and z

teal viper
#

Are you sure you're looking at the correct object?

raw hamlet
#

let me double check

#

yes

#

i am

eternal needle
# raw hamlet

these may be the same rotation. rotations are stored in quaternions so when you want it as euler, they have to convert it. there are many euler angles that can represent a single rotation

raw hamlet
#

i think i will ahve to learn about this

#

i am pretty new

#

thank you for your advice

eternal needle
raw hamlet
#

i am using the rotation to determine what side is up for a dice

#

i am only using the x and z rotation

eternal needle
#

also you can see examples of this by simply setting the rotation in inspector, then it suddenly changes to become something else. I think if you set Y to 180, itll change X and Z to 180 instead

raw hamlet
#

why does this happen?

eternal needle
#

definitely not the most efficient but just a thought

raw hamlet
#

ok

#

i still don't want to give up on using rotation to determine what side is up

eternal needle
# raw hamlet why does this happen?

Because its stored as a quaternion, then converted back to euler angles for you to read in inspector.
https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html

When using the .eulerAngles property to set a rotation, it is important to understand that although you are providing X, Y, and Z rotation values to describe your rotation, those values are not stored in the rotation. Instead, the X, Y & Z values are converted to the Quaternion's internal format.

verbal dome
#

Also the inspector shows localEulerAngles not eulerAngles

raw hamlet
#

i am just going to search up a youtube tutorial on rotation and euler angles and hope for the best

#

Ok, thank you for the advice, i will look into it

eternal needle
eternal needle
#

you would have to hardcode sooo much to get this working

raw hamlet
#

really?

#

i only have like 6 if statements for each of the sides

#

ofc it doesn't work but i am working on getting the right values

eternal needle
#

getting the right values is the hardcode in this case

verbal dome
#

I would get the three dot products, one for each side (XYZ) vs. Vector3.up

eternal needle
#

What would you do if a dice was also not fully flat on the ground? you now cant compare directly to euler angles like 0, 90, 180. You would have to check if its closer to 180 than 90, but also in which direction? What if the angle is something silly like (45, 0, 180), what did you roll?
It may not be the best solution but even just comparing the transform.up of an object on each face to vector3.up is already way more reliable

verbal dome
#

Yeah if the ground can be tilted, you would have to use the ground normal instead of world up

raw hamlet
#

i have no idea what the three dot products is but i will look into everything you talked about

#

Thank you for your time to answer my question

eternal needle
#

if you are rolling the dice via physics, then theres already a chance it wont be fully flat on the ground. Assuming there is more in your world than just a single dice

raw hamlet
verbal dome
#

Do you have multiple dice?

raw hamlet
#

no

verbal dome
#

Nothing it can collide with?

raw hamlet
#

except the ground

eternal needle
#

if its literally just the ground and dice, then yea should be flat. If your solution relies on it being flat though.. thats really not a proper solution

verbal dome
#

Semi-pseudo code of how I would go about it```cs
Vector3 dotY = Vector3.Dot(transform.up, Vector3.up);
Vector3 dotX = Vector3.Dot(transform.right, Vector3.up);
Vector3 dotZ = ...
if abs of dotY is the largest of the dot products
if(dotY > 0)
// Facing up = 6
else
// Facing down = 1
// Etc

raw hamlet
#

again, thank you for your help. I will research this all tomorrow

#

I got to go now

sour fulcrum
#

Might be a little janky but honestly could just have 6 transform points on each side of the dice and see which one has the highest world position, no?

silver dock
#

it should collide with only one thing (enemy, or enemy's head) at a time and perform different actions according to that (gameover or destroy enemy object), but it keeps colliding with both of the things at once for some reason :(

pastel vector
#

I have a simple targeting system for my Ai in my 2d game it works fine for the first couple of targets but then its start rotate on both x and y axis.
Cant figure out what im doing wrong, feels like ive done the exact same thing before without problems.



    private void HandleTurning()
    {
        if (target != null)
        {
            Vector3 targetPosition = target.position;
            Vector3 playerPosition = playerGameObject.transform.position;
            playerDirection = (playerPosition - targetPosition).normalized;
            playerGameObject.eulerAngles = Vector3.RotateTowards(playerGameObject.eulerAngles,new Vector3(0f, 0f,        WorldSpaceUtils.GetAngleFromVector(playerDirection)),50f *Time.deltaTime,50f*Time.deltaTime);
            WorldSpaceUtils.GetAngleFromVector(playerDirection)),1f*Time.deltaTime);
        }
    }
#

The the get angle function looks like this

    public static float GetAngleFromVector(Vector3 vector)
    {
        float radians = Mathf.Atan2(vector.y, vector.x);
        float degrees = radians * Mathf.Rad2Deg;
        return degrees;
    }
chilly moss
#

wrong channel

pastel vector
#

@chilly moss if you export fbx you can set units in some dccs

#

at least in Houdini, think the option should be there in Blender as well

solemn fractal
#

hey guys, is there no .data like this? yesterday someone here told me to do like that but it says data doesnt exist as a method.. what I am trying to do here is basically instantiate an enemy using only 1 prefab and assigning data from a scriptable object to this enemy so I can spawn dif enemies using the same prefab

#

how can I have only 1 prefab and instantiate it on the scene dif enemies, using only 1 prefab and assigning the SO to this enemy that will contain dif values and so on so I can manage a good way to have multiple dif enemies using only 1 prefab so I dont need to have 100 prefabs if I have 100 dif enemies

burnt vapor
#

This is basic c#

solemn fractal
#

i thougt that data was already something unity has .. anyways anyone know a way that I can instantiate enemies using 1 prefab with dif things? or there is a better way? i am 3 days struggling with that and I am not progressing

burnt vapor
#

As far as I am aware Unity does not have a data variable available, and even if it does it would exist for a reason. If you want a place to store your data in the class, you should make an actual variable to store it.

solemn fractal
#

ok, but what about my other question? 😛

keen dew
#

The answer to the other question is the same as to the first question. Make a field in Enemy1 that stores a reference to the SO and then assign the SO to that field

#

and don't use the ScriptableObject type, use the actual type of the SO

solemn fractal
#

hm ok, well I think i will still be stuck for a while with that. Or i will just go the hard way that is creating a dif prefab for all the dif enemies I have as ScriptableObject or any other sort of ways i am trying to optimize and not having 1000 prefabs I am not managing to do it..SO what ever for now I will create 1 prefab for each dif enemy . it is what it is.

keen dew
#

What do you mean "stuck"? What's the issue with that?

solemn fractal
#

well I am beginner, 2 weeks into unity.. progressed a lot with my mini game so far, but now I am stuck. I am trying to do something and I am not being able to do it. Tried this discord many times during the days, google, chatgpt, but surely I am the prob. my game for now will not have more than5 enemies or so, but who knows in the future, so I wanted to already implement a way that I can have a lot of dif enemies with low memory use or in an effective way. Not sure which one it is, but so far as I checked people say SO is the way to go with 1 prefab. But I am not being able to do it. As when I use the instantiate and the prefab, I am not sure how to attribute to that prefab dif SO, So I have dif enemies being spawned using the sabe prefab but dif values from the SO. Also not sure if that is the best way. So maybe I will just forget about it to be able to progress and learn more stuff and use just 1 prefab for each enemy eve tho this is not the best way to do it.

solemn fractal
#

well yeah, for you might be simple to read and understand what you wrote, but for me its not so clear as I am still a nb and i ned time to process and understand things if not more detailed explained or shown in code. But I apreaciate your answer I will try to understand it better.

keen dew
#

What's the type of the SO?

solemn fractal
#

that you mean?

keen dew
#

No, in the code

#

public class XXX : ScriptableObject

#

what is XXX

solemn fractal
keen dew
#

In the Enemy1 class add

public EnemySO data;

in the class that instantiates the enemy change the SO list type to

[SerializeField]
private EnemySO[] listOS;

Then your enemyOne.data = ... code works and you can access the SO through the data field in the Enemy1 class

ruby python
#

Hi all, I have a screenpointtoray firing and colliding with a 'ground' object (3d) with a custom crosshair attached to the mouse pointer. Is it possible to 'lock' the mousepointer inside the area of the ground object? (ie, if the ray is hitting the ground act as normal, but if the ray isn't hitting the ground, as in hitting empty space, the mouse cursor can't move past the edge of the ground?)......not sure if that's explained very well. lol.

keen dew
#

And please stop sharing !code through screenshots 👇

eternal falconBOT
solemn fractal
solemn fractal
keen dew
#

It's ok, it's just easier to help when you can copy-paste the code instead of having to rewrite it

solemn fractal
#

true

#

Another question, here in this SO code ```cs using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "EnemySO", menuName = "enemies/enemy1")]
public class EnemySO : ScriptableObject
{
public string type;
public int health;
public int exp;
public int attackDamage;
public float speed;

public float detectionRadius;    
public float avoidanceDistance; 
public float repulsionForce;    

public GameObject player;

public void Print(){


}

}
Can i put a variable here to change the color of it controlling in the inspector? like acs GetComponent<SpriteRenderer>();

#

becuase for now I dont have a sprite to add to it, so i just want to change the color of the enemies to keep it simple for now

keen dew
#

I think Color type is serializable? So you could do public Color color; and then use that to change the sprite renderer color

solemn fractal
solemn fractal
solemn fractal
# keen dew I think `Color` type is serializable? So you could do `public Color color;` and ...

Any ideas why I would get an error on that line? I mean I can read the error, but not sure how to fix it. ```cs
[SerializeField]
private GameObject _enemySO;

void Start()
{  
    _player = FindObjectOfType<Player>();
    InvokeRepeating("SpawnEnemy", _spawnCount, _spawnDelay);
    
}

void Update()
{
    if (testing == true)
    {
        Enemy1 enemyOne = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
        Enemy1 enemyTwo = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
        enemyOne.data = listOS[0];
        enemyTwo.data = listOS[1];
        testing = false;
       
    }
}
keen dew
#

The field must be of type Enemy1

solemn fractal
#

but it is no?

#
Enemy1 enemyOne = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
keen dew
#

The field

#

private GameObject _enemySO; -> private Enemy1 _enemySO;

solemn fractal
#

yeah but that way it doesnt instantiate in the scene

#

says object you want to instantiate is null

keen dew
#

Then _enemySO is null 🤷

solemn fractal
#

and if I use _enemySO = FindObjectOfType<Enemy1>(); on start

#

it is not null anymore

#

but also doesnt instantiate

keen dew
#

Then either something destroys it immediately or it is instantiated but you just don't notice it

woven kestrel
#

!code

eternal falconBOT
solemn fractal
# keen dew Then either something destroys it immediately or it is instantiated but you just...

Ok, so i create a new project to test it. And that is the setup I have, and with this simple setup you might be able to spot it and help me out maybe. I have just 2 scripts, EnemyControoller and SpawnManager and 1 prefab. The code from the EnemyController now is empty as this is a test. And in the SpawnManager I have: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
private EnemyController enemyController;
private bool test = true;

// Start is called before the first frame update
void Start()
{
    enemyController = FindObjectOfType<EnemyController>();
}

// Update is called once per frame
void Update()
{
    if (test == true)
    {
        Instantiate(enemyController, new Vector3(3, 3, 0), Quaternion.identity);
        test = false;
    }
}

}```

#

and gives me the same thing

#

what am I missing here?

languid spire
#

obviously

enemyController = FindObjectOfType<EnemyController>();

is not finding anything

solemn fractal
#

yeah as it is a script and not a game object, but If I try to do something like that ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
private EnemyController enemyController;
private bool test = true;

// Start is called before the first frame update
void Start()
{
    enemyController = FindObjectOfType<EnemyController>();
}

// Update is called once per frame
void Update()
{
    if (test == true)
    {
        EnemyController enemy1 = Instantiate(enemyController, new Vector3(3, 3, 0), Quaternion.identity);
        test = false;
    }
}

}```

#

and instead of using the EnemyController type use Gameobject

#

it will give me an error

#

What I need is to assign to a variable the instantiate method

languid spire
#

Did you read the FindObjectOfType documentation to see how it works?

solemn fractal
#

oh, yeah, but wait I might not being able to say what i want. give me a second will do a test sorry, sometimes I confuse stuff when I ask as I am still a nb

#

on my actuall game code I have this code here in my SpawnManager, BUT I get an error in the enemyOne.data and enemyTwo.data saying that Gameobject does not contain a definition for data. So how can I access that variable that is inside my enemy1 script if i need to use a gameobject type to instantiate it? ```cs
private GameObject _enemySO;

void Start()
{  
    _player = FindObjectOfType<Player>();
    InvokeRepeating("SpawnEnemy", _spawnCount, _spawnDelay);
    
}

void Update()
{
    if (testing == true)
    {
        GameObject enemyOne = Instantiate(_enemySO, new Vector3(3, 3, 0), Quaternion.identity);
        GameObject enemyTwo = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
        enemyOne.data = listOS[0];
        enemyTwo.data = listOS[1];
        Instantiate(enemyOne);
        Instantiate(enemyTwo);
        testing = false;
    }
}```
minor viper
#

whats wrong with the code

solemn fractal
#

that is so complicated, i might just create 1 prefab for each enemy, 3 days and no progress

#

I give up

#

hahaha

minor viper
#

using UnityEngine;

public class YourScriptName : MonoBehaviour
{
public GameObject enemyPrefab; // Assign your enemy prefab in the Unity Inspector
public List<YourDataType> listOS; // Make sure you have a list of your custom data type

private Player _player;
private bool testing = true;

void Start()
{
    _player = FindObjectOfType<Player>();
    InvokeRepeating("SpawnEnemy", _spawnCount, _spawnDelay);
}

void Update()
{
    if (testing)
    {
        // Instantiate two enemies
        GameObject enemyOne = Instantiate(enemyPrefab, new Vector3(3, 3, 0), Quaternion.identity);
        GameObject enemyTwo = Instantiate(enemyPrefab, new Vector3(-3, -3, 0), Quaternion.identity);

        // Assuming YourDataType is a custom script or component you want to attach to the enemies
        enemyOne.AddComponent<YourDataType>().data = listOS[0];
        enemyTwo.AddComponent<YourDataType>().data = listOS[1];

        testing = false;
    }
}

}
use this you have tho change some things cuz i dont know what project ur doing

languid spire
solemn fractal
#

on my enemy script that I assigned to the prefab I have. So the goal is to have 1 prefab with 1 script to control its basic things and I have a ScriptableObject script to control life, damage, etc... So what I wanted is that my SpawnManager would manage to Spawn dif enemies using 1 prefab only and control their dif stats etc with a SO

minor viper
#

ye

languid spire
#

exactly .data is on a script of type Enemy1. Not on GameObject which is what you are trying to access. So get a reference to the Enemy1 script from the GameObject

solemn fractal
#

its a game like vampire survivors or halls of torment

minor viper
#

ok sounds fun

solemn fractal
#

I already managed to progress in a lot of things.. but now I want to be able to control that part of the enemies to continue

minor viper
#

ok

solemn fractal
#

here is what I have so far

#

but now I want not only 1 enemy to spawn

#

i need more with dif size, color, etc for now as sprites and stuff I will add later in the game when the logic is finished

solemn fractal
minor viper
#

okay looks nice

languid spire
solemn fractal
#

yes

languid spire
#

and the Enemy1 script is attached to the prefab is it not?

solemn fractal
#

yes

languid spire
#

so it is also attached to the Instantiated GameObject. So you can get a reference to it

languid spire
#

do you not see that you are trying to access .data on a GameObject not on a Enemy1 object?

solemn fractal
#

oh

vast yoke
ruby python
gaunt ice
#

you want to lock the mosue cursor inside the area of ground projected to scene?

languid spire
#

As I said, you need to get a reference to the Enemy1 script from the GameObject and, tbh, if you do not know what a reference is you should be following some basic c# tutorials not trying to make a game

gaunt ice
#

i think this is impossible, but you the position of crosshair can be unchanged if the ray is not hitting the ground

ruby python
languid spire
#

so that you can assign to it's .data variable

ruby python
#

@vast yoke

gaunt ice
#

yes impossible, mouse position is data that the OS given to unityengine, so you can just clamp the position of crosshair

ruby python
#

Ah okay. Think I thought of a way around it though.

reef patio
#

im having trouble!

#

my character third person isn't activating

#

those are the error problems

#

can someone help please?

languid spire
#

no.
Imagine a GameObject is like a book and you want to write on page 10 of that book
At the moment you are trying to write on page 10 without having opened the book.
If you want to write to page 10 you need to open the book to page 10, then you can write

vast yoke
ruby python
ruby python
reef patio
ruby python
#

!code

#

oookay, why that not work?

languid spire
#

Sorry, I cannot help you further. You need to learn a lot more about C# and Unity because you just do not have enough understanding about what you are doing. Please go and follow some basic tutorials

reef patio
#

its my first time getting a character module to work in my own level, aside from a capsule, it would be tough

#

the code looks like its running fine

ruby python
#

Yeah the error basically means that the script can't find something it needs. Can you show the inspector for that script please?

reef patio
#

ok

languid spire
#

It is only hard to understand for you because you have no knowledge of the basic fundamentals, these things you need to learn first

reef patio
ruby python
#

Okay, you haven't assigned your Input Module or Camera in the inspector.

reef patio
reef patio
#

which one?

ruby python
#

I don't know anything about the new input system I'm sorry so I don't know. 😕

#

But that would make sense.

reef patio
#

im not sure where the input is located at

ruby python
#

Based on the name that's for UI stuff. But honestly I don't know. 😕

#

try it, see what happens. lol.

reef patio
#

does anyone know what to do?

ruby python
#

Drag it in, and ddrag in your camera and see what happens.

reef patio
#

drag what?

#

i added the camera to the inspector

#

the main camera

#

but the ui

queen adder
#

Hey guys.
I made a plane water in Blender 3d, I want the water to be endless in Unity. How do I achieve this? The water is also meant to be animated, which is done through the animations in Blender. Is this possible?

Do i animate the block in blender or in unity?

ruby python
ruby python
reef patio
#

ok done

#

what next?

ruby python
#

run it

reef patio
#

the character did not progress to moving around

queen adder
ruby python
#

I think that might be related to your input system, but tbh like I said I know nothing about it so can't help 😦

reef patio
#

oh man

#

I need to create a character to walk around and adventure through levels

ruby python
reef patio
#

does anyone know how to do it?

verbal dome
verbal dome
ruby python
reef patio
#

ok ty ill be doing that as soon as possible

#

if anything comes problematic i will report here

solemn fractal
#

Hey guys, If I have an Enemy Prefab using a EnemyAI script. I also have a ScriptableObject Script with some variables, like life, damage, etc.. If I want each enemy to have a dif speed and movement variations, should I implement the move() method in the EnemyAI or in the ScritableObject?

teal viper
#

ScriptableObjects are mostly for immutable data.

solemn fractal
# teal viper Definitely EnemyAI.

Ok, I already have it there. and that is the code ```cs
private void Move(){

    Vector3 MoveDirection = _player.transform.position - transform.position;
    MoveDirection.Normalize();
    _rb.velocity = MoveDirection * _enemySO.speed;

}``` the problem is each enemy  have a dif speed, so when I instantiate 2 dif enemies, how do I do in the _enemySO.speed to get the speed of the dif enemies? as you see here for instance, anemy1 has 2 speed but enemy2 has 4... and if the method is in the EnemyAI I am sayingjust to get the speed, and how does he know if its speed from enemy 1 or 2 ?
teal viper
eager elm
teal viper
inland cave
#

uhmm hello guys uhh if i had a problem which channel do i chat?

#

like... unity got error

solemn fractal
teal viper
# solemn fractal

Well you're halfway through. You just need to use the other SO in the array as well.

teal viper
#

Ah, wait. Didn't notice that error.

#

You need to get the enemy component from the newly instantiated enemy object and assign the SO to it.

teal viper
solemn fractal
teal viper
#

You need to use GetComponent on the enemy object. I feel like there are some C#/unity basics missing...

solemn fractal
teal viper
#

Yeah, I have a really strong urge to just send you to learn
!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

teal viper
eager elm
# solemn fractal

firstly, I would change

private GameObject _enemySO;
to:
private Enemy1 enemyPrefab;

Then you need to reassign it in the inspector, drag your Enemy prefab (not the SO) into this field. Now when you spawn them;

Enemy1 enemyClone = Instantiate(enemyPrefab);
enemyClone.data = listOS[0];
solemn fractal
#

I thought here was a place to help people that are beginner and starter in coding with unity, Sorry, will try 750h of course to get my answer. and in some weeks I am back here again to ask you. Thank you for your time.

solemn fractal
#

Have all a great day and lovely weekend

inland cave
#

wait i got the same problem as them

#

how do i fix it?

teal viper
reef patio
#

Hello, I am stuck in a coding part from the section of the link

#

it has 3 errors, that the code it provided had errors in it

solemn fractal
# teal viper This is a place to help people after they made some effort. These are all very b...

3 days trying non stop, if that is not effort, waking up 7am and going up to 16h with unity open and trying to solve my issue, while I search google, discord and other sources, You think I opened unity and asked questions here? I am days trying something, that is why I asked here. I just come here after trying for a long time, also because its nice to try hard . that makes u learn better.. but you are not here to see how much effort I did before making those questions, you are just assuming i didnt do any effort. I already programmed games in java and other ways but Unity is Unity with its own ways to do stuff, and I am not yet used to it.

slender nymph
slender nymph
reef patio
slender nymph
#

okay and do you have a type or namespace called Controls somewhere?

reef patio
#

yes

slender nymph
#

where

reef patio
#

line 5 / 12 and 19

slender nymph
#

no, those are attempting to use that type. where have you defined it?

wintry quarry
#

Spoiler: they haven't

short hazel
#

Looks like an Input Actions Asset

#

Might have named it something else

reef patio
#

after monobehaviour, private, and controls

short hazel
#

Or not ticked the "Generate C# class" checkbox

short hazel
#

This seems like it's a class generated from an Input Actions Asset (from the new input system package)

reef patio
#

its a file known as controls.inputactions

short hazel
#

Make sure you named it Controls, otherwise it won't find it in your code

#

With an uppercase "C"?

reef patio
#

in the assets

#

yes uppercase

short hazel
#

And did you save the asset?

reef patio
#

ok ticked it

#

the save is autosave in the script

short hazel
#

Okay ticking the check box will generate the class Controls for you, so you will be able to use it now. Go back to your code

slender nymph
#

they may need to eliminate any compile errors before it will actually generate the code

reef patio
#

ok success

#

thanks boxfriend

solemn fractal
slender nymph
solemn fractal
slender nymph
#

outright refusing to actually do some learning and just throwing your face at a problem for 3 days as a result of not learning and still refusing to learn is not effort. it is laziness. if you do not even put in the effort to learn what the fuck you are actually doing, does it really count as being a beginner? because you haven't even begun yet

#

it's okay though, you don't need to bother replying. i have already blocked you and do not intend to offer you help

solemn fractal
#

No problem my friend, 17k people on discord to help with future problems. You are just 1 angry guy, I will not miss it.

modest dust
calm osprey
#

is there a simple way to connect an empty to an already animated object? so that it would move with it?

slender nymph
#

make it a child of that object. or use a ParentContstraint or PositionConstraint component

solemn fractal
# modest dust I haven't been in this discussion but from what I can see... 750h is **everythin...

Can I be honest? I completed a 3 months Java Bootcamp, and worked in the area for 1 year. But unity has its own terms and ways to do stuff I am just not yet used. I created very complex games only with Java. I also just completed a 200h course in unity from Udemy and created 3 games with it.. even tho what I am trying to do now I didnt learn yet and all the material I got I still cant understand.. that is why I came here, but people as this guys and others try to assume things and judge without knowing. But its fine . for him to get angry like that easly surely he is not in good vibes and I which him the best 😄

modest dust
#

I couldn't care less about Java, this is Unity and C#, my previous statement still stays

azure zenith
#

I am unable to use shortcut keys to comment out code

slender nymph
fossil drum
slender nymph
solemn fractal
# modest dust I couldn't care less about Java, this is Unity and C#, my previous statement sti...

That is why I completed a 200h unity course now, but was not enough it seems. And if after 200h course and days trying to do something not enough to ask questions here.. this chat should be calloed Code-medium to advanced. If for me to be a beginner means to have almost 1000h course in videos, its fine I will be back here in 1000h videos and hope people dont judge me and are willing to help.. actually a lot are willing to help.. I just dont understand why people bother saying stuff to me if they dont want to help.. just dont say anything and let people that really want to help.. help as @eager elm just helped me some minutes ago and fixed my prob in 1 answer while others sent me 1000 answers with no help and just judments .

short hazel
#

Gruhlum helped you because they gave you the code to write

solemn fractal
#

yeah but now I understand what was the prob

#

I see the code, and the connection.

#

and BUM i know what I did wrong. next time I know how to do it.

modest dust
solemn fractal
#

Not answers like go watch 700h video or pseudo code that for a beginner is not easy most of the time to get it. and if 1 beginner gets faster than others, that makes us humans.. being dif

short hazel
#

You need to learn how to translate words into code on your own, this is extremely important

calm osprey
short hazel
#

Having the basics is pretty much required to tackle a complex framework like Unity. That's why you either learn C# alone then switch to Unity, or go through Unity Learn that will introduce you to the basics of C# in a Unity context

modest dust
short hazel
#

Completing a 200-hour course that in terms didn't teach you anything means that either the course was way too advanced for you, or you did not reproduce what they did in the course enough to integrate it in your brain, or you did not pay enough attention

slender nymph
reef patio
#

hello again, i had gotten to this part of the learning section, and hes not moving, my character is still at game play

#

does anyone know how to fix it?

frosty hound
#

Your game is paused

slender nymph
#

and the CC component is much lower than the mesh

reef patio
#

whats that mean?

solemn fractal
short hazel
#

It will be a "watch a tutorial" for as long as you don't do so, or not have the basics in mind

#

Not sure what you should be "afraid" of either

languid spire
solemn fractal
short hazel
#

People are here to help, not scare you away. You think you're "afraid", but you're just misinterpreting the kind of help we give out here

#

We don't give you code that just works, we help you with your existing code only

silver dock
#

So as you can see there's two colliders on the rat, one at the top, one to the side, and the cat clearly touches the top one first while jumping on top of it, which means the the rat object should be destroyed cus thats what i did with the script, and it cant collide with the other collider anymore. But the cat is touching the second collider as well thus loading the gameover scene, so how can it touch the second collider if the first collider destroys the gameobject?

slender nymph
#

collision messages will be sent to the parent rigidbody. if the script that loads the game over scene is on the parent object then it's OnCollision method will be called too

reef patio
#

what do i do?

solemn fractal
#

Ok, so lets try again. As per documentation, as per google and even other sources, if I use a scriptable object and inside of it I have this variable cs public Color color; I should be able as per image to change the color of the sprite. When I instantiate 2 dif enemies it is getting correctly all the other variables and its working great. But the color even being dif is not being applied. This color doesnt overlap the prefab color? It is using always the prefab color and not the one I choose in the SO, even tho all the other variables are working great in those 2 enemies. just the color is not working.. both have red color, even they acting dif with dif speeds etc.

reef patio
#

does anyone know hwo to get this character model moving?

#

I did all of the instructions needed

#

and he doesnt go

#

"spacesuit"

zenith cypress
final kestrel
#

https://hatebin.com/rwfhuizfje Hey all. I have this script that is responsible for my character to jump. When the player is on the move and it tries to jump. The forward velocity gets interrupted somehow and its almost in a stopped position. How can I fix this?

fossil drum
hazy folio
#

whats the best way to have tight character controls?

#

i dont remember if i asked previosuly but i haved tried manually settign the velocity and quite a while ago i also tried using drag

#

but im noot sure what the implications of this would be (glitchy behaviour, hardships of managing, etc) because i want to make an actual game worthy of publishing but im still pretty much a beginner and not too used to proper development processes

solemn fractal
final kestrel
zenith cypress
#

Full black = no alpha

solemn fractal
final kestrel
#

Jump seems fine.

silk citrus
#

Hello there, I am building a multiplayer game where I need to display players avatars in the game, so I made this ImageDownloader class :

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class ImageDownloader : MonoBehaviour
{
    private Texture texture;
    public Texture downloadedTexture => texture;
    private System.Action<Texture> onDownloadComplete;

    public void Download(string url, System.Action<Texture> onDownloadComplete)
    {
        this.onDownloadComplete = onDownloadComplete;
        StartCoroutine(GetTexture(url));
    }

    private IEnumerator GetTexture(string url)
    {
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
        www.SetRequestHeader("Authorization", "Bearer " + GameManager.Instance.authorization);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Couldn't download image from " + url + " (" + www.error + ")");
        }
        else
        {
            texture = ((DownloadHandlerTexture)www.downloadHandler).texture;

            if (IsTextureSizeTooLarge(texture))
            {
                texture = ResizeTexture(texture, new Vector2(512, 512));
            }

            onDownloadComplete?.Invoke(texture);
        }
    }

    private bool IsTextureSizeTooLarge(Texture texture, int thresholdWidth = 512, int thresholdHeight = 512)
    {
        return texture.width > thresholdWidth || texture.height > thresholdHeight;
    }

    private Texture ResizeTexture(Texture source, Vector2 newSize)
    {
        Texture2D resizedTexture = new Texture2D((int)newSize.x, (int)newSize.y);
        RenderTexture rt = RenderTexture.GetTemporary((int)newSize.x, (int)newSize.y);
        Graphics.Blit(source, rt);

        RenderTexture previous = RenderTexture.active;
        RenderTexture.active = rt;

        resizedTexture.ReadPixels(new Rect(0, 0, newSize.x, newSize.y), 0, 0);
        resizedTexture.Apply();

        RenderTexture.active = previous;
        RenderTexture.ReleaseTemporary(rt);

        return resizedTexture;
    }
}

However when I try to download and display large images (like 3000x3000) it freezes the game for a short time, less than a second I would say (It drops from 100 FPS to 15). I thought using a coroutine would prevent this issue but it doesn't seem so. Using the profiler shows me the following. Is there any way to prevent that? Using a background worker or something?

fossil drum
final kestrel
#

how can I prevent this? maybe using clamp?

fossil drum
#

Well to be honest, the drag doesn't matter much when you force the velocity this way I think. Unsure about that part.
Yeah, clamping is possible.

teal viper
#
  1. Coroutine still executes on the main thread. It can just help you break down complex processing into several frames. But in your case, there isn't much to break down. Half of it seems to be resizing the texture, while the other half is creating new sprites and stuff. Maybe you can break these 2 things into separate frames.
  2. From what I can see your player loop is already busy enough without that coroutine. It only takes 13 ms out of 32. That means that without it your player loop is 19 ms, which is already lower than 60 fps. Might want to optimize your player loop in other places too.@silk citrus
buoyant knot
teal viper
#

Most of the stuff that takes time in their screenshot is unity api that can't be run from a background thread.

buoyant knot
#

i agree with your approach

#

i think it needs to be taken off main thread

#

and if that operation needs to run all at once, then you need to break it up

silk citrus
silk citrus
teal viper
buoyant knot
#

Jobs let you split things into separate threads. Async lets you get off of coroutines, which need to get run alongside unity’s main thread

silk citrus
#

well that may slow down the PlayerLoop, maybe 0.5 seconds interval is too fast

buoyant knot
#

what

fossil drum
silk citrus
# buoyant knot what
    {
        while (!videoPlayer.isPrepared)
        {
            yield return new WaitForSeconds(0.5f);
        }

        isPlaying = true;
        while (isPlaying)
        {
            if (Mathf.Abs((float)audioSource.time - (float)videoPlayer.time) > syncThreshold)
            {
                audioSource.time = (float)videoPlayer.time;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }```
buoyant knot
#

i thought Time.deltaTime = fixedDeltaTime when in fixed update?

slender nymph
#

it is

buoyant knot
#

then Mr Jackson’s point doesn’t make a difference

fossil drum
#

Uh, its not? At 240 fps deltatime is 1/240, and fixedDeltaTime is 1/50

#

Or am I wrong on that part?

slender nymph
teal viper
buoyant knot
#

i mean that when you are inside of the fixedUpdate loop, deltaTime is set to be equal to fixedDeltaTime

fossil drum
#

My apologies then, ignore my comment.

buoyant knot
#

it’s better to write fixedDeltaTime for clarity, but is not needed

teal viper
silk citrus
teal viper
# silk citrus by running too often? I'm a beginner, that's why I chose this channel, I'm not s...

There's basically no processing done in that coroutine. Also that's not how "slowing the main loop works". If you yield for fixed periods like that, you'll just get spikes of lags(if there was anything that would cause them anyway).

I get that you're a beginner, which is why I'm trying to correct wrong assumptions. If you actually need help with anything, then provide more details on the issue and what you actually trying to achieve.

silk citrus
merry spade
#

quick question: what is better/more efficent:

  1. public variable
  2. private variable but changeable with a public function
teal viper
#

2 is better. Could use a Property too.

gaunt ice
#

most of coders prefer two
but if the setter is just setting the property then there is no different and i would just make it public

merry spade
#

ok

slender nymph
#

typically all fields should be private and you should only expose your variables to other objects through properties

merry spade
#

what do you mean through properties?

slender nymph
gaunt ice
#

i just dont understand what is the different between:

public int a;
vs
private int _a;
public set_a(int a){_a=a;}
public get_a(){return _a;}
```apart from a additional function call
slender nymph
#

the second is pointless since properties exist

merry spade
#

are properties default?

#

or do you have to make them by yourself?

gaunt ice
#

properties is compiled to some code likes second one

slender nymph
#

but it's typically about hiding implementation details and allowing you to change how those methods work without affecting the outward facing api

slender nymph
merry spade
#

not 100%

#

but they ar get and set and stuff

#

but you have to do them by yourselves dont you

slender nymph
#

what do you mean "do them by yourselves"?

gaunt ice
#

ofc if

public set_a(int a){_a=a;some other codes based on the new value of _a}
```then you should use setter
merry spade
#

you have to write the get and set function

#

its not there on default

slender nymph
#

public int MyInt { get; set; }
that's a property
it's an auto implemented property with a compiler generated backing field. but you can use a full property if you need that. all of this is described in the page i linked

gaunt ice
#

not default, since you can change the getter setter body

final kestrel
teal viper
merry spade
#

i dont understand are properties there or do you have to code them?

teal viper
#

Wdym?

merry spade
#

idk

teal viper
#

Properties are a language feature. They have a certain syntax.

#

It's like askind "are methods there or we need to write them?"

#

Of course you need to write them lol

merry spade
#

so you can just write "get var" in every script and get the public value?

mellow shuttle
#

why if is not in blue like it

teal viper
slender nymph
merry spade
#

i hear properties for the first time

teal viper
gaunt ice
#

getter setter is syntax sugar

private int a{get;set;}
```is 
```cs
private int _a;
public int a(){return _a;}
public void a(int _a){this._a=_a;}
teal viper
slender nymph
mellow shuttle
merry spade
slender nymph
spiral oak
#

Right?

teal viper
merry spade
#

no not tool

#

i mean

#

im not a native speaker

#

you know what i mean

#

it just does it for you

slender nymph
teal viper
merry spade
#

it writes the functions for you

mellow shuttle
spiral oak
slender nymph
merry spade
spiral oak
teal viper
# merry spade it writes the functions for you

It compiles the property as a getter/setter method, yes.
You'd be surprised how much the compiler does for you. Probably things you don't event suspect. But that's getting into low level implementation.

mellow shuttle
slender nymph
#

probably because the person who made that tutorial changed something in their project settings and also doesn't know wtf they are doing

merry spade
#

ok thank you i think i understand it a little bit more now

final kestrel
gaunt ice
#

idk if 0.1f in checkshpere is small enough
but if the velocity is not fast enough, in the next physical frame it may return true

final kestrel
#

Hmm I should play with the checksphere's size?

gaunt ice
#

yes maybe adjust it

#

it should < the displacement of each physical frame when you jump

final kestrel
#

made it .08 but still getting the same result

#

smaller than that would break the ground check

teal viper
#

Might want to have sort of a state machine. { Idle, Jumping, Falling}
You only play the sound when you transition from Idle/Falling to Jumping.

final kestrel
#

All right I will take a look at what a state machine is.

#

Thanks for the help

gaunt ice
#

are the player colliding with the ground? i think on collision enter/exit can be used for ground check

#

or if velocity change from (around) 0 to positive value then set the state to jumping

final kestrel
#

I solved it by doing as you said. It seems to be working fine now. Made the checksphere smaller. Then dragged it a bit more below the player.

queen adder
#

Guys, I made a model in Blender, and I want the character to blink, but the thing is the eyes are part of the texture skin, is it possible to make the texture animated for opening and eyes closed? Or should I just make the eyes a 3d model and animate them open and closed?

verbal dome
queen adder
verbal dome
#

I doubt any of this will cause any 'lag' that you should be concerned about

#

3d animating the eyes could mean a few things too. Like is it an anime character or realistic or what

polar acorn
swift crag
#

the answer is probably "neither" if you don't have hundreds of characters on screen

neon ivy
#

I'm following a tutorial about a save and load to json system but I'm changing it so it saves classes instead of individual variables so it's more organized, I swapped from JsonUtility to Json.Net and tried to do this:

[System.Serializable]
public class GameData
{
    public InventoryData playerInventory;

    //set initial values here
    public GameData()
    {
        this.playerInventory = new InventoryData();
    }
}

which gave an error because InventoryData is a monobehaviour so you can't just make a new one without putting it in the scene somewhere, I'm wondering if anyone has an idea to still do something like this without turning the InventoryData into a normal class.

slender nymph
#

make inventory data a plain c# object. then pass that to some inventory monobehaviour

neon ivy
#

that also works I guess, thanks

polar acorn
neon ivy
#

I thought that would be the easier way of doing it

#

but making an inventory holder should be fine

swift crag
#

You might make a MonoBehaviour for a component that talks to an inventory

#

e.g. a chest would have a Container component that has logic for interacting with the container

#

but the inventory itself wouldn't need to be a unity object

neon ivy
#

true

#

it basically just holds data

#

nothing more

prime oar
#

I have been trying to get a simple plane with multiple vertices in my game. The thing is that the primitive plane doesn't have a parameter where you could adjust the number of vertices.
I tried looking for a solution on the internet, but it is impossible to find an easy solution.
Any ideas?

prime oar
polar acorn
teal viper
#

Too broke for free. Need something that would also pay money for using it.😅

prime oar
fossil drum
queen adder
#

Do i animate my character in unity or in blender? I made a character in Blender and it's fully rigged. It will just act as npc and have an animation. What's the best way to do this?

wintry quarry
queen adder
#

Thank you! 🙂

calm osprey
# queen adder Thank you! 🙂

I would very much suggest following Imphenzia's tutorial (the low poly cop thumbnail one) that includes the steps for creating necessary NLA strips and exporting the .fbx files from blender to unity properly.
helped me a ton when I had zero experience with working between blender and unity.

echo owl
#

My play button is Way too big, how do I small it down? Because now even when I click on white surface it activates

slender nymph
polar acorn
#

Make it smaller

silk night
polar acorn
#

Show code

silk night
#

BulletView.cs

        private void OnCollisionEnter(Collision other)
        {
            Rigidbody.useGravity = true;
        }

PlayerShootingSystem.cs

namespace InfinityShooter.Shooting.Systems
{
    public sealed class PlayerShootingSystem : IExecuteSystem
    {
        readonly Contexts _contexts;
        private readonly IGroup<GameEntity> _group;
        private readonly List<GameEntity> _buffer = new List<GameEntity>();

        public PlayerShootingSystem(Contexts contexts)
        {
            _contexts = contexts;
            _group = _contexts.game.GetGroup(GameMatcher.AllOf(GameMatcher.Player, GameMatcher.Shooting));
        }

        public void Execute()
        {
            if (_group.count <= 0) return;
            
            foreach (var playerEntity in _group.GetEntities(_buffer))
            {
                var nextShot = playerEntity.hasNextShot ? playerEntity.nextShot.Value : 0;
                var currTime = Time.time;

                if (currTime < nextShot) continue;

                var bulletEntity = _contexts.game.CreateEntity();
                bulletEntity.AddPosition(playerEntity.position.Value + Vector3.up);
                var rotation = Quaternion.Euler(0, playerEntity.rotation.Value, 0);
                bulletEntity.AddDirection(rotation);
                _contexts.game.Instantiate(Res.Bullet, bulletEntity);
                
                playerEntity.ReplaceNextShot(Time.time + 0.05f);
            }
        }
    }
}
#

Nothing else in bulletview should be relevant, if you really want i can show the whole thing but its unrealted stuff

polar acorn
#

You might want to manually apply a bounce force. I'm not sure if changing useGravity causes the velocity to reset. It might be interfering with the Physics Material

silk night
#

What was the math for bouncing of a surface again? DotProduct of surface normal and object velocity?

silk night
#

Oh thats wonderful, thanks 😄

verbal dome
silk night
#

Had friction on both all the way up, it didnt really care for that

eternal needle
silk night
eternal needle
#

Could try bounciness on 1 and change the bounce combine option to like maximum or whatever the options is

#

Although if you want to visually turn the bullet too then I guess it's easier to do via code. Let's you implement more like a max bounce

verbal dome
#

Using a different collider shape is one thing to try too

silk night
#

the bullet fizzles out after hitting the wall, i dont want a ricochet like thing

#

so i dont mind much about rotation, it can spin out for all i care 😄

chilly moss
#

somebody help, i dont understand

short hazel
#

You need to configure Visual Studio so it works correctly with Unity

#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

short hazel
#

(this step is required to get help here)

keen dew
#

You also need to save the file

chilly moss
#

now it says this

gaunt ice
#

check the method name of ienumerator

sage mirage
#

Hey, guys! I have a question. I have a background music on my Main Menu scene and when the player enters the game he is transferred to the title scene. I have functionality where it says under my Title Text Press any key to start so when the player left click one time,main menu scene is loaded. The problem here is that when the player enters the main menu scene and everytime when he left click the background music of main menu is playing repeatedly. So, what I want to do is to click and get to main menu scene only one time and when I left click not to hear it playing repeatedly. Is there a way to left click only one time and not to hear background music on main menu after left clicking?

{
    // Initialization of some variables here!
    public bool gameIsActive = false;
    public bool isPressed = false;
    public Button quitButton;
    public Button playButton;
    public Button optionsButton;
    public Button pauseButton;
    public Button continueButton;
    public Button homeMenuButton;


    // Start is called before the first frame update
    public void StartGame()
    {
        gameIsActive = true;
        Debug.Log("The game started!");
    }

    
    void Update()
    {
        PressAnyKeyToStart();
    }

    public void PressAnyKeyToStart()
    {
        if (Input.anyKeyDown)
        {
            SceneManager.LoadScene("MainMenuScene");
            Debug.Log("MainMenuScene is loaded!");
        }
    }

    public void QuitGame()
    {
        StartCoroutine(PlayAfterTwoSeconds());   
    }

    IEnumerator PlayAfterTwoSeconds()
    {
        yield return new WaitForSeconds(0.5f);
        Application.Quit();
        EditorApplication.ExitPlaymode();
        Debug.Log("Game quits and editor play mode stops!");
    }


}```

Here is the script!
chilly moss
#

i accidentally misspelt generate lol

sage mirage
#

I know already what causes the issue. I have PressAnyKeyToStart() on Update. So, that's why I am asking is there a pre built method or something to add on my script and add that method to the pre built method? Also, I have to note that I have UI Manager gamobject as a prefab on my hierarchy.

short hazel
#

As if UIManager was persisted through scene changes, but that's not the case here

sage mirage
#

Yeah!

short hazel
#

Scene loading happens at the end of the frame, so you're 100% sure that the if statement in PressAnyKeyToStart() is executed once. Unless:

  • This script is present multiple times in the title scene
  • This script is present by mistake in the main menu scene
sage mirage
#

The case here is that I have the method I said on Update() method. So, when the MainMenuScene loads it repeatedly after left click and every frame is playing the background music I have on MainMenuScene.

short hazel
#

This is not an additive load so scenes will not stack

#

Note that when the Debug.Log("MainMenuScene is loaded!") runs, it's not actually the case just yet

#

All Updates will finish running for this frame, then the scene switch operates

sage mirage
#

I have UI manager script on every scene

short hazel
#

Well there you have it, you will reload the main menu each time you press a key

sage mirage
#

I have it on every scene on my UI manager game object prefab

short hazel
#

The "press any key" logic should be offloaded to another script that's only present in the title scene

sage mirage
#

I have made prefab of UI manage because I want to make every functionality of UI on specifically that script

#

@short hazel So, I have to remove UI manager script on my other scenes?

#

Let me see if that happens on other scenes as well like main scene

short hazel
#

No, you do the thing in the message you reacted "👍" with

sage mirage
#

Oh, so I have to make another script separately for that functionality?

#

Can't I make that functionality work on my UI manager script?

short hazel
#

No, and it shouldn't be the case

sage mirage
#

There is no other method for that?

short hazel
#

Something that's used once must not be put in a script that's used everywhere

sage mirage
#

Alright then thanks 🙂

short hazel
#

Apart from complexifying the code, and requiring you to modify the Inspector of your UI manager in each scene, the best method is still to use a separate script

swift crag
#

I have an entire component whose sole job is to be the "press any key" screen

#

i need to mark that "last selection" field as non-serialized..

sage mirage
#

So, when you are working on a project what do you prefer to do making one script to handle all your UI functionality for example or making different scripts for different things? I think you will say depends on the situation you have. I love making things on single specific scripts for example when I have to handle UI to make UI manager for all of that when I have Audio for example different SFX to be played or background music etc to have an Audio manager.

swift crag
#

I have an InterfaceController whose job is to turn on and off various interface components

#

a HUD, a set of game menus

#

the "you died" text

#

It would be a giant mess if all of those were literally just one script

quasi rose
#

The day I figure out a solid Unity workflow will be the day ❤️

calm osprey
#

hi, I created a public void that allows me to damage my character, but when I use it in another script it says it "does not exist in the current context"
I thought that's what public was for?

swift crag
#

clarification

#

you created a method

#

the method is public, so any class can see it, and the method returns void (so it returns nothing)

swift crag
#

both the definition of the method and the place you tried to use it

wintry quarry
#

it doesn't mean "you can now just use this everywhere willy nilly"

ruby python
#

Am I correct in thinking that there is a way to limit where you can move the mouse onscreen? (not cursor locking) More of a limited region of the screen where the mouse pointer can go?

polar acorn
swift crag
#

What do you want to do?

twin bolt
#

How do i check if a gameobject has a certain script?

swift crag
#

you can test for a component by trying to get it

#

ideally with TryGetComponent

twin bolt
#

okay

swift crag
#
if (!foo.TryGetComponent(out SomeComponentType _))
{

}
#

you can use _ to discard the result, since you don't care about it

short hazel
#

Even out _!

swift crag
#

oh, you can omit the type for a discard?

polar acorn
swift crag
#

oh yeah, you can

#

neat

#

true, so it wouldn't be a huge gain there

sage mirage
#

Hey, guys! If I want my background music of my main menu scene to not play repeatedly after the load of another scene for example I want to go to options scene and I have the same backround music that is playing. So, I want that music to be played continuously. Is there a function to make it work without loading the music again and again?

polar acorn
#

it needs the type either from the generic parameter or the type of the out parameter

ruby python
#

@polar acorn@swift crag okay, basically. I have a plane on the ground receiving a raycast, my character then targets the raycasts hit.point. I'd like a decent solution to 'locking' the cursor to a specific region, but my current solution sucks bottom. lol.

short hazel
#

idk if it really treats it as a discard when you specify the type name in the out param? Will check

swift crag
ruby python
#

The actual scene........

swift crag
#

The mouse cursor will still move around freely.

#

Imagine trying to move the cursor to the top right corner. If it couldn't go out of bounds, you'd be forced to move it left, then up

ruby python
#

Yeah, I've been turning the cursor 'off' when it leaves the bounds of the plane object, but it looks horrible (character just 'locks' up and then 'snaps' when the mouse comes back in.

swift crag
#

you could find the closest point that's still in-bounds (realtively easy for a plane, I'd think)

ruby python
#

I'll take a look tomorrow. Had enough of it for today. Bit of Particle Play for a bit I think. lol.

swift crag
#

raycast to the plane, then clamp its X and Y coordinates based on the playable area's size

unreal imp
#

Can you guys help me with this? I have a problem that my bullets don't always spawn in the same spot on the sight as you can see in the video.
Here is the code (I was trying to get the bullets to come out of the gun but focus on the raycast): ``` private void Shoot()
{
// Create a ray from the camera going through the middle of your screen
Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;

    // Check whether your are pointing to something so as to adjust the direction
    Vector3 targetPoint;
    if (Physics.Raycast(ray, out hit))
        targetPoint = hit.point;
    else
        targetPoint = ray.GetPoint(1000); // You may need to change this value according to your needs

    // Create the bullet and give it a velocity according to the target point computed before
    var bullet1 = Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation);
    bullet1.GetComponent<Rigidbody>().velocity = (targetPoint - muzzle.transform.position).normalized * shootForce;
    
}```
#

sometimes like happens on the video the bullet is generated down of the screen or far where is pointing the raycast

slender nymph
#

well the bullets get instantiated at the muzzle object's position. so take a look at where that object is

#

also that code is suspiciously GPT-like

timber tide
#

bot writes more comments than I do in a single script than I do for my whole project

halcyon hearth
#

Hello, I have a problem regarding sprites. I have a character that is made up of several sprites. all with the pivot below and in the center, all MUST be in Order in Layer 2.

This is because the game is a top down game and the camera orders everything in Y, and thus there is depth with the other objects, and if each part of the body has different orders, that would complicate things for the camera.

So, what do I do to be able to tell the game which character sprite should go first? Any way to do it through code?

timber tide
#

Uh, I think those layers are subdivided, such that sort layer 0 is the first layer, but then the layer numbers is that of the specific layer

slender nymph
#

you know you can also use other sorting layers, right? then you can adjust the order in layer for each individual sprite on the layer

#

also not a code question

timber tide
#

Can make it a coding question if you want to code in your only sorting layer manager ;)

#

basically it's just changing the z-depth by minuscule numbers

halcyon hearth
slender nymph
#

what do you think the order in layer does?

#

it's the same thing, but within a specific sorting layer

halcyon hearth
unreal imp
halcyon hearth
#

And here what happens if I put the clothes and the hair in layer 3, and the body in layer 2. The body does follow the top down system, since all the other objects are also in layer 2, but the hair and clothes they ignore it and put themselves on top

slender nymph
slender nymph
halcyon hearth
slender nymph
unreal imp
slender nymph
#

they aren't going from the gun. they are going from the muzzle object. where is that

unreal imp
#

In the point of the gun you know like all shooters

#

not in the center of the body of the player

#

Or the camera

slender nymph
#

and have you bothered actually paying attentiont to where that object ends up the times that the bullets do not fire from the gun?

#

because that is my whole fucking point

unreal imp
#

So the a viable option is to make the muzzle pointing by rotation to the crosshair?

slender nymph
#

what?

#

i'm telling you to pay attention to where that object is when this issue is happening

unreal imp
#

Ok

#

wait I think I know the problem

silk night
# polar acorn You don't need to do the math, there's a function for it: https://docs.unity3d.c...

https://img.sidia.net/ZEyI5/ViloWIna61.mp4/raw works perfectly now, finally got back to it

        private void OnCollisionEnter(Collision other)
        {
            if (_hit) return;
            
            Rigidbody.useGravity = true;
            
            var dir = Vector3.Reflect(_velocity, other.contacts[0].normal);
            Rigidbody.velocity = dir.normalized * _contexts.config.gameplay.WallBounceStrength;
            Rigidbody.rotation = Quaternion.LookRotation(dir.normalized);
            
            D.raw(new Shape.Line(transform.position, transform.position + dir.normalized * 4), Color.green, 2f);
            D.raw(new Shape.Line(transform.position, transform.position - _velocity.normalized * 4), Color.blue, 2f);
            
            _hit = true;
        }

Ill reduce the bounce and let it spin a bit and that should work for fizzling out then 😄

unreal imp
#

or when i spam click the gun

slender nymph
#

okay. so have you looked at where the muzzle object is when those things happen?

unreal imp
#

it's in the same place correctly but I'm worried about this piece of code var bullet1 = Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation); bullet1.GetComponent<Rigidbody>().velocity = (targetPoint - muzzle.transform.position).normalized * shootForce;

reef patio
#

can someone help me with the input third person system, I have a lot of it done, but he doesn't run?

silk night
#

Please post your code and tell us which part of it does not work

reef patio
#

all the code isn't at error in the scripting part

#

i can show screenshot of what it is set to though in the inspector

silk night
#

yes please show everything relevant, we cant help you without any context

reef patio
silk night
#

So when you press buttons nothing happens?

reef patio
#

yes

slender nymph
reef patio
unreal imp
reef patio
slender nymph
silk night