#💻┃code-beginner

1 messages · Page 20 of 1

devout hull
#

My friend and I are trying to create a game similar to flappy bird, but we’re having an issue where the bird doesn’t die when it falls below the camera or goes too high up. Is there a way to fix this?

#

We’re also experimenting with triggers and trying to get them to work

slender nymph
random sand
#
{
    public PlayerController playerController;

    private void Start()
    {
        playerController = GameObject.FindObjectOfType<PlayerController>().GetComponent<PlayerController>();
    }
    private void OnCollisionEnter(Collision collision)
    {
        playerController.isGrounded = true;
    }


}

Trying to detect if 2 objects are colliding with each other but doesn't work. Both objects have colliders. Please help visualstudio

teal viper
random sand
devout hull
#

We have tags and what not on the objects

#

Sorry this is literally our first day coding lol we don’t know what to look for rly

slender nymph
#

so you've tried nothing and are all out of ideas?

devout hull
#

It’s not that we’re out of ideas we don’t know how to use the ones we have

#

We tried google

#

It didn’t help very much

slender nymph
#

start by learning the basics. if you already know c# then do the unity !learn pathways. that will teach you the basics of using unity including things like collision detection

eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

slender nymph
#

and if you are not very familiar with c# then start with the beginner c# courses in the pins

devout hull
#

Oh cool thanks

random sand
slender nymph
#

does the plane have a collider?

random sand
#

yes

#

no rigidbody though

#

the other object has a rigidbody

slender nymph
#

provided at least one of the objects has a rigidbody then physics messages will be sent to both

#

however it seems like you are doing ground detection and this is honestly a pretty poor way of doing so. i'd recommend looking into using a raycast or some other physics query (like an OverlapBox or OverlapSphere) instead of relying on physics messages

teal viper
slender nymph
#

what happens if you use OnCollisionEnter/Exit for ground detection but you are moving along the ground, suddenly touch another ground object (without fully exiting the current ground object you are already touching) then move away from that other ground object? you're suddenly no longer considered grounded, unless you go and track all ground objects you are currently touching.

#

you would also have to design your objects so that they are only considered ground on the very top of the objects since side collisions would still send physics messages. unless you're also checking where on the collider you hit

#

but then you're just doing more work than it would take for a simple physics query in a small area directly below the player

teal viper
#

Hmm... I guess these are valid points. Never thought about it, since I rarely deal with physics based movement.

obsidian parcel
#

hi, do any one know how to share the unity project without sharing code

#

like hide the code or something

random sand
# obsidian parcel hi, do any one know how to share the unity project without sharing code

This video explains the entire export process to three different platforms.

♥ Support my videos on Patreon: http://patreon.com/brackeys/

····················································································

● Download Inno Setup: http://www.jrsoftware.org/isdl.php

● Mac App Store: http://bit.ly/2oMHziY
● Mac DMG: http://bit.ly...

▶ Play video
obsidian parcel
#

not build but i want to give the full unity project but not code

polar acorn
obsidian parcel
#

ya

polar acorn
#

You can't

obsidian parcel
#

like their are dlls but the process is kinda lengthy

polar acorn
#

That's the closes you're going to get

#

but that's just code

#

It's not a project

#

It's a library

obsidian parcel
#

is thier any other way to hide code instead of dlls?

polar acorn
#

No

#

Not if you want it to be useable

random sand
#
{
    public PlayerController playerController;

    private void Start()
    {
        playerController = GameObject.FindObjectOfType<PlayerController>().GetComponent<PlayerController>();
    }
    private void OnCollisionEnter(Collision collision)
    {
        playerController.isGrounded = true;
    }


}```
Trying to detect if 2 objects are colliding with each other but doesn't work. Both objects have colliders. Please help
obsidian parcel
#

okay

#

do one have rigid body

random sand
#

Using this for ground detection

polar acorn
rich adder
#

this is redundant .GetComponent<PlayerController>();

random sand
polar acorn
eternal needle
polar acorn
#

That's redundant

#

You're getting the component from itself

#

Just use the component returned by the find

random sand
random sand
eternal needle
random sand
rich adder
polar acorn
random sand
#

could i implement like a raycasting thing on an active ragdoll

eternal needle
#

yes

#

infact itll be harder to rely on your current method using an active ragdoll

random sand
random sand
polar acorn
#

Lots of vectors for stuff to go wrong

random sand
eternal needle
# random sand wait sorry for disturbing you but why would it be harder?

for one, you would have to care about niche cases like what boxfriend described #💻┃code-beginner message
but with an active ragdoll things get very weird, like for one would you consider your ragdoll grounded if the chest was lying on a surface but all limbs were dangling off the edge of that surface?
If yes: then all your limbs now have to use collisions and check if any of them are grounded and what they are touching.
If no: your character will be stuck on that surface and you have to add an additional way to free it somehow

#

it really is a lot easier when you just raycast down from the hips, if theres nothing directly below the hips then its very likely you shouldnt be standing upright

random sand
#

wait nvm

#

sorry for asking dumb questions i'm a beginner

eternal needle
#

that also does lead to another niche case, something i faced as well. If you only raycast down from the hips, well you'll run into cases where you are grounded and may have logic running if(grounded) then allow movement. But if the ragdolls feet arent in the proper walking position then it wont exactly make sense what to do. Tldr: Active ragdolls are extremely hard tbh, its clear why they arent common in games. you may even see active ragdoll talks online, then it turns out the person is just using animations to drive the main body anyways 🤷‍♂️

#

not trying to deter you from it, but consider if you really need an active one because its really a major pain

random sand
#

i've looked into different types of active ragdolls, would an animation driven one be better?

eternal needle
# random sand i've looked into different types of active ragdolls, would an animation driven o...

the basic idea for what i consider a real active ragdoll is one that just moves without animations on the main body. It may try to copy another bodies current rotations (who is driven by animation). This would allow it to react to getting hit by something like the arm or head may swing back from the force
When you use animations directly on the main body, this wont happen because animations will override the rotations

random sand
eternal knoll
#

hi, if i want to add a list/array to the firebase, what kind of tutorials should i be looking at?

eternal needle
eternal needle
eternal knoll
eternal needle
#

im pretty sure i always used the firestore database and not realtime but this was just for school projects some time ago

eternal knoll
#

i am new to this

#

the vids i have watched are just ppl inputing random values/one variable to the database, not a list or array

eternal needle
shell ice
#

Don’t know if this would be with code or not but I’m trying to setup my hands for vr and they are lying horizontal on top of where my controller sits and not in a normal resting hand position

rich adder
#

wdym no work

#

this is just a ray, not a raycast

#

and debug would only show if u have gizmos enabled

random sand
#
        {
            Ray ray = new Ray(transform.position, Vector3.down);

            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, raycastLength, groundLayerMask))
            {
                print("Distance to ground: " + hit.distance);

                if (hit.distance < 4.9f)
                {
                    Bone.AddForce(new Vector3(0, jumpForce, 0));
                }
            }
            else
            {
                print("Ray did not hit the ground.");
            }
        }```
how can i make better ground detection? this is what i have so fat
rich adder
random sand
rich adder
#

you only raycast when you tap spacebar

random sand
rich adder
random sand
# rich adder yea in Update

would that make it less efficent because i only need the ray to check if my character is touching the ground

rich adder
#

not sure what you mean "less efficient" ?
maybe look at some example online, you'll see

summer stump
#

You can do a ton of raycasts every frame no problem

timber tide
random sand
#

but how does it reduce functionality?

random sand
summer stump
lunar root
#

