#💻┃code-beginner

1 messages · Page 5 of 1

wintry quarry
#

they they won't be getting hit by this raycast. Can you prove otherwise?

#

Follow the steps linked above and don't skip anything even if you think you did it already

polar acorn
#

Yes, the links you were sent

#

Log the name and layer of the object your raycast hits

ivory bobcat
tawdry rock
vestal valve
#

Guys, How should I display other language text?

ivory bobcat
#

Whatever you can find on the net and that is easier for you. Tutorials and docs should be easy to find for Unity.

wintry quarry
vestal valve
wintry quarry
#

whatever font you are using currently for the ui text does not support it

#

find one that does and use that

silent valley
#

I have a float called "lifetime" which is for my battery % . I'm struggling to add it to this part of the script. I want my light to start flickering at 10% lifetime

ivory bobcat
#

If anything, you could evaluate life time in some update and have it modify the light intensity.

silent valley
#

it's for my flashlight. I have made it so my flashlight flickers. just cant do it for it to only happen at 10%

ivory bobcat
#

Ah, okay. cs if life time > threshold return

#

You'd do this prior before any of the above. No point in doing anything if the condition isn't true.

silent valley
#

so i can put all this into a bool and if true then this activates?

ivory bobcat
#

Umm I'm not sure what you're saying exactly but you'd simply not do the other stuff if the condition isn't met.
If anything, you might also want to reset the intensity before returning so that when the battery increases over the threshold, it resets.

#
light intensity = default
if battery > threshold
    return
...
light intensity = flicker```Where you'd flicker if the threshold (low on battery) is met.
lethal cargo
#

Can someone give me fpc controller or movement ?

ivory bobcat
#

"Unity fps controller"

#

You can also try the asset store and see if there are any free ones

#

Or paid ones.

lethal cargo
#

alr il try thx

silent valley
#

I might find tutorials on flickering scripts. I'm not sure what half the script means and I don't like that Cry

#

Thank you though

lethal cargo
#

is this good?

wintry quarry
#

It's free - give it a shot

ivory bobcat
#

Probably. tryitandsee

lethal cargo
#

alr

silent valley
#

Sorry, I have one more question. Regarding custom methods. I've looked it up before and it didn't quite make sense to me. Why is the method custom and not for example put in the void Update?

wintry quarry
frail hound
#

What would the best method of doing a top down camera be? Should I just keep it attached to the player sprite?

wintry quarry
frail hound
ivory bobcat
wintry quarry
frail hound
ivory bobcat
#

It's powerful and you'll learn to appreciate it's features - future prospects of buttery smooth transitions (free) at the cost of learning.

wintry quarry
silent valley
frail hound
wintry quarry
ivory bobcat
frail hound
lethal cargo
#

i drag this to main camera?

silent valley
#

You should have a prefab or something which is already set up

wintry quarry
#

it's a few clicks

#

that's the point

lethal cargo
#

this

#

?

silent valley
#

open it and drag the fps controller into the hierarchy/scene

lethal cargo
#

i dont see itnotlikethis

silent valley
lethal cargo
#

where is that

silent valley
#

Assets/EvolveGames/RealisticFPSController

#

Thank you @wintry quarry @ivory bobcat for your help. Managed to get my flickering effect when below 10% and works flawlessly while understanding all the code

dreamy ingot
#

Hey so i'm trying to plan out a unity project and was wondering if i could get some opinions on its feasibility.
I want to try and build a library/plug in for creating templates for spells so that you can quickly generate different basic spells and modify them.
I'd like to be able for it to support the D&D spell slot costs and Mana costs methods so you can choose which ones you'd like to use in whatever game.
I'm going to try and let you specify stuff like the spells name, its range and duration, effects from a set of presets, types of projectile behaviors for the user to choose from or create their own implementations as they need.
I just want to make a customizable structure that others could import and work with.

cosmic dagger
wintry quarry
#

share the video as MP4 so it gets embedded

#

also share your code !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.

maiden charm
#

hey guys need some help with vector2 if possible

#

not turning green

rich adder
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)

sharp flower
#

Hey, can someone help me with movement jitter on an FPS rigidbody setup? I've scoured the forums and can't seem to get anything to work. Everything is super smooth when just looking, or when just moving, but when I move and look at the same time, it becomes definitely NOT smooth.

Things I've tried:

-Messing with update vs. fixed update vs. late update.
-Interpolation on the rigidbody.
-Messing with Time.deltaTime in relation to the controller scripts.

Player Controller: https://gdl.space/ibuvamayak.cpp
Mouse Look Controller: https://gdl.space/vawiyevani.cs

maiden charm
#

updating as we speak

#

still not working unfortunately

languid spire
vestal valve
#

Where does the text go?
I just changed font size from 26 to 27.

maiden charm
#

still no vector2 😦

languid spire
maiden charm
languid spire
#

!ide and follow ALL of the steps carefully

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

maiden charm
#

installed manually followed the entire link.

languid spire
#

when this changes you know you've done it right

maiden charm
#

okay will have another look thorugh

ivory bobcat
maiden charm
#

i get no option for that lol

ivory bobcat
#

Sure you do. Run the installer again

languid spire
maiden charm
#

i do now lol

#

thats ticked now

ivory bobcat
#

It's often overlooked but you should be fine now if everything (the easier non missed parts) is done 👍

maiden charm
#

yeah i thought it was on visual program not installer lol

ivory bobcat
#

The other workloads aren't necessary and can reduce install time if you don't have them selected.

maiden charm
#

okay will have a look soon, gotta nip out so back in a hour hopefully refreshed

sharp flower
languid spire
sharp flower
crisp gate
#

!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)

solar tide
#

Hey, how do you use the "FindChild" function but it gets many childs?

#

I can only get 1 with this

slender nymph
#

what FindChild method are you referring to? do you mean GetChild? because that gets a child at a specfic index. why would that return more than one child?

solar tide
#

I wanna do something like
gameObject.transform.FindChild("body", "head")

#

But the Find Child function only works on 1 child

slender nymph
#

that's not FindChild, it's just Find. and much like GetChild it only gets a specific child. just call it for each one you want to get

hushed hinge
#

I don't get what is going with this in the tetris game righ tnow

slender nymph
#

those last things are likely editor errors. but also you should always start diagnosing issues from the first error in your console not the last

queen adder
#

and see if it persists

hushed hinge
solar tide
#

I'm trying to use the CompareTag function but it keeps returning a null exception error

slender nymph
#

you can create whatever you have the skills to create

slender nymph
solar tide
#

does the compareTag function use mesh colliders to find it's target or no?

slender nymph
#

CompareTag has nothing to do with colliders. all it does is check whether an object has a specific tag

#

the only relation that CompareTag has to a collider is that Collider inherits from Component so it inherited the CompareTag method. the method does not care what kind of collider it is, it's only purpose is what i stated before

solar tide
#

I fixed it.

hushed hinge
#

I got a problem with the red and black tetrominos is that unlike from the rest when I turn them around they do not go into the walls but for the red and black ones they go into the walls when I turns around, how can I fix this?

slender nymph
#

typically if you need help with your code you should show the !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.

timber tide
#

Actually looking at it again, you don't seem to update the actual block coordinates for what they can occupy when you rotate them

hushed hinge
#

then how do I fix it?

timber tide
#

When you rotate your blocks, however you're storing the coordinates for each segment, it needs to be updated

hushed hinge
#

I don't know how to update that

timber tide
#
 bool CheckIsValidPosition ()
    {
        foreach (Transform mino in transform)
        {
            Vector2 pos = FindObjectOfType<Game>().Round(mino.position);

            if (FindObjectOfType<Game>().CheckIsInsideGrid(pos) == false)
            {
                return false;
            }

            if (FindObjectOfType<Game>().GetTransformAtGridPosition(pos) != null && FindObjectOfType<Game>().GetTransformAtGridPosition(pos).parent != transform)
            {
                return false;
            }
        }

        return true;
    }```