Hi, I'm making a 2d topdown game and I am currently trying to use a blend tree to have 4 directional idle and movement animations, though I don't know how to do this. Help would be much appreciated.

topaz mortar
#

How do I find an unrelated empty object and call a function from a script on that object?
In my Item script I want to access the Combat script (which is sitting on an empty object) and call a function DrinkPotion there

burnt vapor
#

So the thing you need to figure out is what Combat script should fall under. Perhaps it's a singleton, or are there multiple instances?

#

Perhaps you need a general manager for these things, which contain a reference

topaz mortar
#

I'm just testing my inventory and want to get this to work quickly

#

need to rework the whole combat system anyway

#

but all this reference stuff is too complicated atm

burnt vapor
#

Part of the learning process I'm afraid. Doing stuff quickly is almost never the right way when you're still learning

topaz mortar
#

I got this, but it doesn't work:
Combat combat = GameObject.Find("CombatScript");

#

ah nvm found it 🙂

#
if (combat != null)
    combat.DrinkPotion();```
burnt vapor
#

That is the exact way to not find an object

random sand
#

anyone know how to rig an already imported model?

burnt vapor
#

If you read the page, you would have noticed this should only be used for debugging, and not for actual use in your game

#

It's slow, unreliable and just all around bad. You should find another way @topaz mortar

#

Don't cut corners just because you want to implement it quickly

topaz mortar
#

I'm just testing my inventory system

#

it doesn't work though, throws an error: NullReferenceException: Object reference not set to an instance of an object

unique falcon
#
    {
        Debug.Log("LookAround");
        Collider2D[] colliders = Physics2D.OverlapCircleAll(this.transform.position, sight);
        foreach(Collider2D coll in colliders)
        {   
            Debug.Log(coll);
            if(coll.tag == "Flower" && coll.transform.parent.gameObject.GetComponent<FlowerController>().color == colorPreference) 
            {
                target = coll.transform.position; 
                return;
            }
        }
    }```

I must be missing something obvious here. Unity is throwing a null reference exception at the "if" line.
burnt vapor
#

And this can have multiple reasons, and it's unreliable

#

See why I suggest you don't use it? 🤔

#

With debugging, this mostly relates to finding gameobjects ina more dynamic fashion. Right now it's part of your actual game behaviour and you should in fact not use it there.

#

So please read through the page instead of trying to fix something you should not use to begin with

#

What you want most likely is a singleton

topaz mortar
#

probably, but that would be in my combat system, which is not implemented at all right now

#

and I want to finish my inventory system first

burnt vapor
topaz mortar
#

Meh, I just put in a Debug.Log so I know it works for now 🙂

lunar root
#

I'm trying to do 4 directional movement, but the animations are still janky. Here is my code: https://pastebin.com/Lw8Maeu3. Help would be much appreciated.

neon ivy
#

I have a width and height, and I need it to be filled with square pixels of which the size depends on a float, but I have no idea how to not leave gaps at the sides....
the aspect ratio is currently 11:8 but if that makes it hard I can turn it into 12:8 for a 3:2 aspect ratio.
does anyone know how to do this math? UnityChanPanicWork

queen adder
#

Its hard to make run movment of center tiles? Where start?

silent valley
#

hi. This is for my pistol and the bullet comes out from the transform. do i need to make a new script for my shotgun which has bullets coming out of 5 transforms or is there a way to use this for it. Ie making the shotguns transforms a child or something. idk

fringe pollen
silent valley
#

I've done it like this which works but I'm 100% sure theres a way more efficient way

fringe pollen
fringe pollen
silent valley
fringe pollen
queen adder
queen adder
#

or rather: tile based movement there's a lot of implementations to it

#

ok, will check this video, thx

#

actually the video is wrong UnityChanOops

queen adder
polar comet
azure zenith
#

I need help

#

If you can help please tag me

#

Help

ashen ferry
#

multiply Vector3.forward it might be just too low of a force

polar comet
ashen ferry
#

is rigidbody dynamic?

polar comet
#

?

ashen ferry
#

click on rigidbody component and look for

#

I forgot the name bruh kekW theres a dropdown to set mode to rigidbody

azure zenith
#

I am unable to instantiate cubes

#

I will explain in more details if someone can help

gaunt ice
#

show your code please and just throw your question here

azure zenith
#

Instantiate(spawnCollectibleCube, newPos, transform.rotation);

#

This will not work

#

I don't know why

gaunt ice
#

is there any new GameObject appear on the hierarchy? something like: box (Clone)

azure zenith
polar comet
azure zenith
gaunt ice
#

show your !code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

ashen ferry
polar comet
#

Ok

#

I'll ask chat gpt

topaz mortar
#

Why am I getting this warning* and how do I fix it?
Copied the code from a tutorial but it seems to work fine, the error shows in the tutorial video too

burnt vapor
#

Or in other words, do not copy code and learn to write it yourself

polar comet
ashen ferry
#

no

#

if code is identical I cant answer why it will work in fixed update but not in update but you had to move it over anyways so thats a win ig

queen adder
#

!cs

eternal falconBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
topaz mortar
#

chat gpt is horrible at writing / debugging code
it will consitently give different answers and write just terrible code

gaunt ice
#

start with ```cs and end with```

queen adder
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

queen adder
#
private bool isMoving;
private Vector3 orgiPos, targetPos;
private float timeToMove = 0.2f;


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

// Update is called once per frame
void Update()
{
    if(Input.GetKey(KeyCode.W) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.up));
    }
    if (Input.GetKey(KeyCode.S) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.down));
    }
    if (Input.GetKey(KeyCode.A) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.left));
    }
    if (Input.GetKey(KeyCode.D) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.right));
    }

}

private IEnumerator MovePlayer(Vector3 direction)
{
    isMoving = true;

    float elapsedTime = 0;

    orgiPos = transform.position;
    targetPos = orgiPos + direction;

    while(elapsedTime < timeToMove)
    {
        transform.position = Vector3.Lerp(orgiPos, targetPos, (elapsedTime / timeToMove));
        elapsedTime += Time.deltaTime;
        yield return null;
    }

    transform.position = targetPos;

    isMoving = false;
}

how to increase move speed in this code?

azure zenith
#

Should objects have rigidbody for it to be instantiated?

gaunt ice
#

no

azure zenith
#

Why not?

gaunt ice
#

you can instantiate a empty GO (ie only the transform)

azure zenith
#

I added rigibody to the cube I want to instantiate everytime a new floor is instantiated but my unity editor freezes everytime I run the game

gaunt ice
#

dead loop, please show your code

azure zenith
#

Those two collectible cubes will instantiate

#

Then no more

#

I don't know what the issue could be

#

Adding rigidbody seems to work I think

#

But then my unity editor freezes

gaunt ice
#

then where is the triggered collider? you need to enter the triggered collider to spawn new GameObjects

polar comet
#

is AddForce only made for moving upwards and downwards

burnt vapor
#

It moves the rigidbody in the direction you specify

gaunt ice
#

rb is required for detecting onXXXEnter/Stay/Exit event (XXX=trigger or collision)

polar comet
azure zenith
#

My cube is child element of block

topaz mortar
storm pendant
#

hello! Quick one regarding strings...

if I have a string called "<incr>"+Text+"</incr>", how do I extract the 'Text' portion and disregard the <incr> </incr> modifiers either side?

burnt vapor
#

Or you look for the index of certain characters and work with that

gaunt ice
#

Ontriggerenter only runs once when you enter a triggered collider , so you need to move your ball leave the collider and re enter it

storm pendant
queen adder
storm pendant
#

also, should I be worried about adding too many 'Systems' at the top of my scripts? Notice this 'RegularExpressions' one needs me to add another one

distant current
#

can someone help me with what's causing this error?

burnt vapor
#

I should note that this does not cover all characters

storm pendant
burnt vapor
#

Yeah, Regex is weird. I just happen to need them quite a bit

#

In this regex you can find your text in a group by the name of text

#

I would generally advice against using Regex but if you're sure that the input is always this simple you can use it

storm pendant
azure zenith
#

I need help

burnt vapor
azure zenith
#

All I want to do is to instantiate cubes but it won't work. They say using the instantiate function is easy, well guess what, it isn't

#

There are a lot of things I want to clarify

#

Do I need another script for instantiating an object?

#

Or can I do it in the same one

gaunt ice
#

No

frosty hound
#

Scripts are irrelevant. You just need code. Where it goes is up to you.

gaunt ice
#

You can just put the instantiate code in ontriggerenter

azure zenith
#

Should an object that you want to instantiate on another object being instantiated be a child of that object?

frosty hound
#

No

#

It can be, it doesn't have to be

#

Instantiation just spawns something. Where and what is up to you. And how you organize it in the hierarchy is up to you.

queen adder
#
private bool isMoving;
private Vector3 orgiPos, targetPos;
private float timeToMove = 0.05f;


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

// Update is called once per frame
void Update()
{
    if(Input.GetKey(KeyCode.W) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.up));
    }
    if (Input.GetKey(KeyCode.S) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.down));
    }
    if (Input.GetKey(KeyCode.A) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.left));
    }
    if (Input.GetKey(KeyCode.D) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.right));
    }

}

private IEnumerator MovePlayer(Vector3 direction)
{
    isMoving = true;

    float elapsedTime = 0;

    orgiPos = transform.position;
    targetPos = orgiPos + direction;

    while(elapsedTime < timeToMove)
    {
        transform.position = Vector3.Lerp(orgiPos, targetPos, (elapsedTime / timeToMove));
        elapsedTime += Time.deltaTime;
        yield return null;
    }

    transform.position = targetPos;

    isMoving = false;
}

how to fix it, i dont want hold key to move. Want just one click and player self move

tawdry mirage
#

constantly move the player in fixed update or in update, only set movement vector when you get inputs

gaunt ice
#

You dont need to hold key to move, once you press the key the coroutine will start but you dont know when it ends

queen adder
#
void Update()
{
    if(Input.GetKey(KeyCode.W) && !isMoving)
    {
        playerDirection = Vector2.up;
    }
    if (Input.GetKey(KeyCode.S) && !isMoving)
    {
        playerDirection = Vector2.down;
    }
    if (Input.GetKey(KeyCode.A) && !isMoving)
    {
        playerDirection = Vector2.left;
    }
    if (Input.GetKey(KeyCode.D) && !isMoving)
    {
        playerDirection = Vector2.right;
    }

    StartCoroutine(MovePlayer(playerDirection));

}

this doesnt work ;/

modest dust
#

Well, you're calling the coroutine each frame

#

You'll be having tens and hundreds of the same coroutine trying to move the player at the same time

gaunt ice
#

Your coroutine doesn’t allow you change the player direction while it is moving, you have to hold the key until the player finishes its movement

modest dust
#

Also wouldn't playerDirection = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized be easier and shorter

modest dust
#

also the targetPos stays the same during the coroutine

gaunt ice
#

His previous code

modest dust
#

Well, still, it's not being set to 0 anywhere

queen adder
#

yes, but this code work perfect for me becaue i need grid tille movement, but dont want hold key

modest dust
#

it's just constantly changing to a bigger value

storm pendant
# burnt vapor Yeah, Regex is weird. I just happen to need them quite a bit

Hmmm...I'm having trouble trying to implement this Regex thing...

I have a button with a Text field on it. How would I use the above Regex expression to extract the text from the button and assign it to its own variable? Do I replace <text> with myButton.GetComponentInChildren<TextMeshProUGUI>().text, or does it operate a little differently if I'm adjusting a string value on a GameObject rather than a variable?

modest dust
#

once you press for example W, your playerDirection will be set to up

#

and then it will try to constantly go up

gaunt ice
#

You need a queue to store the key you press since the update will not response to any key you press while the player is moving
I am talking about your previous code not the new one you sent

modest dust
#

at least put a if (isMoving) return; at the beginning of update

gaunt ice
#
if(Input.GetKey(KeyCode.W) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.up));
    }
    if (Input.GetKey(KeyCode.S) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.down));
    }
    if (Input.GetKey(KeyCode.A) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.left));
    }
    if (Input.GetKey(KeyCode.D) && !isMoving)
    {
        StartCoroutine(MovePlayer(Vector2.right));
    }