#

So here you're iterating through all the transforms on your game object and checking if it's inside of the grid

#

Not too sure from here, but some of the segments should be returning false, yet they are not.

languid spire
#

I presume you mean to Rotate, check if valid if not rotate back

edgy prism
#

Hello I am trying to make a questUI that tracks objectives i.e. items collected X/5 and I figured doing this in update is a worse idea than using an event action but im unfamiliar with them if I do

OnUpdated += UpdateObjectiveProgress;

How do I then reference my event action in another script? Is it just ClassName.OnUpdated?

polar acorn
#

Other scripts reference this script to subscribe to it

edgy prism
polar acorn
#

Turns it to A -> B -> C instead of a web where all three things need to know about each other

edgy prism
polar acorn
# edgy prism Ahh I understand you thankyou, so I need a reference in the script that is invok...

You'd still need your listeners to reference the event invoker, but this pattern prevents you from needing them to reference each other. If there's only ever one source of the event, you can make it static, then the subscribers can get the reference to the event with ThatClass.OnUpdate += ... but events must be invoked on the class that defines them, so the event needs to be on the script that knows when it should activate

civic aurora
#

!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.

edgy prism
civic aurora
#

i have the bullets set a trigger and a box collider 2d on the enemy

summer stump
#

OnCollision is between two non-trigger colliders

civic aurora
#

oh you are right

#

should i make 2 types of bullets one for enemies and one for player?

summer stump
#

Just drop all the code in OnCollisionEnter into OnTriggerEnter (and modify it to use collider instead of collision)

civic aurora
summer stump
#

You don't need a second one

civic aurora
#

oh ok

#

thank you

#

yes it works now 🙂

hushed hinge
hushed hinge
timber tide
#

Didn't you say your teacher was writing the code for you? Why not ask them to resolve it?

hushed hinge
jagged gulch
#

Lookin to create a shotgun in my project but having some difficulty wrapping my head around raycasts. I currently have it setup to shoot in the direction Im looking but not sure how to randomize which direction the raycasts point in.

#
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit, shotgunRange))
    {
      Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
      Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
      }
 
}```
slender nymph
#

if you google "unity shotgun raycast" you'll get plenty of results with examples of how to randomize the direction of the rays within some parameters for the shotgun blast

timber tide
jagged gulch
#

ex. most dont use ScreenPointToRay or have different raycast setups

timber tide
jagged gulch
#

raycasts have always been an issue for me atwhatcost

slender nymph
jagged gulch
#

I just wanted to see if anyone had advice on how I could implement it with mine without having to redo the whole system I had setup, like wouldnt it just be possible to adjust the direction of the ray after its been created

slender nymph
#

the only thing you need to change is how you construct the ray

#

but if you refuse to even bother reading about how to do that, why should anyone put in the effort of explaining the exact same things you'll find in hundreds of google results?

jagged gulch
#

thought Id just ask

queen adder
unreal imp
#

boys,how i should change a text mesh with script? ``` private void Start()
{
healthText.text = "Health " + Health.ToString();
}

slender nymph
#

like that. but you probably want to do that when the Health variable changes rather than just in Start since Start only runs once in an object's lifetime

cosmic dagger
jagged gulch
#

another was 30 videos deep into a fps controller series

hushed hinge
jagged gulch
#

Ill try and see what I can take from them

unreal imp
# slender nymph like that. but you probably want to do that when the Health variable changes rat...

nono, it will also change constantly when there is some change ```public int Health = 100;
public GameObject player;
TextMesh texthealth;
public int getHurtWithCollideObject = 2;

private void start()
{
    healthText.text = "Health " + Health.ToString();
}

private void OnCollisionEnter(collision collision)
{
    if (collision.gameObject.CompareTag("Toilet") && collision.rigidbody.velocity.magnitude >= getHurtWithCollideObject)
    {
        takeDamage((int)collision.rigidbody.velocity.magnitude);
    }
    if (collision.gameObject.CompareTag("Toilet") && collision.rigidbody.velocity.magnitude >= getHurtWithCollideObject*2)
    {
        takeDamage((int)collision.rigidbody.velocity.magnitude/2);
    }
    if (collision.gameObject.CompareTag("Explosion"))
    {
        takeDamage((int)Health%50);
    }
}

override takeDamage(int damage)
{
    healthText.text = "Health " + (Health =- damage).ToString();
}
queen adder
cosmic dagger
jagged gulch
slender nymph
cosmic dagger
queen adder
unreal imp
cosmic dagger
unreal imp
#

nope,on the script no

timber tide
slender nymph
# unreal imp yeah ❤️

yeah so stop ignoring the errors in your console. make the variable either public or decorate it with the SerializeField attribute and then drag the relevant TextMesh object into the inspector

cosmic dagger
unreal imp
cosmic dagger
# unreal imp yes

bruh, you should start with that. any error means smth wrong or bad happened. we can't do anything until all errors are fixed . . .

unreal imp
#

the error is: NullReferenceException: Object reference not set to an instance of an object PlayerHealth.Start () (at Assets/PlayerHealth.cs:14)

ivory bobcat
hushed hinge
unreal imp
#

ok i will try

summer stump
cosmic dagger
timber tide
cosmic dagger
unreal imp
cosmic dagger
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.

hushed hinge
jagged gulch
# ivory bobcat With your initial accurate and perfect shot, just apply an offset to each pellet...

Where should I apply the Random.InsideUnitCircle offset to in the code?
like

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit + Random.InsideUnitCircle, shotgunRange))
    {
      Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
      Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
      }
 
}``` since its a vector3?
#

or someplace else?

summer stump
ivory bobcat
#

You'll have to think about it. You'd only want one raycast for the origin.

maiden charm
#

so im back, still struggling with getting this vector 🥲

summer stump
hushed hinge
#

I still don't get it what I am supposed to do

summer stump
#

Honestly, I didn't see the beginning, I don't even know what you want to fix. Mao said log position, and you literally have a variable right there

hushed hinge
#

I. still. don't. know. what. I. Am. supposed. to. do

summer stump
timber tide
#

The idea is your check position is not returning false despite your blocks going out of bounds, so first let's see what those values are

summer stump
#

Put... the position... value... in the debug.
How could you possibly not understand that?

hushed hinge
summer stump
#

No, that is a word, not a value

polar acorn
hushed hinge
polar acorn
hushed hinge
timber tide
#

Where did you read up on this tutorial btw just curious

#

I wouldn't suggest doing tetris games by aproximation in the future. You can easily just do a 2D array and check via index.

summer stump
#

So put the VALUE in there

jagged gulch
#

Evantually figured it out by doing this

#
                {
                    Vector3 direction;
                    Vector2 randomSpread = Random.insideUnitCircle * spread;
                    direction.x = randomSpread.x;
                    direction.y = randomSpread.y;
                    direction.z = 0;
                    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition + direction );
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit , shotgunRange))
                    {
                        Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
                        Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
                    }
                }```
slender nymph
# jagged gulch ```for (int i = 0; i <= numOfPellets; i++) { ...

just so you know, if you ever plan to visualize these rays, they don't start at the same place. the directions are also all just straight so you may even notice some issues with them potentially hitting things they wouldn't otherwise hit if you just randomized their direction a bit

unreal imp
#

ok again, I have a problem and it is due to the speed detection of an object when it collides with another, in my case if my toilet object collides strongly with the floor, or another prop or is shot, it will explode, but my problem The thing is that if I drop it at 200 meters for example and it crashes into the ground or something else, nothing will happen because it seems that the speed value is very small and to explode against an object it must have a certain speed, which is a public variable ( for example 7 speed and I am using rigidbody.velocity.magnitude)

slender nymph
# hushed hinge

holy hell mate, did you take that printing the integer 3 as what you literally need to do instead of just an example of how you can print relevant information to the console?

civic aurora
ashen ferry
#

XD

polar acorn
# hushed hinge

Okay, so, you should probably stop waiting for someone to write the code for you and instead read the words people are saying and put a bit of critical thinking into it

polar acorn
#

No one is going to write the code for you

civic aurora
slender nymph
#

is it printing the correct fill amount or is it printing 1?

civic aurora
#

its not printing it

slender nymph
#

if it isn't printing then that code is not running

unreal imp
slender nymph
unreal imp
#

mmm

civic aurora
#

im sorry it is printing it

#

i think its just not showing visually

hushed hinge
slender nymph
#

log the fillAmount before you change it as well

polar acorn
queen adder
#

Yall how to make the player not affected with gravity while dashing ,so it dashes on a staight line

hushed hinge
polar acorn
#

What is the thing you are trying to log

slender nymph
queen adder
slender nymph
#

probably also reset its Y velocity to 0 immediately before the add force as well

queen adder
hushed hinge
queen adder
polar acorn
summer stump
#

My code wasn't for you to copy..... it was an example.

hushed hinge
queen adder
#

WHY WOULDNT IT WORK 😭

slender nymph
polar acorn
slender nymph
queen adder
slender nymph
slender nymph
#

christ, mate

timber tide
#

:)

polar acorn
queen adder
polar acorn
#

Is that what you're trying to do

slender nymph
polar acorn
queen adder
hushed hinge
timber tide
#

You want to know their positional values to fix the issue

polar acorn
#

And it's been almost an hour and you haven't logged it

timber tide
#

first we need to log those values and print them to the console

slender nymph
hushed hinge
polar acorn
#

The

#

Position

hushed hinge
#

how do I Log the position?

polar acorn
#

you put the value

#

in the log

slender nymph
#

inb4 "Debug.Log("the value");"

polar acorn
#

Seriously, debug log should literally have been the first line of code you ever wrote

#

This should not be hard

#

this should have been squared away before you did anything else

timber tide
#

Neat, is that some unity AI

slender nymph
#

nah, it's vertx's site

polar acorn
timber tide
#

ah, I see

polar acorn
#

who got tired of answering the same questions so much he bought a domain and made a site

polar acorn
hushed hinge
#

I don't know what I am doing right now

slender nymph
#

yes that is clear

polar acorn
eternal needle
#

you should go do some basics of c# first

#

debugging shouldnt be the hard part of this

hushed hinge
polar acorn
#

Again, this should have been the first line of code you ever wrote. Every tutorial that explains unity will start with a debug log

#

If you didn't, you skipped an important starting step

hushed hinge
polar acorn
#

it's putting a variable in a log

ivory bobcat
hushed hinge
#

I know that but I still don't know what I'm doing with it

slender nymph
#

you've already been told you need to log the position(s) you are checking

ivory bobcat
#

You'd want to log the position and see what's not behaving as expected.

hushed hinge
#

what position?

slender nymph
#

do you just not know what your CheckIsValidPosition method does?

ivory bobcat
#

I'm assuming pos

polar acorn
#

Find out what position is not doing what you expect it to do

hushed hinge
polar acorn
# hushed hinge

So log the position so you can see what the last value of it was when it does something you don't expect

hushed hinge
polar acorn
#

in the log

#

as the parameter

civic aurora
hushed hinge
polar acorn
#

and pass in a variable

#

if not then you should not be doing any of this

#

you need to learn the basic syntax of C# first

#

Then make a game

hushed hinge
polar acorn
#

do not pass go

#

do not collect $200

hushed hinge
#

I do not collect

polar acorn
#

At this point, we cannot help you. You fundamentally do not understand enough C# to even get an answer at all. Even if we could get the logs to find the information enough to find out what the problem is, you would not be able to understand any solutions we give. We cannot go further until you learn how to at least communicate about code

hushed hinge
#

... I'm going to cut my wrists

slender nymph
polar acorn
hushed hinge
#

all I did was look at tutorials and did what they said and I don't get why this is happening with jsut the black and red tretromino

polar acorn
#

We are fundamentally unable to communicate any solutions to you until you at least know what code terms mean

hushed hinge
polar acorn
civic aurora
#

use chatgpt

ashen ferry
#

If I have a planet with slots and slots have resources you can mine + you can build buildings, some of them mine resources others craft stuff from inventory im just going at it but sphagetti is forming lol how would topology or how u call it look like, what is a slot what is a building how it all ties together

polar acorn
hushed hinge
ashen ferry
#

bro why u even arguing

civic aurora
#

it will tell you the problems and how to fix it

ashen ferry
#

bro u gotta give perfect prompt for it to do that and at that point its programming again lmfao

languid spire
languid spire
civic aurora
languid spire
#

because then you do not learn

timber tide
#

chatgpt is** a mixed bag. Even if you are trying to learn from it, you still need to distinguish from that it* may be wrong about

hushed hinge
timber tide
#

I've had some success learning some graphic apis earlier this month with it. It's pretty good when your questions are usually in the documentation as it does seem to be trained on it.

ivory bobcat
stiff anchor
#

!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.

languid spire
#

I still do not know what shape red and black are

hushed hinge
#

they are S ans Z Tetrominos

languid spire
#

Ok, so where is their pivot point, how do they rotate?

wraith mulch
#

ahhhh geez i dont know ive been making game for far too long already and i dont knwo what to do anymore... i already had it finshed, compressed the whole game folder to upload it to itch.io but then i noticed it occupies too much memory (around 1.50 GB) and i realised i absolutely forgot about optimizing it. then i started deleting some assets to optimize the game and i fully destroyed it. the biggest problem i have now is that when the player and the obstacle collide, the obstacle doesnt destroy and the game does not restart itself. it says i should use DestroyImmediate() method instead of Destroy(), but when I use it DestroyImmediate(), the console complains that "destroying components is not permited"
obstacle's script: https://gdl.space/bajewepuci.cs

hushed hinge
languid spire
#

so how can you rotate them if you do not know that?

short hazel
hushed hinge
languid spire
#

@hushed hinge It strikes me you have done an awful lot of copy paste and almost nothing in understanding what you are doing

hushed hinge
languid spire
timber tide
short hazel
#

Line 25 of ExplodedObstacle is probably the culprit, you do not use the result of Instantiate one line above it

#

Actually, it's line 27, you're calling this on the prefab

languid spire
wraith mulch
short hazel
#

Again it is because you are not using the return value of Instantiate on line 24

wraith mulch
#

i guesss i can just give up on the scaterring around part

short hazel
#

Compare with how you're doing it on line 36

timber tide
# hushed hinge I was only looking at tutorials

If you're going to follow tutorials, follow along and type as they do. Don't just pull their code from their repository. If you don't understand it after all that, do it again or ask questions here about specifics.

wraith mulch
#

should i write it like

GameObject scatteredObstacle = Instantiate(explodedObstacle, transform.position, Quaternion.identity);
        Destroy(originalObstacle);
#

?

#

ahhh wait how do you properly format it?

short hazel
#

And then use scatteredObstacle yes, on line 27

wraith mulch
#

remind me of how to format code blocks please ^^'

short hazel
#

```cs
// Code
```

wraith mulch
#

aaahhhh without the space

hushed hinge
#

it rotates from there

wraith mulch
hushed hinge
#

I asked in chatgbt and added more details to my saying for it to understand what is wrong with my script