```this one
burnt vapor
# storm pendant Hmmm...I'm having trouble trying to implement this Regex thing... I have a butt...

Create a variable with the regex
private readonly Regex _textRegex = new(@"<Regex goes here>", RegexOptions.IgnoreCase);

Get all matches
var textMatchCollection = this._textRegex.Matches(myContent);

For each match, get the text group I mentioned before.
var text = match.Groups.GetValueOrDefault("text")?.Value ?? throw new InvalidOperationException($"Expected text content.");

You now have the text.

burnt vapor
burnt vapor
#

It sounds pointless

gaunt ice
#

it is not my code....

queen adder
#

Man i find this code and works great, i want just make grid movement.

storm pendant
gaunt ice
#

i have said the main reason why you need to hold down the key to make player turn is that the update will simply "return" because it will not start any coroutine while the player is moving,
you can have a queue to store the input while the player is moving and dequeue to process it
(though i think you need some guard on it)

private Queue<Direction> q;
void Update(){
  if(input.getkeydown(XXXXX)||other direction key){
    q.enqueue(the direction)
  }
  if(q.Trydequeue(out direction)){
    switch(direction){
    case here
    }
  }
}
queen adder
distant current
#

Can anyone help me why Im getting null on this?

gaunt ice
#

try next step to see if it is null

#

i dont know what exactly the button is called

random sand
#

why can't this use mixamio animations

distant current
#

Im calling the name of the scriptable object, the Base is a scriptable object

gaunt ice
#

just nextstep since the line var x=X() is not executed since the process is stopped in this line

distant current
#

sorry I am too dumb, which next step

gaunt ice
#

step over button?

keen dew
#

I think they mean that Base is null, not saveData. Stepping over doesn't change the value of Base

gaunt ice
#

try press it the vs should stops in next line

distant current
#

is this it?

#

what makes the Base null?

keen dew
#

Did you write this code or is it a library/plugin?

gaunt ice
#

i think one of them is step over, hover on it and have a look

languid spire
#

Step In, Step Over, Step Out. In that order

distant current
#

when I click the Step Over, it just stays on the break

distant current
#

Im trying to use the same approach to my inventory and it works

#

But my quest is getting null

keen dew
#

well Base is null either because you've passed null to the constructor, or GetObjectByName didn't find anything, depending on which constructor was used when the object was created

#

that's the part that you should be debugging

gaunt ice
#

i misunderstand your problem, probably the name passed into getobjbyname is "wrong"

distant current
#

Is it the (saveData.name)?

keen dew
#

when you say that you wrote this, do you mean that you copied it from a tutorial? It seems strange that you wrote it but have no idea how it works

distant current
#

Yes, I did copy it from a tutorial but I was able to follow all of it but somehow the quest state is not working

keen dew
#

Put this at the end of the second constructor:

Debug.Log($"The value of Base is {Base} and saveData.name is '{saveData.name}'");

(or use the debugger)
Then when it says Base is null, check that the database contains an item with that name

distant current
#

Got it, thanks I will try that

azure zenith
#

How can I instantiate 3D cubes on top of blocks that instantiate themselves?

distant current
#

It doesn't print the log

keen dew
#

Then the object was created using the first constructor. Log _base there.

distant current
#

I tried to debug the first constructor, it doesn't print the log

keen dew
#

did you save the file

#

the NRE still points to the same line

distant current
#

as soon as the game runs, it NRE occurs as well as when I try to save the game

ashen ferry
#

so if you instantiate the block instantiate 3d cube above it whats the issue

faint elk
#

I am not sure if this is considered a beginners question but from the channel directory this one seemed to be the place since I am fairly new to C# and unity. So I was looking around the unity documentation and notice that there was a section for JAR plugins and I had the idea of having my game open a jar file of runescape just to see if it was possible. I went through the process of adding the jar to the file hierarchy and got all the import setting figured out and noticed the open button in the inspector which just ran the jar file when clicked. I looked through the docs to see if there was any way to open the jar through a script but i didnt see anything and figured i would ask here. Is this possible to do?

iron galleon
#

can someone help me? I wrote this rigidbody script and it doesnt work. only the camera script works which is in another file. it says nothing.

#

there isn't any error that shows up

#

it just doesnt work

languid spire
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

iron galleon
#

wait so like I paste the link of of the code?

languid spire
#

yes

iron galleon
#

oh

languid spire
#

Now why does that look like AI generated code?

iron galleon
#

it honestly is

#

im too lazy to not use chatgpt or smth

languid spire
#

this server has a rule against helping solve problems in AI code, sorry you're on your own

iron galleon
#

oh

tough lagoon
# iron galleon https://paste.ofcode.org/gkFMGQJYtLsBkCyF9ZKyjp

The code, in of itself, is usable. It's wrong on the ring damage portion. But as long as you tagged objects right, added it to a main (3D, not 2D) object. And have a rigidbody and collider it'll be usable. I'm also not so sure on the sliding mechanic and if that is actually functionally correct.

At any rate, it should be doing something. So debug and look at it closer.

frosty hound
#

You're too lazy not to use AI generated code, yet you come here asking people to use their time to resolve it for you? Have some respect.

slender cargo
#

So my player now rotates with the mouse, but I can't get it to walk in the correct local axis?

#

I remember there was something like Vector.3.axis

#

or something

ashen ferry
#

chat gpt comments be like ``` // declaring a:
int a = 2;
// declaring b:
int b = 2;

    // adding a and b together:
    int c = a + b;``` ![kekW](https://cdn.discordapp.com/emojis/888545109262622760.webp?size=128 "kekW")
ashen ferry
slender cargo
manic shore
#

I am trying to make an enemy AI that's trying to follow the player when they hit their line of sight. But I keep getting this error

rich adder
manic shore
rich adder
slender cargo
rich adder
ashen ferry
# slender cargo
        float ver = Input.GetAxis("Vertical");
        Vector3 moveThisUpdate = transform.right * hor + transform.forward * ver;
        transform.localPosition += moveThisUpdate * speed;``` try this idk
#

actually its a bit shit but idk how u wanna move the thing exactly

slender cargo
manic shore
rich adder
rich adder
manic shore
rich adder
#

they dont' bake navmesh in this video?

#

send link

manic shore
# rich adder send link

The closest I've seen is him adjusting the settings. Unless there's a big detail I'm missing
https://www.youtube.com/watch?v=xppompv1DBg

Let’s make some enemies!

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

●The Playlist: http://bit.ly/2xiecdD
● Sebastian's Channel: https://www.youtube.com/user/Cercopithecan

● Download the assets: http://bit.ly/2u4rcEX
● Download the source code: http://bit.ly/2uecCew

● Singleton Patterns: http://wiki.unity3d.com/index.php/Sing...

▶ Play video
rich adder
#

another brackys tut..

manic shore
#

?

rich adder
#

he probably did it in a different video

#

since its a series

rich adder
manic shore
#

oh damn

rich adder
manic shore
#

2022.3.8

rich adder
manic shore
#

Yes

rich adder
#

ok good. now you have a floor yes?

manic shore
#

Yes

rich adder
#

put the component I sent u link of. NavMeshSurface

#

hit bake , show screenshot of scene with surface selected

manic shore
#

This how you do it?

rich adder
#

did you test it

manic shore
#

It works!

#

Thanks.

rich adder
vast ivy
#

does this code look correct for changing animations?

if(enableSprint)
        {
            if(isSprinting)
            {
                playerAnim.SetBool("run", true);
                isZoomed = false;
                playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, sprintFOV, sprintFOVStepTime * Time.deltaTime);

                // Drain sprint remaining while sprinting
                if(!unlimitedSprint)
                {
                    sprintRemaining -= 1 * Time.deltaTime;
                    if (sprintRemaining <= 0)
                    {
                        isSprinting = false;
                        isSprintCooldown = true;
                    }
                }
            }
            else
            {
                // Regain sprint while not sprinting
                sprintRemaining = Mathf.Clamp(sprintRemaining += 1 * Time.deltaTime, 0, sprintDuration);
                playerAnim.SetBool("run", false);
            }
rich adder
vast ivy
#

The animation is set to loop, so when I start sprinting it should start to run, but no animation happens for a few seconds, then it runs the animation for 1 second then stops again, does this every few seconds

rich adder
#

on transitions

mental zenith
rich adder
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

vast ivy
#

the only things I've messed with in the animations themselves are the humanoid shape, and loop

rich adder
vast ivy
#

wheres that at

#

like tab

rich adder
#

oh its on the animator, on the line / transitions

#

the white line

#

click it

vast ivy
#

ohhh found it

#

it recommends having at least 1 condition between the animations, is this a problem I need to fix

vast ivy
vast ivy
#

lol I got it working

#

I read it wrong

mental zenith
rich adder
# vast ivy

you dont seem to have it plugged transitions

#

ie the bool param

vast ivy
#

Had to give it the bool values in the arrows

mental zenith
vast ivy
#

wait so do I need any code?

rich adder
rich adder
vast ivy
#

the bool is set in the manager isnt it?

#

no check means false correct? which it is referencing in the arrows

rich adder
#

yes, unchecked = flase

mental zenith
#

i dont get it hahahaha

rich adder
mental zenith
#

in the input.getdown("jump") if statement

polar acorn
#

Curious how you expected anything else

mental zenith
#

thats the entire issue xD

#

the logs are (semi) correct

#

is it possible its because of the fixedUpdate?

polar acorn
mental zenith
polar acorn
#

that is different than "when they land"

#

If you're on the ground already

#

then you set it to 5 then to 10

mental zenith
#

but thats normal when the player is on the ground it should have a speed of 10 but if it jumps it should become 5 until they are on the ground again

polar acorn
mental zenith
#

what is axiom 1?

polar acorn
#

I literally numbered them for you

mental zenith
#

sorry didnt know what axiom mean

#

but I think I see the issue thnx

rich adder
mental zenith
#

thnx

polar acorn
#

It doesn't matter here, but it's a thing used in mathematical proofs which is essentially defining a true initial state

#

Such that if the axiom is true then the proof is true

twilit trail
#

like in Start()?

#

so just an else Destroy(gameObject); ?

#

since the block is already if (IsServer)

rich adder
eternal needle
#

Destroying it probably shouldnt matter, especially since all the logic only runs if they are the server

rich adder
#

true!

twilit trail
#

okay I'll copy it there

manic shore
#

Is there a package that comes with this code?

polar acorn
#

What code

rich adder
manic shore
#

Yes

rich adder
#

so its a series , follow from 1 to whatever

#

he probbaly made it somewhere else

swift sedge
#

what series is it??

manic shore
manic shore
manic shore
polar acorn
manic shore
polar acorn
#

This means "Episode 10" which means there's 9 episodes of code that already exist

buoyant knot
amber nimbus
#

Hey, I have this code that rotates a turret on my tank this rotates it on the y axis. That is great but I need the turret to also follow the movement of the hull (which is the parent) so how can I get only 2 of the axis to follow?

#

the commented out code didnt work

polar acorn
#

If you want to get the euler angles in XYZ space, use localEulerAngles

buoyant knot
#

isn’t rotating on 2 axes the same as free rotation?

amber nimbus
#

what i basically need is to keep the localRotaion of X and Z at 0 but I need to change the Y axis in world space to follow the rotation

buoyant knot
#

because 2 angles defines the whole sphere

rich adder
buoyant knot
#

so, what if the parent has a non-Y axis rotation

amber nimbus
#

Basically what I need: transform.localRotation.x = 0 then transform.rotation.y = rotation and transform.localRotation.z = 0 And I need the Y rotation to happen slowly at a constant speed towards the target

buoyant knot
#

rotation gives euler angles in world space. local rotation is a quaternion in local space

amber nimbus
#

well yes, but i need to work with Y in world space

#

and X and Z in local space

buoyant knot
#

you know vector of turret to target, and you should know the local up of the transform

amber nimbus
#

here is my problem, the turret follows the "crosshair" but it doesnt follow the parents rotation

buoyant knot
#

unity’s documentation explicitly says to never assign transform.rotation

#

probably because you get that sort of thing. you are assigning the world space rotation

#

so you want to get the current localrotation quaternion, calcluate the desired future quaternion using Quaternion.LookRotation, interpolate between the two using turret speed, then transform.SetLocalPositionAndRotation to assign it

#

make sense?

amber nimbus
#

Yes, it does I will try it and thanks

buoyant knot
#

you should browse the scripting API methods for quaternion

#

lots of useful shit in there

#

lots of good methods that don’t require you to actually understand exactly how quaternions function

swift sedge
buoyant knot
#

because saying there is a lot of useful crap makes it seem like the content in there is not good, when it is in fact quite good

swift sedge
#

:/

faint elk
#

Stupid question if I have an object with script foo attached to it and do .GetComponent<Bar> which foo is an derived from will i get anything back or will I get an error

verbal dome
#

If Foo inherits from Bar then yeah it will find it

faint elk
#

Ok I figured it would but i thought id check before making the assumption

faint elk
fringe pollen
languid spire
timber tide
#

beautiful

harsh vault
#

idk why but my when I press the WASD keys. the character tries to make itself go back to idle then has a hard time going back to the walk animation. Is there a way I can make this better?

languid spire
#

by doing them first and saving the reference, just like you cache anything

faint elk
faint elk
#

or maybe im thinking of the wrong thing

timber tide
#

if it's only component data for that frame it may just be fine since it doesn't need all the component data if it shortcircuits, no?

languid spire
#

have you never done

MyScript myscript = GetComponent<MyScript>();

that is caching

faint elk
#

oh thats called caching

#

learned something new

languid spire
#

yes, means you only call GetComponent once instead of everytime you need something from MyScript

faint elk
#

this leads me to ask how I would implement it in this case?

timber tide
#

Ah, yeah you're getting the same component each statement, so yeah good idea to cache

faint elk
#

the thing is that its all raycasts so its not always going to be able to get the component from the the collider

timber tide
#

because each time you getcomponent, you're searching through the list of components on the GO

faint elk
#

you know it might be better if I pasted the whole code bit instead of just the if statement

#

that will probably give better context at whats going on

languid spire
# faint elk this leads me to ask how I would implement it in this case?
old

hitDown.collider.GetComponent<Pieces>().pieceType == "king" && hitDown.collider.GetComponent<Pieces>().pieceColor != this.pieceColor
hitLeft.collider.GetComponent<Pieces>().pieceType == "king" && hitLeft.collider.GetComponent<Pieces>().pieceColor != this.pieceColor
new

[] types;
[] colors

FillArray(hitDown.collider.GetComponent<Pieces>(),0);
FillArray(hitLeft.collider.GetComponent<Pieces>(),1);


etc, etc


void fillArray(Pieces pieces, int ix) {
types[ix] = pieces.pieceType;
colors[ix] = pieces.pieceColor;
}
#

then you have arrays you can loop over

timber tide
#

That's a lot of raycasts per update. I'd feel like you could probably accomplish something with just some overlapsphere/circle and figuring out the distances between you and the hit component.

#

but honestly, if what you're making isn't that complex it should be fine

faint elk
#

so if im understanding that right the code just gets the component no matter what and adds the color and pieceType to an array, then once all of it is populated i just check to see if the array has the king of the opposite color/

languid spire
#

you could also make FillArray return a bool and not need the arrays at all

faint elk
timber tide
#

Oh is this chess?

faint elk
#

yes

timber tide
#

You can probably just ignore the raycasts then and do it by indexing, no?

faint elk
languid spire
faint elk
#

I am currently doing indexing for everything else in it but I felt like using raycasts to check for the king being in check would be easier and cheaper to use raycasts instead of going through indexing

languid spire
#

is hitdown etc a raycast hit?

faint elk
#

yea

languid spire
#

ok, wait one

#
if (checkCollider(hitDown) || checkCollider(hitLeft) etc, etc

bool checkCollider(RaycastHit hit) {
if (hit.collider != null)
Pieces pieces = hit.collider.GetComponent<Pieces>();
if (pieces.pieceType == "king" && pieces.pieceColor != this.pieceColor) return true;
}
return false;
}

@faint elk

faint elk
languid spire
#

Always look for patterns in code, when you find one there is always a better way

faint elk
#

it didnt even process that I could pass the variable to a function and do it like that

languid spire
#

btw pieceType and pieceColor should probably be enums

faint elk
#

pieceColor is an enum as for pieceType I should probably turn that into an enum

faint elk
languid spire
#

now it does

faint elk
#

Lol thank you so much for your help

languid spire
#

np

last grove
#

why are none of my gameObjects rendering except for the player capsule?

rich adder
last grove
#

how do I do that?

rich adder
languid spire
#

Also @last grove Not a code question and don't cross post

last grove
last grove
rich adder
languid spire
last grove
#

Thanks

timber tide
# faint elk I am currently doing indexing for everything else in it but I felt like using ra...
const int SIZE = 8; //8x8 grid
const int ChessPiece[,] chessBoard = new ChessPiece[Size, Size]

//knight moves
int const numMoves = 8;
int x[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };

public bool KnightValidPositions(int x, int y)
{
   if(x >= 0 && x < SIZE && y >= 0 && y < SIZE )
   {
      if(chessBoard[x, y] == null) return true;
      
      else if(chessBoard[x, y].ChessPiece.owner == OwnerType.Enemy)
      {
        return true;
      }
    }
    return false;
}