languid spire
short hazel
#

Most of them use a 3x3 grid for rotations, except for the straight bar

languid spire
#

No, pivot should be between the blocks, not in the center of one of them

short hazel
#

Nope, if you do that, on half the rotations your tetrominoes will be misaligned on the grid

ivory bobcat
#

I think Tetris has them on individual blocks

languid spire
#

in a 3x2 pivot is at 1.5, 1

short hazel
#

The link I posted has images showing the pivots

maiden charm
#

struggling to GetAxisRaw

civic aurora
wraith mulch
#

aaahhhhh why do i have to be so duuuuuuummbbbbbb

#

it still tells me that it wants me to destroyimmediate

slender nymph
#

that means you're trying to destroy a prefab instead of the spawned instance

wraith mulch
short hazel
#

Make sure you're calling GetComponents* on the instance, not the prefab

#

Yup called it

#

Line 29

wraith mulch
short hazel
#

It's not relevant anymore because you're doing it now

#

The issue is that you're not using scaterredObstacle on line 29

wraith mulch
#

????

maiden charm
#

anyone able to help with this?

wraith mulch
#

wait should i use scateredObstacle instead of rbs?

slender nymph
maiden charm
#

but it doesnt work for me?

slender nymph
rich adder
#

its already a pos

wraith mulch
#

oh no wait instead of explodedObstacle, huh?

short hazel
wraith mulch
#

yeah omg im so stupid

polar acorn
short hazel
wraith mulch
#

but then i dont have to change anything on this line, right?

#

rb.AddExplosionForce(Random.Range(minForce, maxForce), explodedObstacle.transform.position, explosionRadius);

#

(line 32)

short hazel
#

You do, scatteredObstacle here too

#

For the position argument

wraith mulch
#

yupo thanks

#

also

maiden charm
rich adder
#

InputEvent doesn't have that method

#

you wrote the wrong class

wraith mulch
#

i want to destroy the originalObstacle when the player collides with it and i have it on line 36, but im not sure whether it'll work this way?

polar acorn
short hazel
wraith mulch
#

aaahhhhhh i wanna cryyyyyyy

wraith mulch
#

its just that i already got too much help from too many people on this game and so the game got really confusing

#

i had it all complete but i did not optimize it, and when i started deleting the assets i thought i didnt need anymore i basically deleted half of the game

wraith mulch
short hazel
#

ie. gameObject

#

You do not need originalObstacle because it would be like referencing yourself, it's unnecessary

#

You didn't drag-drop the object itself in the script's Inspector did you?

naive glacier
#

Hello guys, is this expected behavior for child prefab objects? I am trying to override the color but it keeps reverting back when I want to apply it

wintry quarry
naive glacier
#

Yup, I just realized that I have some stuff in OnValidate that are resetting the values back

#

I was freaking out for a while

queen adder
topaz coyote
#

Does anybody know how I can make it so that a Parent object always visually appears over its children?

I have a Prefab which contains a TextMeshProGUI as the main object/prefab source, and an image child I want to appear BENEATH the text. I could fix it so that the main object is the image, with the text as the child, but I just want to know if what I asked is possible, as it will make it much easier for me instead of having to re-write tons of different scripts.

timber tide
#

You can try canvas grouping

#

such that you create an additional canvas and then order them with that. Otherwise you can try swapping the hierarchy around at times but that's dependent on your use case.

#

"and an image child I want to appear BENEATH the text."
You can just add the text as a child to the image component

topaz coyote
timber tide
#

My reading comprehension is bad, but the grouping idea does work for some situations, though reading it again, yeah just child the text ;)

orchid trout
#

what's the smartest way to map all 20 faces of an icosahedron to values? UnityChanThink
I have a low poly mesh of the 20 triangle faces, but I'd like to return dice roll results from that

#

My naieve guess is that I could somehow convert vector3 euler angles to dice results? But I have no idea what vector values every face would be, seems error prone on my part trying to divine that info

#

that also might not work either because if the mesh isnt sitting perfectly flat, the euler will be some other value UnityChanThink

frosty hound
#

Smartest way would be pure math.

Friendly way would be empty objects placed in the center of each face rotated outwards with a simple component to give it a value property.

Either way, when the dice stops, you find the face whose dot value with world up is closest to 1 to get the most up facing value.

orchid trout
#

oh I see what you mean, game objects on each surface, that is very friendly but less cool than doing it with math
But I suck at math UnityChanThink

#

I'll try game objects for now but I feel like thats going to mess up the results because I won't be able to perfectly position each object's vector3 position dead center of the face

frosty hound
#

You don't need to always go the smartest route, the alternative is fine.

#

You don't actually need to position them perfectly, it's their rotation that matters. I only said put it on the face for visual ease.

orchid trout
#

ooh their rotation, not their position

#

I misunderstood that

ashen ferry
#

ayo new unexplainable issue just dropped how this could possibly keep printing that log if panel is already activated I use same thing in statement and activation so its same game object https://hatebin.com/jzdzhodumt

#

I already fixed it by referecing gameobject directly without getting it from animator but what the hell

jagged gulch
#

Having an issue with debugging, couldnt find any resource online with this issue, but Im trying to do Debug.DrawRay, but the rays only appear onscreen for a quick second before disappearing

#

not sure if its because I have debug.drawray in update() or something else but I dont know why they quickly appear and then vanish

#
                {
                    Vector3 direction;
                    Vector2 randomSpread = Random.insideUnitCircle * spread;
                    direction.x = randomSpread.x;
                    direction.y = randomSpread.y;
                    direction.z = 0;
                    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition + direction );
                    RaycastHit hit;
                    Debug.DrawRay(ray.origin, ray.direction * 100, Color.green);
                    if (Physics.Raycast(ray, out hit , shotgunRange))
                    {
                        Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
                        Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
                    }
                }```
ashen ferry
#

use overload where u can set its duration

north kiln
#

That's how they work. If you want them to draw for longer use the duration parameter or call draw repeatedly

jagged gulch
#

gotcha, sorry haven't used drawray in ages so I wasnt sure if thats what it was supposed to do

light arrow
#

I’m having trouble making my camera follow my character like have the camera alwsys behind my player even when I rotate but what I have now is it kinda rotated at a different speed than my player so it starts off behind my player then can end up infront of my player or to the side of it can anyone help me

wintry quarry
#

you can get the behavior you want in a few clicks instead of bashing your head against code

upper spire
#

is there any way to fire a ray or something similar, and then get the direction of its bounce? im trying to create a realistic mirror.

upper spire
upper spire
# wintry quarry sure, a raycast combined with https://docs.unity3d.com/ScriptReference/Vector3.R...
    public Transform mirrorcam;
    RaycastHit bounce;
    Vector3 bounced;
    public LayerMask mask;
    void Update()
    {
        Physics.Raycast(playercam.transform.position, mirrorcam.transform.position - playercam.transform.position, out bounce, Mathf.Infinity, mask);
        bounced = Vector3.Reflect((mirrorcam.transform.position - playercam.transform.position), bounce.normal);
        mirrorcam.transform.rotation = Quaternion.Euler(bounced);
    }

this is the code i wrote, im trying to reflect the way that light reflects off of real mirrors, but it isnt working. it wiggles on all axis, but very subtly. are there any obvious problems in my code?

steel girder
upper spire
# steel girder can u show the class initialization as well?

sure. here.

using UnityEngine;

public class MirrorEffect : MonoBehaviour
{
    public Transform playercam;
    public Transform mirrorcam;
    RaycastHit bounce;
    Vector3 bounced;
    public LayerMask mask;
    void Update()
    {
        Physics.Raycast(playercam.transform.position, mirrorcam.transform.position - playercam.transform.position, out bounce, Mathf.Infinity, mask);
        bounced = Vector3.Reflect((mirrorcam.transform.position - playercam.transform.position), bounce.normal);
        mirrorcam.transform.rotation = Quaternion.Euler(bounced);
    }
}
orchid trout
frosty hound
#

Awesome, nice work 🎉

wintry quarry
#

which is ????

#

Quaternion.Euler(bounced); makes no sense

#

maybe you wanted Quaternion.LookRotation(bounced);?

upper spire
upper spire
wintry quarry
wintry quarry
#

set to 0

#

equivalent to projecting the vectors on the x/z plane

sour fulcrum
#

with Unity's Script Execution Order, does that play nice with Inheritance or do I have to specify everything

ie. if i have UIManager before Inventory, Will everything that inherits from Inventory go after UIManager?

wintry quarry
unreal imp
#

Hey, if this code is being executed in the update, does it mean that rays will be generated continuously every time the E is pressed without deleting anyone? Is there a way to avoid it so that there is no lag? ``` void Update()
{
if (Input.GetKey(KeyCode.E))
{
objectAnimator = gameObject.GetComponent<Animator>();
ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit, interactDistance) && hit.collider.gameObject == gameObject)
{
InteractWithObject(gameObject);

        }
    }
    }```
timid quartz
#

Why is my sprite so offset from the origin? It's the only object in the prefab (there's no parent or children here) and yet it's really offset from where the actual object "is" for some reason

#

it means I have to offset the circle collider 2d to get it to match up

wintry quarry
unreal imp
#

welp,first of all is that true that i say?

wintry quarry
#

I have no idea what you are saying

#

the code will run every frame since it's in Update

#

beyond that I don't follow what you're saying

#

if (Physics.Raycast(ray, out hit, interactDistance) && hit.collider.gameObject == gameObject)

#

is this code you're trying to put on interactable objects?

unreal imp
verbal dome
#

Rays are temporary

wintry quarry
#

rays are not persistent objects that live in the world

unreal imp
#

because none of them are erased

wintry quarry
#

a raycast is just an instantaneous computation that happens

unreal imp
#

ahhhhhhh

wintry quarry
#

there is nothing created that needs to be erased

unreal imp
#

thanks so so so muchhhh 😘

wintry quarry
#

that being said this is very inefficient if this is a script you have on many objects in the scene

timid quartz
#

oh, I think I found my answer - this particular sprite is from an animation and I think the animation has it displaced?

wintry quarry
# unreal imp thanks so so so muchhhh 😘

you'd be much better off just having a single Interactor script on the camera that does a single raycast each frame. Rather than doing one raycast per interactable object.

wintry quarry
#

I just explained how to do it basically

#

you just do one raycast per frame. Call an Interact() function on whatever object you hit with that one raycast

unreal imp
#

oka

summer stump
wary delta
#

So OnCollisionStay won't work with a ray?

rich adder
summer stump
wary delta
#

I thought a ray would create a Collision or Trigger event on what it hit.

rich adder
#

A ray detects colliders

wary delta
#

yep, and in detecting them, I thought it could also activate them. I was wrong.

rich adder
#

right, thats something you code through the collider component when is found with araycasthit

wintry quarry
#

Rays don't "do" anything

#

A "Raycast" is a math operation in which you find the intersection of a ray and any colliders in the scene

wary delta
#

but it can "hit" something... it was just a misunderstanding

wintry quarry
#

No it can't

#

Raycasts hit things

#

Ray != Raycast

rich adder
#

casting is the physics part ye?

wary delta
#

it did to me a minute ago.

#

so does a raycast hit create a collision or trigger event on the object it hit?

wary delta
#

ok.

timid quartz
#

say I have a player and I want there to be an evil cloud that when the player enters the cloud, I want something to happen. should I put the collision script on the cloud or the player? and should I mark the cloud as a trigger or not? right now I have the script on the cloud and if it's a trigger the player walks through it without the special stuff happening (no collision reported) but if it's set as not a trigger, when the colliders touch the thing happens, but the player can't walk through

rich adder
#

trigger would be better no?

wintry quarry
timid quartz
#

when I do that then collision doesn't report

wintry quarry
#

"no collision reported" means you're likely just doing it wrong

#

Show what you tried

timid quartz
#

it's a very simple script...
void OnCollisionEnter2D(Collision2D other)
{
print("player entered!");
}

wintry quarry
#

OnTriggerEnter for triggers

timid quartz
#

OHHH

wintry quarry
#

Look up examples

timid quartz
#

thank you!

silent valley
#

Hi, is there a way to be able to make it so i can write the bool parameter of an animation in the inspector? I commented what I'm after. Hope it makes sense

timber tide
#

make a public bool, no?

cosmic dagger
wintry quarry
#

Or I guess a string if you meant the parameter name and not the value

cosmic dagger
#

Use a string to access the name for StringToHash to get its anim id or just use a bool variable to assign its value. Not really sure which one you want . . .

silent valley
#

What I want was the access the name. I'm aware about the public bool. So StringtoHash is the way to go?

rich adder
#

StringToHash is more efficient for the animator to lookup that parameter

silent valley
#

Thank you. I'll look that up

wintry quarry
#

To start with you can just use a string

silent valley
#

Thank you. 🙂

valid finch
#

I want to remove a game object from the scene when the player collides with it. Can I delete items from the scene with a certain tag from within my playercontroller script?

#

I already set it to change the animation on the player after they collide with the tag, was just wondering if I could also destroy the item with that tag from the scene, since it is a unique pickup. not like coins or whatever

#

or any better way to go about removing it from the scene. doesn't have to be destroyed.

#

But, I don't want the player to be able to see or collide with it anymore

polar acorn
valid finch
#

How would I go about that. The item in the scene doesn't have a script attached to it.

rich adder
#

but has a tag?

valid finch
#

I was just using the item to change animation state of the player

polar acorn
valid finch
#

private void OnTriggerEnter2D(Collider2D football)
{
thisAnim.SetBool("hasBall",true);
}

rich adder
#

if(football.CompareTag("YourTag"))

polar acorn
valid finch
polar acorn
valid finch
#

So it shouldn't fire unless a player touches it right? Or am I missing something

polar acorn
#

It will fire when the player touches any trigger. Is that what you want

valid finch
rich adder
#

thats not a tag

polar acorn
valid finch
#

Collider2D football) << I thought this is where the tag went

valid finch
#

but.. that doesn't make sense. Navarone what you said about the compare tag is right

#

sorry for the dumb question.

polar acorn
rich adder
#

the parameter name is just for you

polar acorn
#

It could literally be anything and the code would be identical

#

It could be Collider2D TheChungasAmongus and the code would be unchanged

valid finch
polar acorn
valid finch
#

Thanks for the link navarone. Sorry I need to brush up badly. Lots of stuff I don't remember.

#

So I can just use the if tag compare within my method

valid finch
#

I made a public gameobject football
So I could assign the football in it so I can destroy it from within the playercontroller.

Is there a better way to go about that. I am thinking that when the ball is fumbled or thrown.. the public gameobject football won't be set because I had to manually drag it in.

#

!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.

valid finch
#
 private void OnTriggerEnter2D(Collider2D hasFootball)
 {
     if (hasFootball.CompareTag("Football"))
     {
         Destroy(football);
         thisAnim.SetBool("hasBall", true);
     }
 }
rich adder
cosmic dagger
#

true, that sounds like a bool variable . . .

rich adder
#

should just be Destroy(collider.gameObject);

#

iirc colliders like transform, always have access the object their on

valid finch
#

So I am thinking I should probably not destroy the football. when collided with

rich adder
#

any component pretty much if its on a gameobject lol

rich adder
#

you're doing stuff to it, after tag checks out

#

Collider2D is the thing you collided with

valid finch
#

So after they collide with the football the animation changes to look like its carrying the ball. If I do destroy the ball from the scene.. is it possible to place an object back into the scene if it isn't in the heirarchy?

#

if that even makes sense..

rich adder
#

easier to just deactivate the object if you plan on spawning the same thing

valid finch
#

Yeah I do just plan on only having the one football.

#

That can be fumbled handed off and passed

rich adder
#

yeah you can reset positions and move it around even if its deactivated

#

as long as you have the transform referenced

valid finch
#

the game object isn't actually attached to the player, I use the animation to show it is being held

#

So should I put a script on the football to follow the player, while it is deactivated?

rich adder
#

no deactivated objects dont run script afaik

valid finch
#

shit

#

lol

rich adder
#

just set its position when you need it, or parent it

#

parenting essentially follows it without needing a script

valid finch
#

There are going to be a bunch of players. I'm gonna have to look into making the football become a child of whichever player has it

#

Or I could add in the player script, when they pass the ball. reactivate the football, and then give it the players current transform?

rich adder
#

you could also just have a main script that keeps the ball following whoever has control of it

valid finch
#

football.transform.parent = transform;

#

something along those lines..

#

I like the gamecontroller script idea

rich adder
#

could even be BallController

valid finch
#

for keeping score.. stats.. time.. ball possession

rich adder
#

ideally you want a a script to only deal with one thing

valid finch
#

Do you find it better to keep all of that stuff in one script

#

or is it cleaner

#

ahh alright, that's what I was wondering

tropic crown
#

Im trying to toggle a UI visibility using code and and an if statement to show a you died screen if health reaches 0, but I cannot for the life of me figure out what to put in the if statement to toggle the UI on??? please help

valid finch
#

What is your PFP of navarone. It looks bad ass btw lol

north kiln
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)

north kiln
#

It should not say Miscellaneous Files in the top left

valid finch
rich adder
tropic crown
#

how do I do that?...

valid finch
#

Those links provided above

#

follow those, and you will be in a happy world of coding.

valid finch
rich adder
valid finch
#

So with that main script that makes the ball follow the player. If football is deactivated. It would still be able to follow the player, since the code making the football gameobject move is on another FootballController gameobject

rich adder
tropic crown
#

I assume its pretty simple I just dont know what im doing

rich adder
#

show us its configured @tropic crown

tropic crown
#

doesnt say misc files

rich adder
#

looks good !

#

saved yourself future headaches / syntax errors 😛

tropic crown
#

ty

rich adder
tropic crown
#

I have a UI of a black screen and a child text that says you died*

rich adder
#

you have that gameobject / blackscreen referenced yet?

tropic crown
#

I believe so

rich adder
# tropic crown

I assume you died is on the gameobject you want to toggle ?

tropic crown
#

yeah

rich adder
#

it would just be youDied.gameObject.SetActive(true);

tropic crown
rich adder
#

eh u used a _

#

dont copy verbatim lol

tropic crown
#

yeah yeah

#

got it

#

ty

valid finch
#
 private void OnTriggerEnter2D(Collider2D collider)
 {
     if (collider.CompareTag("Football"))
     {
         thisAnim.SetBool("hasBall", true);
         football.SetActive = (false);
     }
 }
#

won't let me do that within a method group

worn harbor
#

Hey guys, does anyone know what I did wrong? Lets say I have a GameObject that has a script connected to it that is using OnDrag, OnBeginDrag and OnEndDrag.

This is the script (Test Script)

https://paste.ofcode.org/cUMhXZXezDUVHJzdPbLGzw

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class TestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
    }
}

Now on the GameObject, I added an Event Trigger in which I added the Begin Drag, Drag, and End Drag and I conncted the same GameObject with the script to it.

But for some reason when I looked up the function, the options for OnBeginDrag, OnDrag, and OnEndDrag weren't there.

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.

white yew
valid finch
white yew
rich adder
#

methodsHaveParenthesis(somethingHereSometimes)

white yew
#

The problem here is that you have a equal sign there. I am unsure if this was intentional, or by accident.

valid finch
#

I was just trying to disable the game object and i saw that SetActive was the way to go about that

#

I was trying to do it within my if statement

rich adder
#

methods don't use =

valid finch
#

Ohh shit

#

ffs

rich adder
#

when in doubt always look at the !api

eternal falconBOT
valid finch
#

i get you both now.. just so used to always using = when writing true or false

valid finch
#

right and the setactive method im using is false

rich adder
#

not only for bools

white yew
#

Try Pomodoro timing. Helps destress your brain for long stressful work environment.

#

I'm surprised that your IDE doesn't tell you that you have a problem here.. Would recommend reading the pinned #854851968446365696 post @valid finch

valid finch
#

It did tell me it was a method. and gave an error

#

I wasn't thinking about the =

distant current
#

is it a good idea to use scriptable objects for switching scenes? I want my player to keep his position as where he enter when he gets back to previous scene and also keep the data like the inventory and when the player picks up an item from previous scene and switch to another scene then get back, the item shouldn't be there

white yew
#

Or have the player save information before loading a new scene, and then instantiate the player after scene loaded.

valid finch
white yew
#

Scriptable Object should be used as a template instead of items.

rich adder
white yew
#

I should program in c more often..

valid finch
#

Kind of like the Update() is internal

rich adder
#

yea Update is calling the C++ side

white yew
#

Isn't it backward? Update is called from the c++ side...?

rich adder
#

unity's c# is just an API essentially to the c++ engine

valid finch
#

Any good google search ideas to find a list of internal built in methods within C#

rich adder
valid finch
#

Like a list of things like Update() Start() FixedUpdate()

#

are there more I am missing

white yew
white yew
rich adder
valid finch
#

Gonna get back to work. Just a random question, out of curiosity is it possible to change executionOrder. I don't need to do that, just like to learn some new stuff

#

And like to know limitations

zenith cypress
white yew
#

As per the actual Unity execution order - no. You cannot change Unity's event flow.

white yew
valid finch
rich adder
#

kinda wild how empty Update/Events can still allocate resources

white yew
#

This seems excessive... To go as far as to change the game engine's loop order...

rich adder
white yew
#

If it's flawed, it wasn't considered initially.

zenith cypress
#

I've used it in a few projects where I just needed a renderer and my own execution loop TT_laugh It's quite nice

white yew
#

Speaking of dangerous code, I'm dealing with JNI and unity's interops.

north kiln
#

I probably wouldn't reorder it but injecting stuff is very normal 😄

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.

valid finch
#
 private void OnTriggerEnter2D(Collider2D collider)
 {
     if (collider.CompareTag("Football"))
     {
         thisAnim.SetBool("hasBall", true);
         football.SetActive (false);
     }
 }
------------------------------FootballController Code Below

 void Update()
 {

     football.transform.position = following.transform.position * Time.deltaTime;
 }

#

The ball gets disabled upon triggering, but the hasBall animation isn't activating.. is it happening too fast or something?

#

Cuz It is definitely immediately moving to the player's location

rich adder
#

also whatsu up with that Time.deltaTIme on the follow code lo

valid finch
#

nothing is showing up even though I'm getting the default running animation. although it should be the hasBall animations

#

The running animations are working as they should

#

but not transitioning anymore. They used to transition when I had the ball not following the player

rich adder
#

also show transition for hasBall

valid finch
#

The animator isn't showing realtime inputs while in gameview though

#

That time.delta time was messing it up or something..

#

Just curious why the animator isn't showing live blend tree changes while playing

#

It's not a giant deal right now. Was just wondering why it isn't showing. Gonna call it a night shortly.

rich adder
#

its a bit tricky

valid finch
#

Oh.. damnit

#

always the most simple shit. I had the scene selected not the player..

rich adder
#

usually is..
when I started and wondered why none my transitions were working :p

valid finch
#

I wish I could move my blend tree around like I can with the base layer

#

thats just nitpicky stuff. it really doesn't matter

#

Goodnight, thanks again

fossil tree
#

A people know how i can make a local game ? Like i use 1 controller for control my char and the other people use a other controller

ivory bobcat
fossil tree
solid coral
#

How to avoid such code duplication in classes? They have a difference of a couple of fields.....

modest dust
#

Inheritance

solid coral
#

I use interfaces, due to the fact that multiple inheritance is prohibited 😦

modest dust
#

I mean

solid coral
modest dust
#

You can just create a base class with all the common fields

#

and inherit from that

ivory bobcat
#

Definitely ought to couple the shared members into a single base class if they do the same thing.

modest dust
#

Or, if inheritance is really not what you want to do

#

Then you could create a class / struct inheriting from nothing, containing all the shared members

#

and have it as a field

ivory bobcat
#

Correct, not everything needs to inherit MB

solid coral
#

what's wrong?

#

maybe I should write a code, not a screenshot?

ivory bobcat
#

A class would inherit item and interface the iweapon.

solid coral
#

I didn't understand(. please rephrase

wanton prism
#

interfaces cannot inherit from classes

solid coral
#

but what should I do if the code in Item is the most repeatable

gaunt ice
#

c# not allow multiple inheritance
so you should first define a base class inherits from SO then your custom class inherits from this class
or use composition instead

wanton prism
#

C# allows you to inherit from multiple interfaces, but from only one class. Try to change Item from abstract class to an interface.

nimble kernel
#

Hello everyone !
I need some help simulating/triggering a mouse click in the interface of my game.
In my game, the player can use either keybaord+mouse or a controller to play. I and them to be able to use the controller in the menu of the game.
Since the interface of the menu is not a usual grid with horizontal/vertical movement between things, it's not great to simple show the focused button, and I have chosen to have the controller move the mouse in the menu, even though I know it's not a great UX.
I have already written some code that let me move the mouse with the joystick of the controller (without preventing mouse movement at the same time), but I can not figure out how to make it click the mouse.
Here is my current code :
https://hastebin.com/share/ogutupacaj.java
This code is called in the Update function of my menu.
Can you guys help me ?

solid coral
#

is it possible to inherit an interface from an abstract class?

stiff birch
#

An interface can't inherit from anything

solid coral
#

the first screenshot is the code that gpt wrote... I was deceived(((

stiff birch
#

Don't use GPT...

#

Unless you already know how to code, and know how to differentiate working and non-working stuff, it's a very bad tool to code

ivory bobcat
#
SO Item
SO Weapon : Item
SO Range : Weapon
SO Melee : Weapon
...``````cs
SO ItemsInGame
  Item[] items;```