public List<(int, int)> KnightMoves(ChessPiece Knight)
{
    List<(int, int)> knightMoves = new();

    for (int i = 0; i < numMoves; i++)
    {
        int newX = Knight.x + x[i];
        int newY = Knight.y + y[i];

        if (KnightValidPositions(newX, newY))
        {
            knightMoves.Add((newX, newY));
        }
    }

    return knightMoves;
}```
#

If you wanna ditch the raycasts it's just possible to check the indicies like this

#

I actually hate this site, but the information seems to be there

#

they got some anti-addblocker now too haha

languid spire
#

yes, Geeks for Geeks should be renamed 'Showoffs reposting other peoples code for people who dont know better', not as snappy perhaps but truer

timber tide
#

just not in the mood to read through Stackoverflow's chain of comments of how you should do it like this instead at the moment

eternal needle
#

There was a point where they made it so you had to have an account too, think they reverted it

languid spire
#

I love Stackoverflow responses they always seem to start with ' You should not be doing this' or 'I wouldn't start from here'

empty sentinel
#

“The result of this expression is always ‘true’ since a value of type ‘OVRInput.Button’ is never equal to ‘null’ of type ‘OVRInput.Button?’” Anybody know how to fix this?

languid spire
#

showing code might help

short hazel
#

Doing != null probably, where the value can never be null

#

But yes, post the code

empty sentinel
#

It’s code from a an Itch asset

#

I’m not super great with Unity, that’s why I’m using an asset, and it’s also a project for my little brother, my goal is to be able to add whatever he wants relatively fast

#

Here’s the asset if you want to take a look

faint elk
#

So I am getting an error saying " FindObjectsOfType is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'Queen'." and it appers to be because the variable is serialized for some unknown reason, how do i prevent it from be serialized

short hazel
#

No it's because you're calling FindObjectsOfType in a field initializer

#
class Sample : MB {
  public T Something = FindObjectOfType<T>(); // not allowed
}
faint elk
short hazel
#

Post the Queen class, that is where the error is originating

faint elk
#

thats the thing its not even in the queen class its in the piece class

short hazel
#

The error says otherwise

faint elk
short hazel
#

Where do you call Queen.setup()?

faint elk
#

in the chessboardmanager class

short hazel
#

Same for movement(). Where exactly

faint elk
#

movement is called in the queen class

#

im telling you the issue is in the pieces class

#

unity even opens the piece class when i go to the error

short hazel
#

Then search for any FindObjectsOfType there

faint elk
#

that code doesnt even exist in the class

#

i dont think i have ever used that findobjectsoftype

#

I have FindObjectOfType but not objects

short hazel
#

A quick "Find In Files" will sort that out

faint elk
#

nothing

short hazel
#

Well I see the stack trace of the first error and it mentions the constructor of Pieces

#

Chess.Pieces.ctor(), line 29

faint elk
#

i can post the pieces class for you if that will help

languid spire
#

yes

faint elk
short hazel
#

There is nothing on line 29. Save and run the game again to get an updated stack trace

#

Also Pieces inherits from Chessboard? What?

faint elk
#

lets not talk about that one

#

still figuring out why i did that myself

#

but the issue seems fixed now

delicate portal
#

Hey! How do I import assets to unity from unreal engine?

summer stump
delicate portal
#

Textures, meshes

#

I mean I imported them but they look like theese:

polar acorn
rich adder
#

better not be the ones from Epic Store, its against TOS

short hazel
# faint elk but the issue seems fixed now

Considering that your error is from half an hour ago (if you don't live in one of those countries that have half an hour of time offset), then yes you likely fixed it half an hour ago

delicate portal
delicate portal
polar acorn
#

The image, or fbx or whatever file was imported

paper sable
#

hey guys, im trying to make a car with wheel colliders but when i start the game, my wheel colliders move a bit forwards (which they shouldn't), and when i press W to move forward, the wheels move, but the car doesn't move. also the wheels go a bit under the ground

delicate portal
#

I imported theese assets but I cant import the materials

polar acorn
#

Whatever file you dragged in

delicate portal
#

That contains the uassets?

polar acorn
#

No, the file that you imported

short hazel
#

This is a code channel folks, move to whatever channel is on topic for asset importing

delicate portal
polar acorn
#

I'm not sure there's much more to say anyway. Just drag in the file you imported into unreal into unity instead

tender stag
#

any way to make the enum ogranized better?

[System.Serializable]
public enum CellTypes
{
    Hotbar,
    Inventory,
    Head,
    Body,
    Legs,
    Feet,
    Fuel,
    Furnace,
    Campfire,
    Scrapper,
}```
#

something like this

timber tide
#

You can always make sub-type enums

tender stag
#

what is that?

timber tide
#

What does Celltype represent? Like a base type?

tender stag
#

on the slot script you have an array for CellTypes

#

and on the item SO you also have an array

#

it cheks the compatibility

#

if you can place into that cell

timber tide
#

Ah, ok so it's stuff that can be stored on slots which include an SO

#

Right, so stuff like Head, Body, Legs, Feet. Perhaps another enum like EquipCellTypes

unique falcon
timber tide
tender stag
#

ohhhh

#

like that

#

yeah thats good

#

dont i need to [System.Serializable] all of them?

timber tide
#

ye

tender stag
#

alr

timber tide
#

Actually you don't need to serialize them. Unity does this automatically for you, but if encapsulated in a class then that needs to be serialized

tender stag
#

then how do i modify my CompatibleWithCell method?

public bool CompatibleWithCell(Item item, InventoryCell cell)
{
    if(cell.canPlace)
    {   
        if(cell.cellTypes.Count == 0)
            return true;

        if(cell.cellTypes.Contains(CellTypes.Hotbar))
            return true; 

        if(cell.cellTypes.Contains(CellTypes.Inventory))
            return true; 

        foreach(var compatibleType in item.itemData.allowedCells)
        {
            if(cell.cellTypes.Contains(compatibleType))
            {
                return true;
            }  
        }

        return false;
    }

    return false;
}```
tender stag
#

cause on my furnace

#

im not using all the UtilityCellTypes

#

im only using Furnace

#

and on a campfire im only using Campfire

timber tide
#

This is just to reduce type checking. If you know that the furnace is at least a Utility type, then you can eliminate checking every single enum

#

Ah, maybe im thinking of this wrong. I think what you have is probably fine, but when it comes to the hotbar, that requires a bit more checking.

tender stag
#

what do you mean

timber tide
#

What can you store on the hotbar

tender stag
#

i already got that done

#

look

#

on my inventory manager

#

i got hotbar manager

#

the items list holds the item data and the game object in the players hands

#

and if the current selected hotbar slots item item data matches the one in the items list

#

then equip, or unequip or switch

#

you get the point

#

anyways i'll keep what i had at the moment with the enums

#

can i at least add spaces?

#

like this

#

i know it wont show in the editor

polar acorn
tender stag
#

why not?

#

i just want the code to be more visible

#

i know in the inspector wont be seperated

polar acorn
# tender stag why not?

Oh wait, I misread what you said. I thought you said "It won't show in the inspector" like that was the question

#

You can put lines in code anywhere you want

#

even in the middle of lines in certain cases

tender stag
#

alright thanks

timber tide
tender stag
#

alright i'll worry about it later on then

timber tide
#

Yeah absolutely

#

it's not like it's every update at runtime type of thing, and you're only checking once

#

so it's all good if it works for you

tender stag
#

i wish you could just do something like

#

or add headers

swift sedge
empty sentinel
tender stag
tender stag
#

if you want info

short hazel
swift sedge
#

like bool can be either false or true

empty sentinel
short hazel
#

Without at least the code, and the position of the warning/error, nothing can really be done

empty sentinel
#

Yeah

jade elk
#

how do I add a background to a scene?

swift sedge
empty sentinel
swift sedge
jade elk
short hazel
empty sentinel
swift sedge
tender stag
#

is there anyway to make it so that when i add a new enum i dont have to manually set every single one again?

#

cause the enum moves up or down

short hazel
# empty sentinel So if I downgraded sdk versions it may help?

They probably have versioned docs. Look for the type name in the API reference, and see if it's a class or a struct for your current version. Repeat for an older version.
No need to up/downgrade until you're sure the type has changed. It's unlikely though, I've never seen a type change like this in a codebase

ashen ferry
#

Ive got poco class serialized and noticed its never null it makes sense but I need to know if its not just a shell of default values how do I check for that

jade elk
#

i have a 2d game, i made the background a sprite, but now i can't see the other sprites

#

why is that

polar acorn
#

It's probably in front of them

jade elk
#

how do I make it behind them

polar acorn
#

Move it behind them

jade elk
polar acorn
jade elk
#

ah

swift sedge
jade elk
#

setting into 1 works

#

-1 doesnt

timber tide
empty sentinel
jade elk
#

how do I make it so if my sprite is hit, it is deleted?

polar acorn
#

The hitting or the deleting

jade elk
#

to delete it

polar acorn
#

Destroy(someGameObject)

jade elk
#

will it delete it in real time?

short hazel
swift sedge
empty sentinel
swift sedge
#

if you want it to delete faster, you can use DestroyImmediate() but it's not recommended for performance reasons

ashen ferry
short hazel
jade elk
empty sentinel
eternal needle
short hazel
eternal needle
timber tide
ashen ferry
#

sorry one of us dont get something kekW how does that help me to know whether that instance of class is empty or not

polar acorn
short hazel
jade elk
#

is the game manager where everything is called and used?

summer stump
jade elk
#

how do you guys get more than one sprite up and running?

summer stump
jade elk
#

do I have to create multiple instances?

#

or is there a better way

summer stump
jade elk
#

can you explain?

#

do I make instances within?

summer stump
jade elk
#

would I do this in that file?

summer stump
#

Probably not

#

That should handle an individual black hole

timber tide
summer stump
jade elk
#

alright bet

jade elk
# summer stump You want like a BlackholeSpawner script to handle that, and the prefab would hav...
using UnityEngine;

public class BlackHoleManager : MonoBehaviour
{
    public GameObject blackHolePrefab; // Reference to your BlackHoles prefab
    public int numberOfBlackHoles = 5;

    void Start()
    {
        for (int i = 0; i < numberOfBlackHoles; i++)
        {
            GameObject newBlackHole = Instantiate(blackHolePrefab, GetRandomPosition(), Quaternion.identity);
            
        }
    }

    Vector3 GetRandomPosition()
    {
        float x = Random.Range(-10f, 10f);
        float y = Random.Range(-10f, 10f);

        return new Vector3(x, y, 0f);
    }
}```
#