neon ivy
#

anyone have experience with the UnityGoogleDrive plugin? not sure what this means

#

nvm, turns out I wasn't handling the url correctly

#

problem solved, now I have a byte[] of a .obj / .fbx file. how do I turn it into a unity object?

final kestrel
#
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class CharacterControllerFrom0 : MonoBehaviour
{

    CharacterController _characterController;
    [SerializeField] private float _moveSpeed = 2f;
    [SerializeField] private float _jumpStrength = 2f;
    [SerializeField] private float _gravity = -9.81f;
    private Vector3 _velocity;
   


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

    // Update is called once per frame
    void Update()
    {
        MoveForward();
        ApplyGravity();
       
    }

    private void MoveForward()
    {
        _characterController.Move(transform.forward * Time.deltaTime * _moveSpeed);
    }

    private void Jump()
    {
        if( Input.GetKeyDown(KeyCode.Space))
        {
            
        }

    }

    private void ApplyGravity()
    {
        _velocity.y += _gravity * Time.deltaTime;
    }
}

Hey all. I'm using character controller component and this is my code. I'm trying to apply gravity but cannot seem to get it work.

slender nymph
#

you need to actually use that _velocity variable somewhere

ivory bobcat
#

Apply gravity before moving

#

Also with CC you'll want to multiply gravity by delta time twice

final kestrel
#

Thanks.

sullen rock
#

"A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details."

uh.... how tf did I manage to create a memory leak in C#

slender nymph
#

have you been using any native collections in your own code (such as with the jobs system)? if not, then it's likely just an editor error and you can restart the editor if it bothers you

sullen rock
#

IEnumerators belong there, dont they?

slender nymph
#

no

sullen rock
#

in that case I dont think I have

slender nymph
#

i'm not talking about the System.Collections namespace. i'm referring to unmanaged data structures that unity provides in its code base

#

like NativeArray and NativeList

sullen rock
#

I dont think Im using any of that considering I dont even know what they are

slender nymph
#

well then if the error bothers you just restart the editor

sullen rock
#

huh

#

well that worked

#

thanks

#

aaand... its back, lol

slender nymph
#

and again, if you are not using any native collections in your code you can safely ignore it as it is likely just an editor error

sullen rock
#

Im just gonna pretend its not there until it breaks something

sullen rock
slender nymph
#

use the profiler if you have performance concerns

unique hull
#

Hello everyone , i cant seem to get Cursor.Setcursor to work / Appear in my project

#

Is there any packets or something that i need to have before it works?

unique hull
unique hull
ivory bobcat
#

Case sensitive

#

It should be Cursor.SetCursor

unique hull
#

That was becouse i wrote it in discord

#

But it doesnt exist as a function even

slender nymph
#

you've probably made your own Cursor class or a variable called Cursor

unique hull
#

Checked that , nothing called cursor

verbal dome
#

You have using UnityEngine, right?

unique hull
covert matrix
#

hi im trying to make a gameobject active when pressing the Z key while the player is colliding with an npc.
the player does stop when the player's and npc's collider hits, but nothing shows up on console logs when they do, so pressing Z does nothing
https://gdl.space/ibelesanaw.cs

slender nymph
verbal dome
# unique hull

Does your IDE detect other unity classes (is it configured)?

unique hull
#

I found the problem

#

UIElements has a Cursor function

#

Ill just have to make a new script for the cursor specificly for this one.

Thanks for the help 🙂

slender nymph
#

just use the fully qualified name UnityEngine.Cursor or a using alias

unique hull
covert matrix
ivory bobcat
#

OnTriggerEnter2D implies you're doing a trigger event rather than a collision event. Also 2d.

#

Then use the non trigger variant

#

OnCollisionEnter2D

#

With parameter type Collision2d

covert matrix
#