like this right

#

but how do I set the prefab

polar acorn
#

Drag it

jade elk
#

to where

polar acorn
#

Into the variable

jade elk
summer stump
#

Yeah. I would make minX, minY, maxX, maxY variables to pass into the random range
Avoid "magic numbers" wherever possible

jade elk
#

don't see anything about prefab

summer stump
#

Drag it to the Manager one

polar acorn
#

Did you try looking at the script that has the variable

#

instead of a different unrelated script

jade elk
#

i don't have that script added though

summer stump
jade elk
#

what do I add it to though

polar acorn
summer stump
#

A gameobject...

polar acorn
#

Considering it does not exist

jade elk
#

sorry, new to unity but not programming. don't we add scripts to a sprite?

#

do I have to create a sprite for the manager then?

summer stump
#

So no

#

Add it to an empty gameobject unless you want to see it for some reason

#

But it's a manager, so you probably dont

jade elk
#

gameoject in the scene?

summer stump
jade elk
gaunt thistle
#

i havent had this issue for a very long time but im an idiot so eh. i have a child object of pistol. under that child i have a another child which then has a mesh child. its been put under the camera object and it skews weirdly whenever the camera moves

summer stump
#

You can make it a prefab too, but it will only work in the scene

jade elk
#

so I hit "new" and create game object

summer stump
eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

summer stump
gaunt thistle
#

so its not 1:1

summer stump
#

It's fine to scale children. Parents are the issue

gaunt thistle
#

its normal

summer stump
#

Hmm

#

I'd need to see a screenshot I guess. I'm not sure what the issue is otherwise

tender stag
#

how could i handle displaying item info in my inventory?

#

like each item has of course non mutable data

#

like name

#

max stack

#

weight etc

tender stag
#

and all of that i want to display

#

but then you have mutable data

gaunt thistle
tender stag
#

like recoil

#

damage

#

etc

short hazel
#

Scriptable object for immutable data, regular serializable class for mutable data

gaunt thistle
tender stag
#

im using them

tender stag
#

which is an SO

gaunt thistle
#

hang on i know why

#

fuck im stupid

#

player is 1, 1.5, 1

summer stump
#

Sorry, had to step put. I was gonna say, it can be any scaling up the whole chain

ashen ferry
#

can DDOL game object get destroyed in some other ways than by ur own code its just disappearing like 10 frames into the next scene im so confused lmao

polar acorn
#

It does not convey it any sort of invulnerability

ashen ferry
#

yea tho loading next scene or destroying it myself are like only ways I know how it can be gone

polar acorn
#

Yeah that's basically it

#

So, if it's not being destroyed by changing scenes, there's only one other option

ashen ferry
#

I had line I completely forgot about adding singleton on that game object when loading scene but I was changing that scene and ended up adding that script there as well, which was destroying intruder from last scene with no logs that was nasty ngl

faint elk
#

Is there any ways to make a script wait for a new frame to be rended before it continues?

polar acorn
faint elk
#

a coroutine?

gaunt swan
#

If you are on 2023.1 you can also use the new Awaitable.NextFrameAsync method from an async function

faint elk
#

so its literally just C# IEnumerator Waitforframe() { yield return null; }

#

i can never get code blocks to work

gaunt swan
#

You would put whatever you want to happen before the next frame above yield return null, and everything after below it.

#

Then call the method with StartCoroutine(WaitForFrame())

faint elk
#

So next question in VS its showwing IEnumerator as not a thing

#

Am I suppose to import something?

gaunt swan
#

It's in System.Collections

faint elk
#

ok ill give it a try

#

did not seem to work

gaunt swan
#

Post your coroutine function

faint elk
#
IEnumerator Waitforframe()
       {
           yield return null;
       }```
gaunt swan
#

That's not going to do anything

faint elk
#

OOOOH

#

THE IT GOES INTO THE COROUTINE

#

im stupid

gaunt swan
#

yield return null acts like a barrier that 'pauses' your code and then resumes it in the next frame.

faint elk
#

I can pass variables and stuff to coroutines, right

gaunt swan
#

Yes, they act like normal functions. They just can't have a return value since they return an IEnumerator implicitly

vast ivy
#

Is there a way either in the animator manager to automatically reset this bool back to false after the animation is played or a way to do it in code?:

private void Jump()
    {
        // Adds force to the player rigidbody to jump
        if (isGrounded)
        {
            playerAnim.SetBool("stand jump", true);
            rb.AddForce(0f, jumpPower, 0f, ForceMode.Impulse);
            isGrounded = false;
            
        }

        // When crouched and using toggle system, will uncrouch for a jump
        if(isCrouched && !holdToCrouch)
        {
            Crouch();
        }
    }
faint elk
#

ignoring how bad my code is I am having trouble figuring out what the best way to implament the coroutine would be. I need a whole object generated and configured before the if statement runs on line 98 https://gdl.space/eqetalazel.cs

gaunt swan
#

The link you posted has no line numbers

faint elk
#

damn

#

its in the spawnmovementdot function

gaunt swan
faint elk
#

i dont quite understand what you are refering to

#

my brains a bit out of it since i have been doing this for 6 hours

gaunt swan
#

I need a whole object generated and configured before the if statement runs
Why are you running the statement at all if your program is not ready to do that? You could for example generate the object in a different script and then enable this one once the required objects exist

ivory bobcat
#
coroutine:
    yield
    do something after yielding```