hmm after changing it to

    {
        Debug.Log("player colliding with npc");
    }```
it still isnt working
spiral glen
#

how do you make the camera consistent with different monitors?

slender nymph
#

care to be more specific about what exactly you are referring to?

spiral glen
#

When running my code as a program it makes everything really small when in the unity editor it's the right size

slender nymph
#

are you referring to your UI objects being the wrong size/location?

spiral glen
#

Gimme a sec I'll get a screenshot

#

The red box is what it looks like on the unity editor

slender nymph
#

so yes, your UI. see the documentation pinned in #📲┃ui-ux to learn how to anchor and scale your UI objects

spiral glen
#

swag ok

steel kestrel
#

I want the Agent to start jumping from the beginning after a fall, but it seems that it won't recalculate the path unless I execute Agent.CompleteOffMeshLink(). How should I prevent it from recalculating the path?

strong parrot
#

My project has audio files that get generated in real time. Whats the best way to add the audio to an audio source while the project is running?

rare basin
final kestrel
#
 void Update()
 {
     ApplyGravity();
     MoveForward();
     Jump();
 }

private void Jump()
{
    if( Input.GetKeyDown(KeyCode.Space)&& IsGrounded())
    {
        _velocity.y += Mathf.Sqrt(_jumpHeight * -2.0f * _gravity*_gravityMultiplier);
    }

}

private void ApplyGravity()
{
    if (_velocity.y < 0 && IsGrounded())
    {
        _velocity.y = -2f;
    }
    else
    {
        _velocity.y += _gravity * Time.deltaTime;
        _characterController.Move(_velocity *_gravityMultiplier* Time.deltaTime);
    }
    
}

When my character executes the first couple jumps it sometimes lands right on the ground and sometimes below it. What is causing this?

wintry quarry
#

CC behaves best with a single Move call per frame

final kestrel
wintry quarry
#

Simply add the two vectors you would have used for the two individual Move calls

#

And call it once on the sum

final kestrel
final kestrel
#

oh you mean move in apply gravity?

wintry quarry
#

probably in ApplyGravity() I would just adjust the _velocity

#

likewise in MoveForward()

#

then elsewhere do the actual Move with the combined values

final kestrel
#
  void Update()
  {
      ApplyGravity();
      Move();
      Jump();
  }

  private void Move()
  {
      _characterController.Move(transform.forward * Time.deltaTime * _moveSpeed);
      _characterController.Move(_velocity * _gravityMultiplier * Time.deltaTime);
 
  }

  private void Jump()
  {
      if( Input.GetKeyDown(KeyCode.Space)&& IsGrounded())
      {
          _velocity.y += Mathf.Sqrt(_jumpHeight * -2.0f * _gravity*_gravityMultiplier);
      }

  }

  private void ApplyGravity()
  {
      if (_velocity.y < 0 && IsGrounded())
      {
          _velocity.y = -2f;
      }
      else
      {
          _velocity.y += _gravity * Time.deltaTime;
          
      }
      
  }

I did this

wintry quarry
#

that's still two Move calls per frame

#

the idea is combine them into one

final kestrel
#

Ah okay so you mean do the vertical and forward movement in one cc.move

wintry quarry
#

e.g.

  private void Move()
  {
      Vector3 horizontalVelocity = transform.forward * _moveSpeed;
      Vector3 totalVelocity = _velocity + horizontalVelocity;
      Vector3 totalMovementThisFrame = totalVelocity * Time.deltaTime;
      _characterController.Move(totalMovementThisFrame);
  }```
final kestrel
#

So I was moving twice per frame before

#
 private void Move()
 {
     horizontalVelocity = transform.forward * _moveSpeed;
     totalVelocity = _velocity + horizontalVelocity;
     totalMovement = totalVelocity * Time.deltaTime;
     _characterController.Move(totalMovement);
 }
``` now Its like this
#

Uhm okay. Can you explain how this solved the "going below the ground" after jumps?

#

Was it that I was moving too fast to detect the collision?

foggy canyon
#

Hey guys
I am new here
Hey can someone help me?
i have a Unity project more than 2GB, till now i used Git for version control but now git do not cover 2gb or more file size for version control in free plan
which version control do you guys use?

safe radish
#

I'm thinking about how to implement stats for my units. i want them to have individual values x their jobs base stats. would it be a good idea to give the iv's and stat calcs on the units stat script and keep the base stats of jobs in a pure c# class?

rich adder
rare basin
#

Hello. I have a game that I need to Instantiate 500 objects of the same prefabs on start in random position (2D Sprites). What is the best optimization idea for this? I feel like doing for with 500 iretarions is bad idea

rich adder
oblique ginkgo
rich adder
#

yup, something to keep in mind

oblique ginkgo
rich adder
rare basin
rich adder
#

do it in a Coroutine

#

it should at least help freezing

rare basin
#

1 per frame?

foggy canyon
# rich adder Git . you're probably not using `.gitignore`

so here is detailed issue:
i used to work from macOS
i created a project there, worked on it for a month,
YES, do use gitignore. My .gitignore file code is exactly copied from the Git unity template for gitignore
it worked well till now when i was on MacOS
but i just purchased Windows yesterday and today when i do git clone with the link
it clone the project in local but here is the bug:
"ImportFBX failed" and i cannot see any mesh renderer

safe radish
foggy canyon
#

all my mesh renderer are missing
ALL PREFABS mesh missing and it is NOT PINK but white or transparent and missing

oblique ginkgo
# rich adder do it in a Coroutine

Can probably do this, I still recommend running the instantiation in a loading sequencce so the player doesn't see the freezing while they instantiate

rich adder
#

true

#

put it in a loading screen

rare basin
#

load scene async, put loading screen

rich adder
oblique ginkgo
#

I'm not sure if Awake methods are part of loadsceneasync, but if they are then instantiate in awake.

rare basin
#

and when the scene loads and and all objects are instantiated then remove the loaiding screen with nice fade out

foggy canyon
rich adder
rare basin
#

still, should i do it in a coroutine? async loading + coroutine 1 object per frame

rich adder
#

never modify a SO for base stats

rare basin
#

or async loading and 500 iteration for loop?

oblique ginkgo
rich adder
#

for loop can just be thrown in the corotuine

rare basin
#

but then 500 frames (1 object per frame)

#

capped at 30fps

#

will take some time, no?

oblique ginkgo
rare basin
#

im talking just pure for or for with yield return

oblique ginkgo
#

Benchmark it out, see how many instantiations you can do per frame without freezing

rare basin
#

i am capping my game framerate for mobile platform to 30fps, to if i am about to instantiate 500 objects that will take 500 frames approx

rare basin
#

thank you for the ideas

foggy canyon
rich adder
rare basin
#

also i want to avoid spawning objects in the same position as my other object

#

any idea how to achieve that?

#

pick random position, do overlapbox2d and check if there is any object inside that box

#

if yes, repeat?

rich adder
#

checkbox

rare basin
#

if no, spawn?

rich adder
#

or overlap sure

rare basin
#

yea ok

oblique ginkgo
#

Overlap would work yes

rare basin
#

i wonder how will that be in optimization wise

oblique ginkgo
#

By the way,

rare basin
#

cuz i can see a sitaution where it's at 499 iteration and there is not much space

#

and its trying to find empty space al ot

polar acorn
rich adder
rare basin
#

okay

oblique ginkgo
#

Quoting lordofduct off the unity forums here:

How Awake and Start is setup it's:

  1. You call LoadLevelAsync (you may not have, this is step 0, because the game may have just been started and steps 1 and on still occur)

  2. Load of scene occurs, objects get deserialized and created.

  3. Once everything is created, Awake is called on all scripts. It is safe to grab references to other objects in scene, BUT those objects may or may not have had Awake called on them.

  4. All enabled/active scripts have Start called on them. This is guaranteed to happen after ALL Awake calls. So intercommunication between scripts is cool.

  5. If LoadLevelAsync, and you yielded the AsyncOperation, this will now return. As far as I can tell it's the frame FOLLOWING the 'Start' call on all the objects loaded.

So you can run all this in a loading screen, yes.

polar acorn
#

You shouldn't feel bad about using any of them as much as you need to, they are unilaterally faster than any sorts of alternatives

rare basin
#

idk if you have followed the context

polar acorn
#

Obviously doing nothing is better than doing anything, but the physics methods are designed to be used frequently

oblique ginkgo
#

if its not already

rare basin
#

if i understand correctly

oblique ginkgo
#

Yeah, Awake or Start

rare basin
#

cool, tysm

west arch
#

So I have ton of string contents in scriptable objects that are remote addressables. I need help with how to work with dynamic contents like this. I meant I've searched any localization tutorial but must of them just a simple tutorial like localization in the build. In my case these string contents is a CDN which is downloadable later by user. Someone enlighten me please!