gaunt swan
tender stag
#

can the random number be 100?
float randomValue = Random.Range(0, 100);

#

or do i have to like add 1

tender stag
#

what do you mean?

ivory bobcat
#

Inclusive for float

ivory bobcat
faint elk
#

Ok I think i understand it thanks for the help

ivory bobcat
#

Exclusive means not including

gaunt swan
tender stag
#

like i need to calculate a percentage

#

but im not sure if it can pick 100

gaunt swan
#

Then why not use values in the range of [0, 1] as floats?

tender stag
#

or the max will be like 99.9999999

ivory bobcat
gaunt swan
#

You probably want something like float randomValue = Random.Range(0f, 1f)

ivory bobcat
#

Integer: 100
Float: 100f

tender stag
#

i could use integers for the percentage tho

#

right?

gaunt swan
#

Yes, but why would you ever want to do that

tender stag
#

not sure

#

lol

ivory bobcat
#

Random.value will produce a random value between 0 and 1 inclusive if that's what you're wanting.

tender stag
wary delta
#

Yes

tender stag
#

alright thanks

#

i always thought u needed to like add 1

#

when using random range

wary delta
#

Of type float, not int

tender stag
#

alright

wary delta
#

@tender stag the docs are your friend...

tender stag
#

yeah i know i just didnt understand what inclusive means

#

and exclusive

#

i read them but still didnt understand

wary delta
#

inclusive means including, exclusive means excluding

tender stag
#

ohhh

wary delta
#

so if it was exclusive, it would return a value between 0.000001 and 9.999999 where the value would be random but could never be 0f or 100f.

#

but its not, it's inclusive.. which means it will return a value between 0.000000 and 100.000000 and both 0 and 100 are possible outcomes.

eternal needle
#

The exclusive one (ints) only applies to the max

unique violet
#

How can I make something for an iOS app that brings up the file picker and sends the chosen file to an api? I’ve seen some file picker assets but idk if it’ll work to send to an api

swift patio
#

No idea how to fix this error

Enemy.OnParticleCollision (UnityEngine.GameObject other) (at Assets/Scripts/Enemy.cs:17)```
the image below is line 17
#

nvm guys i fixed it

teal viper
swift crag
unique violet
swift crag
#

that...is the whole file

#

barring extra data stapled on by your filesystem

#

you will need to elaborate.

teal viper
#
  • maybe some metadata, like info on its path, extension creation date, etc...
elder osprey
#

How can I use info from the 2DRaycast so i can draw a cube gizmo at the position the raycast hits?

swift crag
#

Store the point you hit in a field.

#

then use it in OnDrawGizmos

summer stump
cosmic dagger
unreal imp
#

guys,im making a pickup objects player system to imitate it like half life 2 and the code is this but doesnt works: ``` private FixedJoint joint;
private Rigidbody grabbedObject;

void Update()
{
    
    if (Input.GetKeyDown(KeyCode.E))
    {
        if (grabbedObject == null)
        {
            TryGrabObject();
        }
        else
        {
            DropObject();
        }
    }

    if (Input.GetMouseButtonDown(1) && grabbedObject != null)
    {
        
        ThrowObject();
    }
    if (Input.GetMouseButtonDown(0) && grabbedObject != null)
    {
        
        DropObject();
    }
}

void TryGrabObject()
{
    RaycastHit hit;
    if (Physics.Raycast(transform.position, transform.forward, out hit, 5f, LayerMask.GetMask("Pickable")))
    {
        grabbedObject = hit.collider.GetComponent<Rigidbody>();
        if (grabbedObject != null)
        {
            
            joint = gameObject.AddComponent<FixedJoint>();
            joint.connectedBody = grabbedObject;
            joint.breakForce = 1000f;
            joint.breakTorque = 1000f;
        }
    }
}

void DropObject()
{
    if (joint != null)
    {
        
        Destroy(joint);
        grabbedObject = null;
    }
}

void ThrowObject()
{
    if (grabbedObject != null)
    {
        
        grabbedObject.AddForce(transform.forward * 10f, ForceMode.Impulse);
        
        DropObject();
    }
}```
#

anyone has an idea?

timber tide
#

that's a lot of code, have you debugged it via logging or breakpoints

wintry quarry
unreal imp
#

i had the steps like they said with doing FixedJoint

#

ahhh i think i might already know what the problem is.

#

By chance, would anyone know what it would be like to make the steps of grabbing objects like Half Life 2 more detailed?

acoustic arch
#

for my fps small game would the gun shoot to like the crosshair or how does it usually work

unreal imp
fossil harness
late burrow
#

does findobjectsoftype work if parent gameobject is disabled?

empty juniper
#

how do i get the current rotation of an object

late burrow
#

transform.rotation

empty juniper
#

i need to use it in an if

late burrow
#

rotation.eulerangles

summer stump
late burrow
#

parent disabled but child enabled

summer stump
late burrow
empty juniper
# summer stump In what way

so i have a plane and i want the fins to rotate 45 degrees when i press w but only if the current rotation is less than 46

summer stump
late burrow
#

i mean child is enabled in a way that its ticked

#

but parent is not

#

so in theory its disabled

fossil harness
#

A bit more context on this answer:
Rotations are stored as BUFFs (quaternions) that aren't really human friendly, so we can cast them to EulerAngles which are the degrees around the XYZ axes that we're used to (e.g. 90 degrees around y axis is "left" if you're facing 0 degrees around the y axis)

summer stump
fossil harness
#

You could read local rotation no?

#

Or does Unity still have rotation shenanigans with the inspector and code

summer stump
empty juniper
#

i put (transform.rotation.z < 46 || transform.rotation.z > -46) as the condition and i didnt get syntax errors but it just dont work

fossil harness
#

Ah yeah, because you're accessing the z of the quaternion

summer stump
#

Lol

fossil harness
#

I.e. a 4D circle from hell

You need to access "transform.rotation.eulerAngles.z", though I'd recommend "transform.localRotation.eulerAngles.z"

#

Quaternion = incomprehensible extremely high-level math
EulerAngles = normal, readable numbers

cosmic dagger
cosmic dagger
violet topaz
#
public class LookAtMouse : MonoBehaviour
{
    
    // Update is called once per frame
    void Update()
    {
        var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
        var angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
} ``` how do I make the player look at the mouse. right now its looking the opposite way
fossil harness
#

I.e. some field "rudderAngle" and assign the local rotation to a quaternion constructed from the eulerangle of the aforementioned "rudderAngle" whenever it changes?

cosmic dagger
# empty juniper idk what to do bruh

@fossil harness
you can store the original direction of the flaps in a field and check the angle against the current forward direction of the flaps

you can store the current z axis in a field and subtract it from the input, clamp field using your ranges, then assign the rotation using the stored field . . .

violet topaz
#
public class LookAtMouse : MonoBehaviour
{
    
    // Update is called once per frame
    void Update()
    {
        var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
        var angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
} ```
 how do I make the player look at the mouse. right now its looking the opposite way \
unique violet
teal viper
teal viper
smoky ledge
#

Hello, I'm trying to get into Unity but I can't cuz I think I goofed up. I set my programming holder as notepad and whenever I try to write code it won't open up the notepad, is there a way to change this?