#💻┃code-beginner

1 messages · Page 38 of 1

wintry quarry
#

Read what it says

mossy arrow
#

THIS!??

summer stump
#

What is the difference between mine and yours?

mossy arrow
#

this

slender nymph
#

something is missing

#

there you go

mossy arrow
#

so like im a pro now?

slender nymph
#

you should really consider going through some beginner courses to learn wtf you are doing. Debug.Log should have been like the first line you wrote in unity

mossy arrow
#

why is no one talking

elfin eagle
mossy arrow
summer stump
slender nymph
mossy arrow
mossy arrow
shell sorrel
#

if you missed that, you did not follow the basics

summer stump
mossy arrow
shell sorrel
#

learning about debug or print call for any langauge is like first 10 mins of learning shit

slender nymph
mossy arrow
slender nymph
#

no, i'm just going to block you since you clearly don't know wtf you are doing and you refuse to actually take the time to learn

swift crag
#

how about you stop wasting our time and go learn the fundamentals of programming

#

it's really not that much to learn, but you really do need to put in some amount of effort on your own

mossy arrow
#

there we fixed it

heady nimbus
#

I should probably just look at this more tomorrow when I'm not so tired but I can't get this enemy to reverse direction when it hits a wall. It does it when it finds the end of the platform, but then just slams into the wall and stops... It's probably something very stupid...

https://hatebin.com/avifwbymtr

summer stump
#

So it it is grounded, it never evaluates the wallcheck

#

Also, looks like you do two wallchecks, but the first isn't actually used?

heady nimbus
#

Ah yea shit the first was to make sure the gizmo was actually drawing correctly, forgot to take it out..

round scaffold
#

this is gonna sound real dumb

#

but i have an interaction system that calls a function on an object when its close enough

#

is there a way to let that object know what called its interact function?

shell sorrel
#

make the first arg of the function be the calling object

#

then when you call it just pass a this reference

round scaffold
#

wack

#

thank u mr knight with horns

copper perch
#

Can anyone help me with my ammo pick up for my fps game.
The ammo pick up script below is not working with the UI script and the Player Manager script.

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

public class AmmoPickUp : MonoBehaviour
{
    public AudioSource pickupSound;
    public int ammoToAdd = 20; // Number of bullets to add when picking up one clip
    public string ammoType = "DualGlock"; // Type of ammunition (can be "Pistol", "Shotgun", etc.)

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            // Play the pickup sound
            pickupSound.Play();

            // Update the player's ammunition count based on the ammo type
            PlayerManager.Instance.AddAmmo(ammoType, ammoToAdd);

            // Add bullets to the total bullets count
            PlayerManager.Instance.totalBullets += ammoToAdd;

            // Destroy the ammo pickup object
            Destroy(gameObject);
        }
    }
}```
heady nimbus
#

Ok so I think it's a problem with the way I'm reversing direction because if I put a wall in front of the enemy, it WILL reverse off that, but will not reverse again

rich adder
#

put a debug.log inside the trigger

slender nymph
rich adder
#

i smell gpt 😮

slender nymph
#

yeah there's a lot of unnecessary comments here

rich adder
#

// Destroy the ammo pickup object Destroy(gameObject);

#

haha no shit gpt

round scaffold
#

whats the error

Assets\Inventory system\Scripts\InventoryContainer.cs(13,25): error CS0246: The type or namespace name 'GroundItem' could not be found (are you missing a using directive or an assembly reference?)

#

am i missing some kind of reference?

slender nymph
#

do you have a type called GroundItem

round scaffold
#

yea

slender nymph
#

where

round scaffold
#

its just this

rich adder
#

huh..

#

they must be in two different assemblies or something

slender nymph
#

it doesn't look like it, but just to be sure is that class in a namespace?

cosmic dagger
round scaffold
#

i dont think so

#

my inventory script is inside an assembly

#

is that the problem

queen adder
#

Try recompiling...

cosmic dagger
#

do the class name and the file name for GroundItem the same?

north kiln
queen adder
#

It can sometimes be that.

slender nymph
cosmic dagger
#

did you save the GroundItem file?

north kiln
#

Do you mean under an assembly definition?

lean grove
#

Wrapping all your code in a specific namespace schema will do wonders

cosmic dagger
#

oh, just read the assembly comment. that's most likely it . . .

round scaffold
#

alrighty lemme try lol

ashen ferry
#

I want to instantiate/destroy some prefabs while in edit mode I didnt try anything yet but whats the idea would execute always attribute suffice or not

rich adder
lean grove
#

One day…

slender nymph
#

hopefully sometime next year 🤞

lean grove
#

Or the next

queen adder
round scaffold
#

how i do that just opening and closing it?

slender nymph
#

that's not going to magically make one assembly have a reference to another

rich adder
#

if you're using assembly defintions make sure you include the correct one

queen adder
#

Go to Preferences - External Tools, and you'll see a button that says "Regenerate project files".

queen adder
heady nimbus
#

Is Quaternion.Euler "amount to rotate" or "set rotation to"?

rich adder
slender nymph
queen adder
#

I got a question about custom inspector script. Is it viable to post it here or in code-advanced?

rich adder
heady nimbus
#

Ok so I'm not using it correctly then. What would I want to use as an "amount to rotate"

shell sorrel
#

also i tend to avoid Euler where i can, oftne better ways to do things

queen adder
round scaffold
#

i decided just delete all my assemblies and take the headache later when the project actually gets big enough to care

#

cant hve problems when u erase them from thier virtual existenc

cosmic dagger
rich adder
#

yeah compartmentalized af in the beginning . Overkill

shell sorrel
#

really would avoid them unless you have a reason to isolate certain things

#

and want to ensure a system is easy to move between projects

cosmic dagger
shell sorrel
#

even in a very large project at work, we only have a handful of extra asmdefs or precompiled assemblies in use

#

and that is mostly for things we use more like a library

heady nimbus
#

Nevermind, I'll just flip localScale, that seems easier for now. Lol. But yay! It's working

shell sorrel
cosmic dagger
#

see, that sounds cool . . .

shell sorrel
#

our behaviour system has one too, since it was useful being able to use internal to properly encapsulate things

cosmic dagger
#

that's what i need to start doing: change my classes to internal from public . . .

worthy veldt
#

i used OnPointer events for my buttons, and now i want to display item information UI when mouse is hovering over item slot.

even though this preview UI is set to ignore raycast, this new instantiated UI is obstructing and thus executing OnPointerExit. how do i make it behave like it doesnt exist or do i have to change and write raycasts from scratch

upper spire
#

how can i get the material of the face a raycasthit variable hit?

queen adder
#

how to make this Task class nullable, but still visible in the inspector? I cant null it since the class is serilized

wintry quarry
queen adder
#

[Serializable]
public class Task
{
    public int priority;
    public Vector3 position;
    public Skills required;

    public Task(int priority, Vector3 position, Skills required)
    {
        this.priority = priority;
        this.position = position;
        this.required = required;
    }
}```
wintry quarry
north kiln
cosmic dagger
wintry quarry
worthy veldt
#

sec

wintry quarry
#

Which Is what your original comment seemed to imply

worthy veldt
cosmic dagger
wintry quarry
lean grove
upper spire
#

something about a triangleindex

wintry quarry
lean grove
upper spire
wintry quarry
#

Does your object actually have multiple materials?

wintry quarry
#

Then yeah see which submesh the triangle is in

worthy veldt
upper spire
worthy veldt
#

owh, really. i had to write my own raycast before just to finish the job

#

i'd love to know whats wrong this. ill check again

wintry quarry
#

Disable raycast target on it

wintry quarry
#

Probably best to build a Dictionary to map it beforehand

#

Otherwise it will be quite slow

upper spire
#

im so dumb imdumb

upper spire
static cedar
static cedar
#

Tbh, at that point, just make an attribute so it's reusable. UnityChanThink

sturdy lintel
#
using System;
using UnityEngine;

public class TravellingBalls : MonoBehaviour
{
    private Vector3 startPoint;
    private Vector3 endPoint;
    private Vector3 direction;

    private GameObject travellingBallPrefab;

    private float speed = 6f;
    private float lifeSpan = 10f;
    private float spawnInterval = 1f;

    void Update()
    {
    }
}

I want to modify this script such that:

  1. the travellingBalls will always stay on the lineSegmentLayer while translating between the startPoint & endPoint. Note that these 2 points can change their position, then the balls should change their path.
  2. The balls will destroy themselves after the lifeSpan (in seconds) is over
  3. The balls will keep on being generated after the spawnInterval (in seconds)

I want to achieve the following without the use of lerp, slerp, lookAt(), coroutines.
Can anyone please help me out ??

rich adder
#

spawnInterval should be handled by a ball spawner

#

same with spawning and timed lifespan

static cedar
#

Why lifespan too? UnityChanThink

#

Actually nvm.

#

Unless he wants it to vary to each ballsssss.

rich adder
#

is easier to let the spawner destroy what it spawned

sturdy lintel
static cedar
#

First make a ball spawner class that inherits from monobehaviour.

sturdy lintel
teal viper
#

Try to write some code and come back if it doesn't work.

#

Don't expect people to write the code for you.
Also provide more info on why you don't want to use lerp?

static cedar
#

I don't think he knows that ngl.

sturdy lintel
#
public class TravellingBalls : MonoBehaviour
{
    public GameObject travellingBallPrefab;
    private GameObject travellingBall;

    private Vector3 startPoint, endPoint, directionOfTravel;
    private float speed = 6f, lifeSpan = 10f, spawnInterval = 1f;

    void Update()
    {
        Debug.Log(startPoint + " " + endPoint);
        this.transform.position += directionOfTravel * speed * Time.deltaTime;
    }

    public void GenerateTravellingBalls(Vector3 _startPoint, Vector3 _endPoint)
    {
        startPoint = _startPoint;
        endPoint = _endPoint;
        directionOfTravel = (_endPoint - _startPoint).normalized;
        Debug.Log(_startPoint + " " + _endPoint);
    }
}``` 
This is what I tried to write so far. But the Debug.Log() inside update ends up printing Null
static cedar
#

But that has to be mentioned since that's what he's asking.

teal viper
teal viper
#

In fact it's impossible for it to print null there.

sturdy lintel
#

No error. I mentioned right it prints Null. I am calling this GenerateTravellingBalls() from another script. If I do Debug.Log() inside GenerateTravellingBalls() then it prints proper value

teal viper
slender nymph
#

yeah it is 100% impossible for either of the logs in that code to print null since those Vector3s cannot be null

teal viper
#

Make sure your debug logs are informative and tell you what objects are involved. You can also look at the stack trace to see where it was printed.

sturdy lintel
#

The first Debug.Log is done from Inside the GenerateTravellingBalls() the 2nd Debug.Log is done from Update()

cosmic dagger
sturdy lintel
#

sorry 0,0,0 not null

cosmic dagger
#

You have to present your information correctly. . .

sturdy lintel
#

my bad

slender nymph
sturdy lintel
#

This is what I am doing in another script

slender nymph
#

where do you assign tBall

sturdy lintel
#

I am dragging the TravellingBallPrefab in the editor inside the tBall

slender nymph
#

well there you have it.

cosmic dagger
slender nymph
sturdy lintel
#

I'm sorry, I didn't understand 😢 I am very new, just started learning 8days back

#

Could you explain in some other way

slender nymph
#

you're calling the method on your prefab rather than on the one that you just put into the scene

#

do you know what it means when a method returns something?

slender nymph
#

great! So Instantiate returns the object that was spawned. do you know how to get that returned object?

sturdy lintel
#
GameObject TBall = Instantiate(travellingBallPrefab, 
sphere1.transform.localPosition, Quaternion.identity);```
slender nymph
#

sure. but you probably want to make your travellingBallPrefab a TravellingBalls type rather than a GameObject type and it will return a TravellingBalls object. then you won't need to call GetComponent on it

sturdy lintel
#

I feel awful to ask you again. But I don't understand how to fix this yet 😢

slender nymph
#

show what you've tried and let me know what part you are not understanding

sturdy lintel
#

I haven't made any changes to the code yet. For now the smallest thing I want to achieve is. I want to move these travellingBalls between 2 points, after small interval the balls should respawn & travel between those 2 points

slender nymph
#

focus on the issue at hand first. you need to make sure that you are calling that GenerateTravellingBalls method on the object you instantiated and not on the prefab

sturdy lintel
sturdy lintel
slender nymph
#

the type of object you put as the first parameter for Instantiate is the type of object Instantiate returns. obviously GameObject does not have a method called GenerateTravellingBalls. that is on your TravellingBalls type. if your prefab variable is a GameObject type then Instantiate will return a GameObject. and how do you get your component from a GameObject?

sturdy lintel
#

right

#

using GetComponent<>

slender nymph
#

yes. except you can completely skip the GetComponent step if you just make your prefab variable the type you want to access

#

for example, if you were to pass your tBall variable instead of travellingBallPrefab it would return a TravellingBalls type because that's what tBall is. it's also conveniently your prefab too

sturdy lintel
#
TravellingBalls TBall = Instantiate(travellingBallPrefab, sphere1.transform.localPosition, Quaternion.identity);
TBall.GenerateTravellingBalls(sphere1.transform.localPosition, sphere2.transform.localPosition);
slender nymph
#

yep, there you go

#

just make sure you've actually changed the type for your travellingBallPrefab variable and that you drag the object into the inspector again. do that even if it shows it is still assigned

sturdy lintel
#

This is throwing an error "InvalidCastException: Specified cast is not valid.
(wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at /"

slender nymph
#

yep and i just told you how to fix that

sturdy lintel
#

So this works now

#

So at first my prefab was being assigned to a GameObject type. But then what exactly was the issue with that? Why didn't the movement part of the script work exactly

#

This is the first time, I encountered this problem so trying to make a note of it. Could you point me to some resource so that I can read it as well

slender nymph
#

it had nothing to do with it being a GameObject type. as i already explained, you were calling the GenerateTravellingBalls method on the prefab not on the instance you spawned in the scene

sturdy lintel
#

So I created a prefab but then my other script was not able to understand the start,end points that I was assigning were for that created instance?

#

am I correct

slender nymph
#

not really

#

let's put it this way:
create a new txt file somewhere on your computer. add some text to it then save it. this file will represent your prefab.
if you were to copy that file to another place on your computer they would be two separate files so modifying one will not modify the other.
now open the original file again, add some text to it, but do not save. this operation represents you calling the GenerateTravellingBalls method on the prefab. since that method modified non-serialized variables they weren't changed (not that you'd want them to change in this case).
now look at the first copy you made. notice how it didn't change when you performed the previous operation (and how the prefab wouldn't have changed either)? yeah, that's what you were doing basically

#

and even if calling that method had changed the prefab, it would not have done anything to the object you had spawned on the line before, it only would have effected future objects spawned as clones of that prefab

sturdy lintel
#

Damn now I get it

#

Thanks for being so patient with me

#

I really appreciate it. From next time, I will make sure to convey my issues properly at beginning which I didn't do it right now. Sorry for the inconveniences

pastel marten
#

Can anyone give me some guidance here?

I want the player to walk in different directions based on the direction they are aiming and their movement direction. (strafe left, backward left, forward right, etc)
I tried playing with the code but I can't seem to figure it out.

Need to calculate the player rotation and movement direction difference, then activate animations based on that.
Already have the animations and animator controller set up, just not sure how to code this...

How should I code the animations to trigger based on the players rotation +/- movement direction?

Tried calculating the player.forward - movementVector, but it always returns 0f or it will return different angles based on which direction the camera is facing, which makes it impossible to trigger animations based on the angle. Is there a way to calculate the cameraForward rotation into the playerRotation and playerMovementDirection?

I made a short video clip displaying the problem. Any Help is Appreciated! blobbounce

eternal needle
candid oyster
#

how can I make a gameobject's name a string?

slender nymph
#

wdym? because it already is a string

candid oyster
#

I mean

#

uhmm

#

I have a public GameObject

#

lets say its name is A2

eternal needle
#

You wanna assign it a certain value I assume?

candid oyster
#

and then I have a string variable

#

and I want the string variable

#

to be the gameobjects name + something

#
stringvariable = GameObject + "2"
slender nymph
#

did you know that you can finish typing your full thought before pressing enter?

slender nymph
#

also GameObject has a name property that will return its name, which you would know if you had consulted the !api

candid oyster
#

Thanks

slender nymph
#

wait is that not the command. maybe !docs

eternal falconBOT
pseudo sable
#

GameObject.name will return the name of the game object as it appears in the scene

candid oyster
#

Thanks, it works

pseudo sable
#

GameObject.name also has a setter so you can change the name of the object on the fly with GameObject.name = "foo"

eternal needle
pastel marten
gaunt ice
#

!code

eternal falconBOT
pastel marten
#

I was trying to put the code in the TopDownPlayerMovement script in the MovePlayerTowardTarget(Vector3 targetVector) method when RightClickHold

eternal needle
#

use the code command above to paste it to a code site. discord trims it

pastel marten
#

Here in this block section is where I was making previous attempts:

private void MovePlayerTowardTarget(Vector3 targetVector)
    {
        var speed = MovementSpeedWhileWalking * Time.deltaTime;
        //playerSpeed = MovementSpeedWhileWalking;
        if (_input.RightMouseHold)
        {
            isAiming = true;
            speed = speed * MovementSpeedWhileAiming;
        }
        else if(_input.Shift && !isAiming)
        {
            speed = speed * MovementSpeedWhileRunning;
            playerAnimator.SetBool("isRunning", true);
        }
        else if (!_input.Shift)
        {
            playerAnimator.SetBool("isRunning", false);
        }

        targetVector = Quaternion.Euler(0, _camera.transform.rotation.eulerAngles.y, 0) * targetVector;
        var targetPosition = transform.position + targetVector * speed;
        transform.position = targetPosition;
    }
#

let me try pastebin for the full script

slender nymph
#

skipped right over that "Large Code Blocks" section, eh?

pseudo sable
#

yeah pastebin will be much easier to see

slender nymph
#

if you're going to use pastebin, make sure you select the correct language for syntax highlighting

pastel marten
pastel marten
pseudo sable
#

c# is all good!

slender nymph
#

c# is the language

pastel marten
#

I should have saved a copy of my edited script where I made an attempt to calculate the angle as a float based on playerRotation and movementDirection.

It worked... except for when I rotated the camera, then it was out of whack. It only worked for like World-Z direction

eternal needle
pastel marten
#

I had it in the MovePlayerTowardTarget() method

#

after the if (_input.RightMouseHold) statement

#

or in*

#

Unless you are asking about the camera rotation? That's handled by a different script.

eternal needle
#

it would have to be later on in the function, after the vector is rotated. from what i see, doing it at that point would mean you are just checking the players input compared to the players transform.forward

#

like the players input could be (0, 0, 1) the entire time but rotating the camera and doing Quaternion.Euler(0, _camera.transform.rotation.eulerAngles.y, 0) * targetVector is what you gives you movement in the direction you want. So thats the movement you wanna compare to the forward, not (0, 0, 1)

pastel marten
# eternal needle like the players input could be (0, 0, 1) the entire time but rotating the camer...

so what I did that somewhat worked before was

angle = Quaternion.Angle(player.transform.rotation, Quaternion.LookRotation(moveDirection));
``` but maybe I needed to use a global rotation instead of the local? or visa versa? Because the angle (float) would differ based on the camera's rotation around the player.

are you suggesting I should try 
```csharp
angle = Quaternion.Euler(0, _camera.transform.rotation.eulerAngles.y, 0) * targetVector;
```?
#

I can give that a shot, but the players rotation and aiming rotation can sometimes differ from the camera's y-angle

#

I was under the assumption I should base the animation states according to the players rotation & movement direction.

eternal needle
#

with Vector3.Angle

pastel marten
#
var Vector3 modifiedDirection = Quaternion.Euler(0, _camera.transform.rotation.eulerAngles.y, 0) * targetVector;

float angle = Vector3.Angle(playerForward, modifiedDirection);

is that essentially what you are saying?

eternal needle
#

Unless im misunderstanding something, you want to know when theres a big difference between where the player is trying to move and where they are looking, like looking one way but moving the other way, so you can play animations based on that.

pastel marten
#

Yes, I want the animations to change based on the direction the player is facing when aiming and the direction the player is moving. 🙂

eternal needle
#

you already calculate the value in line 145 of the pastebin you posted, so you can just use that. but yea get the angle then just check if the angle is greater/less than some amount. Based on that amount, play a different animation (or change some value so whatever other code can play the correct animation)

pastel marten
# eternal needle you already calculate the value in line 145 of the pastebin you posted, so you c...

Right, thanks.

So that is just returning 0f constantly.

I changed it to the following and it seems to be working, no matter what the camera's rotation is:

float angle = Quaternion.Angle(transform.rotation, Quaternion.LookRotation(targetVector));

The only issue I see is that StrafeLeft and StrafeRight are both returning 90° angles. I wonder how I would adjust it so that StrafeLeft is -90 and StrafeRight is +90? hmmm....

#

(Making progress!) I appreciate your help! Just have to figure out how to get a different value for Strafe Left/Right

eternal needle
lean basin
#

Hello, I have a prefab, and I wanted to change one of it's component to a class that inherited it. How do I do that without changing the component's current property and references in the inspector?

pastel marten
pseudo sable
#

if they have the same properties you might be able to right click old one > copy values, right click new one > paste values, maybe

lean basin
pseudo sable
#

might just have to be a manual job then unfortunately, as far as I know the editor isn't really aware of any inheritance and will treat them as basically different components

tender stag
#

how can i make each required item i dont have template name text turn red? and if i do have it to turn white```cs
if(inputItem)
{
foreach(var template in templates)
{
foreach(var requirement in inputItem.GetProcess<RepairProcess>().repairRequirements)
{
int amount = InventoryManager.Instance.inventory.GetAmount(requirement.item, InventoryManager.Instance.inventory.inventoryCells);

        if(amount >= requirement.amount)
        {
            template.transform.GetChild(1).GetComponent<TMP_Text>().color = Color.white; // Set text color to white
        }
        else
        {
            template.transform.GetChild(1).GetComponent<TMP_Text>().color = Color.red; // Set text color to white
        }
    }
}

}```

#

also i dont really want to use transform get child

#

but i dont see another way of doing it

quaint thicket
#

I'm trying to make a gameobject rotate the same direction as a camera but only using the Y rotation. For instance, even though the camera can look in all directions the gameobject would only rotate left/right and not up/down.

#

Never mind, I solved it. Talking about it really does help.

pseudo sable
# tender stag also i dont really want to use transform get child

you could add a component script onto the template gameobjects that handles it for you, so you would only have to call template.SetTextColor(color) (for example) - that way you can just change the implementation in the template code if you find a better way to do it

#

also might be worth looking into .GetComponentInChildren<T>()

#

This method checks the GameObject on which it is called first, then recurses downwards through all child GameObjects using a depth-first search, until it finds a matching Component of the type T specified.

tender stag
#

thanks

pseudo sable
#

no worries!

quaint thicket
#

I'm using a Cinemachine freelook camera and want to allow it to look upwards. For instance, when I use the mouse to rotate the camera below a gameobject it will show the camera facing upwards.

#

Solved it. The Cinemachine's FreeLook camera's Orbits > BottomRig needed to be set to a minus number like -4.5.

#

Still having a issue with the camera kind of zooming in to the middle rig while transitioning from looking upwards/downwards

eternal needle
quaint thicket
uneven swan
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InternetChecker : MonoBehaviour
{

    public static bool InternetConnection;

    void Start()
    {
        StartCoroutine(CheckInternetConnection(isConnected =>
        {
            if (isConnected)
            {
                Debug.Log("Internet Available!");
                InternetConnection = true;
            }
            else
            {
                Debug.Log("Internet Not Available");
                InternetConnection = false;
            }
        }));
    }

    IEnumerator CheckInternetConnection(Action<bool> action)
    {
        UnityWebRequest request = new UnityWebRequest("http://google.com");
        yield return request.SendWebRequest();
        if (request.error != null) {
            Debug.Log ("Error");
            action (false);
        } else{
            Debug.Log ("Success");
            action (true);
        }
    }
}

it says Assets\Scripts\InternetChecker.cs(27,41): error CS0246: The type or namespace name 'Action<>' could not be found (are you missing a using directive or an assembly reference?)

normal shell
uneven swan
#

i have it i miss copied it it seems

#

oh actually you were right I don't have just the using System never used it almost

normal shell
#

😁

uneven swan
#

thx

lean basin
#

I have this script:

public enum State {None, Idle, Walk, Rotate, Check, Chase,ChaseDynamic, Peek,InitialPooled, Pooled, Despawning, DebugFreeze, Examine, Pounce, Laugh}
public void ChangeState(State newState)
{
    nextState = newState;
}

But why doesn't it appear as an option in UnityEvent trigger dropdown?

pseudo sable
#

for a button event or?

lean basin
#

this event

#

custom UnityEvent. Im guessing it would be the same for button's OnClick event, but haven't tried,

slender cargo
#

So I am working on a silly game of mine, How would I get a line renderer with physics between 2 objects?

#

Line renderers have no physics, so does anyone have any suggestions?

#

Rope physics?

pseudo sable
#

(or even just as the only parameter, just to test)

slender cargo
lean basin
pseudo sable
#

quick check, looks like enums are indeed not supported!

#

you could cast back and forth from a string or int that represents the enum though

pseudo sable
pseudo sable
# lean basin BaseEventData don't appear when I used it as the only parameter. However `string...

another solution would be having a different handler for each enum type, which may or may not be appropriate based on your project, like this:

public void FuncWithEnum(EnumType enumType) {
    switch (enumType) {
        case EnumType.Value1:
            //Do something
            break;
        case EnumType.Value2:
            //Do something
            break;
    }
}

public void FuncWithEnumValue1() => FuncWithEnum(EnumType.Value1);
public void FuncWithEnumValue2() => FuncWithEnum(EnumType.Value2);
#

then your event can just point to FuncWithEnumValue1(), etc. might get a bit wild if you're doing anything a bit more complex though

lean basin
lean basin
pseudo sable
slender cargo
pseudo sable
# lean basin Where did you obtain this information?

https://discussions.unity.com/t/enum-as-a-function-param-in-a-button-onclick/214010/7
it's talking about the OnClick delegate but i'm sure it'll all come from the same base

#

(thread is quite old so maybe it's supported now but i suspect since it isn't working for you, it's still not supported - unless there's a new fangled approach)

azure zenith
#

I am supposed to make a throwable item explode if it touches the ground in an OnDestroy() method, how would I do this?

pseudo sable
#

OnDestroy() gets called on a gameobject just before it is removed

azure zenith
#

Oh

#

That makes more sense

#

Thank you 🙂

pseudo sable
#

no worries!

azure zenith
#

If you are still here, I tried it and it worked. However, if I press restart the game, every single throwable explodes

#

I guess that is normal...?

cosmic dagger
azure zenith
#

I only want it called on the throwable that the player throws

#

Or maybe that is not possible

cosmic dagger
#

OnDestroy is a unity event function that is automatically called when a GameObject is destroyed . . .

teal viper
#

You can't control the OnDestroy function being called, but you can control what happens inside of it.

cosmic dagger
#

you don't even need to use it. just destroy the GameObject when it collides with an object (or only the ground) . . .

azure zenith
#

From the Unity's website: Note: OnDestroy will only be called on game objects that have previously been active.

pastel marten
#

Would anyone be able to help me figure this out?

I am trying to set the Movement Angles X & Y for a Blend Tree and can't quite figure out the proper method of doing so.

Here is the method I am attempting:

private void ApplyAnimation()
    {
        // Calculate normalized movementAngleX and movementAngleY.
        movementAngleX = Vector3.SignedAngle(transform.right, targetVectorA, Vector3.up);
        movementAngleY = Vector3.SignedAngle(transform.forward, targetVectorA, Vector3.up);

        // Ensure that the resulting values are clamped to the range [-1, 1].
        movementAngleX = Mathf.Clamp(movementAngleX, -1f, 1f);
        movementAngleY = Mathf.Clamp(movementAngleY, -1f, 1f);

        // Set the Blend Tree parameters in the Animator
        playerAnimator.SetFloat("MovementAngleX", movementAngleX);
        playerAnimator.SetFloat("MovementAngleY", movementAngleY);

        print("X = " + movementAngleX);
        print("Y = " + movementAngleY);
    }
``` it gets the targetVectorA from here:
```csharp
        targetVector = Quaternion.Euler(0, _camera.transform.rotation.eulerAngles.y, 0) * targetVector;
        var targetPosition = transform.position + targetVector * speed;
        transform.position = targetPosition;

        targetVectorA = targetVector;

The -1,1 values seem correct in the debug console ~ the problem is I want it to use all the in between values and also set back to 0,0 when there's no input or movement.
Also, if I walk straight forward movementAngleY = 1 and movementAngleX does not go back to 0. Seems like a constant 1,1 or -1,1 and never a 1,0 or 0,-1

Should I be using Mathf.Lerp for this? Or is there another math function I should be using?

Here is the full script: https://pastebin.com/SHqHF6xD
And here is an image of my Blend Tree below:

swift crag
#

It's going to tell you the angle between two vectors

#

But that's not what you want. You want to compute X and Y values telling you how much you're moving in those directions

pastel marten
swift crag
#

You should use Vector3.Dot. If you do this:

Vector3.Dot(transform.right, movementVector);
#

you'll get a value between -x and x, where x is the length of movementVector

#

If the two vectors are aligned, you'll get x

#

if they're pointing in opposite directions, you'll get -x

#

Alternatively, convert the movement vector into local space and then just use its X and Z components

#
var local = transform.InverseTransformVector(movementVector);
#

local.x will be the left-right component and local.z will be the forward-backward component

#

the Inverse methods take a world-space vector and convert it to local-space

pastel marten
dusk dust
#

I searched about the Resource folder, and they said it's not recommended in production, why is that and what is the alternative?

swift crag
#

I would not say it's "not recommended in production"

heady nimbus
#

Did debugging in vscode get fixed with the new c# dev kit stuff?

swift crag
swift crag
#

but sometimes you just need to load an object by a name with no other references

#

for example, I recently added a "singleton scriptable object" type to my project

#

it's a singleton that initializes itself like this

heady nimbus
swift crag
#

_instance = Resources.Load<T>(typeof(T).Name);

#

i should really make a subdirectory to put these singleton assets in

azure zenith
#

From the Unity's website: Note: OnDestroy will only be called on game objects that have previously been active.
Is it possible to disable it on objects that have been active?

dusk dust
queen adder
#

Hi i need help on adding admob banner to my game

swift crag
#

I would make it explode when it detects that it has hit the ground

stable jackal
#

helo im pretty new and im following a guide for a game, im using Unity 2018.3.7f1 and i need to import Navmesh components, im on the github link right now but i dont know how to "import" this navmesh into my game/unity project

stable jackal
#

sure do i send it here or to your dms

swift crag
#

here.

stable jackal
#

dude just said go to this github link and import navmesh components, and idk how to do that

swift crag
#

see the readme on the github page

#

Clone or download this repository and open the project in Unity. Alternatively, you can copy the contents of Assets/NavMeshComponents to an existing project.

#

So, you can just copy that entire NavMeshComponents folder into your project

stable jackal
#

ohh

swift crag
#

Make sure to click the correct link here first

#

master for 2020.3-LTS, 2019.3 for up to 2019.4-LTS, 2018.3 for up to 2018.4-LTS and 2019.2, 2018.2, 2018.1, 2017.2 for up to 2017.4-LTS, 2017.1, 5.6.

#

(these are hyperlinks on the readme)

stable jackal
#

thank you

swift crag
#

oh, that link is busted

#

it's not set up correctly

#

You can switch branches in this dropdown menu

#

You will want to pick 2018.3

#

then download the zip, unpack it, and copy NavMeshComponents into your assets folder

stable jackal
#

so im just gonna download the assets folder then shove it into my project?

swift crag
#

pretty much

stable jackal
#

alr thanks thanks

swift crag
#

the important folder in there is NavMeshComponents. The others are samples and stuff

stable jackal
#

im at the 2018.3 branch i dont see a green download button how do i download this (sorry i am very new to all this)

#

nevermind, found it

subtle veldt
#

Hello !
This is the code I use to make my player move :

    void Update()
    {
        playerRigidbody.velocity = new Vector2(inputX * walkingSpeed, playerRigidbody.velocity.y);
    }

    public void Move(InputAction.CallbackContext context)
    {
        inputX = context.ReadValue<Vector2>().x;
    }

But I need to change it because it causes weird things to happen when I link my player to another object with a SpringJoint2D. How would you make your player move in a 2D game which uses Physics ? (i'm using grappling hooks for example)

stable jackal
#

question how do i add like my gameobject ground/player into a layermask

pastel marten
#

@swift crag

It's working as intended! Thank you!

        movementAngleX = Vector3.Dot(transform.right, targetVectorA);
        movementAngleY = Vector3.Dot(transform.forward, targetVectorA);
        float length = targetVectorA.magnitude;
        movementAngleX /= length;
        movementAngleY /= length;
        movementAngleX = Mathf.Clamp(movementAngleX, -1f, 1f);
        movementAngleY = Mathf.Clamp(movementAngleY, -1f, 1f);

        playerAnimator.SetFloat("MovementAngleX", movementAngleX);
        playerAnimator.SetFloat("MovementAngleY", movementAngleY);
stable jackal
#

thankss

spice smelt
#

well i have made guns and i want to do some particles and shooting animation shake screen or something

  • my model broke
swift crag
#

Normals are flipped

#

Fix them in blender

spice smelt
#

tutorial

north kiln
wintry quarry
stable jackal
#

yup thank you, running into another problem rn where if i click play my enemy ai just vanishes into thin air

cosmic dagger
#

stealth mode activate . . .

spice smelt
#

fixed

#

so how do i do the Unity particle siumulator

azure zenith
#

Can I have two OnCollisionEnter in my script?

cosmic dagger
#

you only need the one . . .

polar acorn
gray python
#

Hello, i'm wondering if anyone could help me understand the built in physics engine a lil bit, right now this dash function is working fine while on the ground and while moving, however it's not applying the force correctly/at all while in the air during a jump. Could anyone tell me why, or maybe what to watch out for?

void Dashing() {
    float dashForce = 30f;
    if (Input.GetButton("Dash")) {
        if (IsFacingRight() == true && !hasDashed) {
            Debug.Log("Dash Right");
            rb.AddForce(Vector2.right * dashForce, ForceMode2D.Impulse);
        } else if (IsFacingRight() == false && !hasDashed) {
            Debug.Log("Dash Left");
            rb.AddForce(Vector2.left * dashForce, ForceMode2D.Impulse);
        }
        hasDashed = true;
    }
}
silk night
polar acorn
gray python
gray python
subtle veldt
azure zenith
#

If I add a tag to an empty object, will it also apply to all its children?

azure zenith
#

I did and I do not think it does

heady nimbus
swift crag
#

Tags and layers both apply just to the object you set them on

#

but Unity does offer to apply a layer to all children if you want

azure zenith
#

Basically, I made an empty object to store all my cubes

#

Does that mean the empty object is a parent and all its cubes are child objects?

swift crag
#

That sounds reasonable.

#

The Hierarchy shows you all of the objects in the scene. In this example, "Camera Controls" is the parent of "Main Camera", and "Main Camera" is the child of "Camera Controls"

#

Every item in the Hierarchy is a GameObject. Every GameObject has a Transform.

#

and the Transform is what has a parent / has many children

#

that's why you do transform.SetParent(otherObject.transform), not SetParent(otherObject)

azure zenith
#

So if I add a tag to the parent object, it will apply the same tag to all its children objects?

swift crag
#

No.

azure zenith
#

Yes

#

Oh

swift crag
#

Each game object can have a tag

azure zenith
#

I see

swift crag
#

Tags aren't propagated to children or anything like that

azure zenith
#

What if I added a script?

swift crag
#

Sure, you could set the tags of all of the children if you wanted to

somber wren
#

someone has any idea of it is not hitting ?

#

also my ray are clearly hitting ? the layer is all on default

polar acorn
#

The fact that it's curved leads me to believe this is not the ray you've drawn

#

It's just another red gizmo

somber wren
#

its a serie of rays

#

its a coded Arc RayCast fonction, its just a serie of rays that end up doing an ArcRay

#

kind of like that

shell sorrel
#

does the raycast originate from inside the wall

#

if so it would not hit the collider

polar acorn
#

And is it always supposed to be a 180 degree arc? If so, it seems like it's working just fine

somber wren
#

not it orginates from above the spider, i mean the first ray

polar acorn
#

Pictured is only about a 90 degree arc, and the last segment is the one that hits the wall

somber wren
#

yes, but its not returning that it hits as it should

#

no, its supposed to stop when it hit something

shell sorrel
#

test assumptions

#

do 1 raycast with the same settings you know will hit and see what happens

polar acorn
#

Make sure the thing you're expecting to hit is in the layer mask

#

Use that same mask with something easy like an infinite forward ray

somber wren
#

ill see

shell sorrel
#

if something does not work, i tend to just strip it back to the most simple test case that uses the same parameters

somber wren
#

a simple infinite ray doesnt work too :(

azure zenith
shell sorrel
#

why would you need to do it manually to all of them though

pseudo sable
#

few solutions depending on how you want it to work

swift crag
#

not "setting tags on objects"

#

what are you trying to make your game do?

heady nimbus
#

Dumb question, if I want an enemy to be able to pass through the player, but still collide with ground and walls and use physics, what options do I have to handle this

shell sorrel
#

@heady nimbus physics layers

heady nimbus
#

Awesome, thank you, I'/ll look into it

polar acorn
heady nimbus
shell sorrel
#

would need mulitple colliders then

#

1 that does the real collisions but ignores the player

#

then a other that is just a trigger collider on a layer that colliders with player

heady nimbus
#

Ok, so I could one that uses the Layer Overrides -> Exclude Layers -> Player

#

Cool, I think it's working, thanks

vagrant lynx
#

Hello

#

Can I use vs code instead of visual studio ?

silk night
#

Yes

heady nimbus
#

!ide

eternal falconBOT
vagrant lynx
#

I want to delete the visual studio

silk night
#

You cant really delete it because you need dependencies of it

vagrant lynx
#

Should I have to keep it

silk night
#

but you can just not open it and use vs code instead

vagrant lynx
#

Okay

heady nimbus
#

? What dependencies do you need? I removed it in favor of VSCode...

silk night
#

Oh my bad, that was UE5 that needed vs installed

heady nimbus
#

Lol I was going to say, I always remove studio

vagrant lynx
#

So, is that okay to uninstall it ??

heady nimbus
#

Lmao, so I got my knock back "working" but it has some amusing side effects going on. If I hit player input in the direction of the knock back at the exact right moment I get a bit of a velocity "boost". Hahaha

silk night
spice smelt
#

lets say i have a script that changes weapon

vagrant lynx
#

Alright

spice smelt
#

what do i need to add to in to make them animated

silk night
polar acorn
heady nimbus
#

I lock movement

polar acorn
#
Unity Learn

An Animator Controller is a Unity asset that controls the logic of an animated GameObject. Within the Animator Controller there are States and Sub-State Machines that are linked together via Transitions. States are the representation of animation clips in the Animator. Transitions direct the flow of an animation from one State to another. In thi...

heady nimbus
#

But I probably need to set velocity to 0, THEN handle the knock back

vagrant lynx
#

I opened a script rn, and it's showing
Do you trust the authors of the file or folder ?

heady nimbus
#

But for now it's funny

polar acorn
#

Do you trust yourself?

vagrant lynx
heady nimbus
#

I wouldn't. Tired me and drunk me write some pretty suspect scripts

vagrant lynx
#

Lol

polar acorn
swift crag
#

you don't need Visual Studio installed to use Unity or another core editor..

#

oops, was scrolled back

swift crag
heady nimbus
#

Kind of sad to see it go, but yes, setting velocity to 0 before locking movement and processing knock back DOES prevent the rocket launch effect I was getting. Lol

swift crag
#

so the default is to run in an "untrusted mode" that disables that stuff

azure zenith
#

I believe OnCollisionEnter checks all objects colliding with an object?

#

Unless you tell it not to?

heady nimbus
#

If the objects have a collider, yes

azure zenith
#

Then a specific object will collide with the object?

swift crag
#

what are you trying to do?

#

don't ask about your attempted solution. ask about your original problem.

queen adder
#

!code

eternal falconBOT
copper perch
# rich adder what is nor working exactly

hello, the ammo number does not update to 20 when I pick up the ammo clip, and the sound plays when I eneter the 3rd level right away, and play on awake is off on the audio source

polar acorn
mellow jacinth
#

Someone teach me

#

Programming

copper perch
polar acorn
eternal falconBOT
#

:teacher: Unity Learn

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

azure zenith
heady nimbus
#

if (col.gameObject.GetComponent<Grenade>())

#

Or something along those lines

azure zenith
#

Cheers

#

So yeah, basically I do not want the cube to explode and destroy when a player goes through it

mellow jacinth
polar acorn
swift crag
#

I prefer using TryGetComponent. It can be very handy for doing an early-return

heady nimbus
#

Yea, try is probably better, but I suck as this and always forget it. Haha

swift crag
#
void OnCollisionEnter(Collision collision) {
  if (!collision.gameObject.TryGetComponent(out Grenade grenade))
    return;

  // do stuff with the grenade variable
}
#

TryGetComponent returns false if it fails

#

if it succeeds, then you'll have a variable named grenade holding the Grenade

silk night
#

What the hell is going on with my nav-agents here?

https://img.sidia.net/ZEyI5/BOmAJuDe53.mp4/raw

I basically tell them to follow my player:

public void OnPosition(GameEntity entity, Vector3 value)
{
    Agent.SetDestination(value);
}

The onposition is called whenever my player moves to a new position

unique hull
silk night
# unique hull I am not an expert at the navmeshes , but i am using destination on all my units...
    /// <summary>
    ///   <para>Sets or updates the destination thus triggering the calculation for a new path.</para>
    /// </summary>
    /// <param name="target">The target point to navigate to.</param>
    /// <returns>
    ///   <para>True if the destination was requested successfully, otherwise false.</para>
    /// </returns>
    public bool SetDestination(Vector3 target) => this.SetDestination_Injected(ref target);

    /// <summary>
    ///   <para>Gets or attempts to set the destination of the agent in world-space units.</para>
    /// </summary>
    public Vector3 destination
    {
      get
      {
        Vector3 ret;
        this.get_destination_Injected(out ret);
        return ret;
      }
      set => this.set_destination_Injected(ref value);
    }

They are doing the same thing

timber tide
#

lol at the spinning cube

#

do you get the same results without rigidbody

#

ideally you don't want to use rigidbody anyway

silk night
#

OHHH that might be it xD

timber tide
#

Rather, rigidbody is fine, but using it for collision detection like this does cause complications.

#

ideally, you'd make your own character controller and handle how things should be pushed back instead of relying on the physics system.

silk night
#

removing / setting the rigidbody to kinematic fixes the issue

#

I dont want player/monster collision anyways

#

Aslong as the monsters dont clump up while following me its fine, and navagents seem to prevent that by default

timber tide
#

if you do want to use kinematic, you can potentially try just adding *your own displacement methods around your character passively to push stuff back

silk night
#

Nah basically I just need an ontriggerenter to damage my player when its touched

buoyant knot
#

is there any overhead for using tuples?

swift crag
#

tuples are reference types, so they're different from a struct

#

i guess this could result in more garbage being produced than if you were passing structs around

buoyant knot
#

I’m making a system where I need to store pairs of colliders (where col 1 ignores force from col2), and I’m contemplating Dictionary<Collider2D, HashSet<Collider2D>> vs HashSet<Tuple<Collider2D, Collider2D>>

short hazel
#

First one if you need to access the second element of the pair using the first, and fast

buoyant knot
#

also wtf tuples are reference types?

short hazel
#

Else second one

buoyant knot
#

I just need to check the pair really fast

brave compass
#

The old System.Tuple is a class. But the language feature (x, y) has been replaced with System.ValueTuple, which is a struct.

short hazel
#

In recent enough versions of C#, there's ValueTuple, a struct

buoyant knot
#

ie if I have colliders 1 and 2, do we ignore

elfin eagle
#

im new to scriptable objects, so like can you not assign gameobjects or anything else?

buoyant knot
#

hmmm, maybe ValueTuple will do this faster?

short hazel
#

Second one then, tuples will correctly produce hash codes for the pair

#

It defaults to ValueTuple now

buoyant knot
elfin eagle
#

ohh ok is it like in project files only?

buoyant knot
#

SOs are usually used as immutable data that you store separately that can be used to populate/query other things

cosmic dagger
brave compass
buoyant knot
#

so if I am making a Goomba SO, I could add in: Goomba Prefab (to make it), string for enemy name, bool for if I can stomp it…

#

but 1) you really do NOT want to write to SOs during runtime. You can, but I always pay the price

#

like, you do NOT want enemy boss current HP in an SO

#

you DO want enemy boss Max HP in an SO. That does make sense

#

understand?

buoyant knot
elfin eagle
#

alright okay i see

buoyant knot
#

So I define EnemySO with: GameObject prefab for enemy, string for name, bool for stompable…
Then [CreateAssetMenu()], and you can make a new EnemySO file

#

then you fill that new EnemySO file in inspector with goomba data, and call it GoombaEnemyData

#

then again right click on asset menu to make another EnemySO, and we fill it out again, but this time for Koopas

#

right click asset menu => new EnemySO file => make Piranha plant file

timber tide
#

yes

buoyant knot
#

then in game, I would make an EnemyDataHolder Monobehaviour, for example. This is a component that goes in the prefab, and I have a Serialized Field for EnemySO, and connect it.

elfin eagle
#

I have this main problem so I have a game object in scene one, and in scene two there is a prefab of that game object. My character has a script attached to it that the game object in scene 2 needs to access but it cant since it is from originally from scene 1 (Im using do not destroy on load). I need help to find a way that the gameobject in scene 2 can access it when the player enters the scene

so how could I use the scriptible object to fix this? or is there a different way

buoyant knot
#

So every goomba, koopa, and piranha plant has its own EnemyDataHolder component for every new one, and that component has a reference to the data for that specific enemy

timber tide
#

ye

buoyant knot
#

yeah

timber tide
#

I like to add constructors on my SOs too so I can just call them to construct them right from it. Assuming it will only ever be inserted by one type of monobehaviour.

buoyant knot
#

scriptable objects do not exist in any scene

#

I try not to ever construct SOs outside asset menu. GC doesn’t automatically clean up / destroy them when done

#

which is obnoxious

timber tide
#

Oh, no I mean I construct the enemy by calling the SO, instead of the enemy prefab script

buoyant knot
#

scenes are basically giant prefabs. The scene has a bunch if gameobjects, and each gameobject has components. Those components can reference SOs or prefabs. And prefabs can have gameobjects with components that reference SOs

timber tide
#

just a different way to implement it

buoyant knot
#

I always instantiate prefabs by looking into an SO

#

example: GetTile from tilemap => tilebase for a given tile => big dictionary gives me the SO associated with that tilebase => that SO has a field for a prefab

#

this way the tile on the tilemap is tied to a prefab

#

does all of this make sense?

swift crag
#

otherwise two tuples with the same elements will still have different hash codes

buoyant knot
#

and ty guys.

brave compass
#

Does the order not matter for the hashcode ValueTuple generates?

#

Pretty sure it does. (colliderA, colliderB) != (colliderB, colliderA)

sage mirage
#

Hey, guys! I have a question. Can I use a lot of Audio Sources on a specific game object? If yes how to manage on this object the sounds?

swift crag
#

You can have multiple audio sources. You'll just need to put in a little more effort to pick the right one

cosmic dagger
swift crag
#

Dragging a game object into a field will pick the first matching component on it

#

But you can drag a specific component into a field instead.

sage mirage
#

For example, I want to add for the player game over sound when he collides with an object and also hit sound when the collision occurs

buoyant knot
swift crag
#

Multiple audio sources are only needed if you want to have several simultaneous non-one-shot sounds, or want to have different audio settings for different sounds

brave compass
buoyant knot
#

that is probably cleaner tbh

sage mirage
swift crag
#

audioSource.PlayOneShot(someClip);

#

This does not use the audio clip field on the audio source

buoyant knot
#

so let’s say you are looking at a gameobject with like 20 different audio sources, but it also has all the colliders etc. That will be a mess

swift crag
#

I prefer to put different audio sources on different game objects

#

I can add audio filters to each one independently, and it's just easier to wrangle them

sage mirage
#

Yes but if i have the clip inside of my audio clip on audio source then I can play only this sound if I am not wrong?

swift crag
#

That audio clip field is only used when you Play() the audio source.

buoyant knot
#

you probably want to make an SO with separate fields for: death SFX, dmg SFX, running SFX, idle SFX etc. if it gets complicated

swift crag
#

PlayOneShot does not set the field and doesn't care about the field. You can have many one-shot sounds going simultaneously

buoyant knot
#

if you don’t need to make multiple gameobjects with similar SFX needs, you can use field: SerializeField to specify specific audio clips

sage mirage
swift crag
#

It's used when you Play()/Pause()/Stop() the audio source

#

Which you usually do for things like music

buoyant knot
#

which you don’t usually want two of at the same time

sage mirage
#

@swift crag To tell you the truth, I didn't know that with a single Audio Source you can handle with PlayOneShot() every sound you want. Thanks! I will see what I can do with all your suggestions.

spice smelt
#

i need help

buoyant knot
#

PlayOneShot is a method for an AudioSource that takes an AudioClip as an argument

short hazel
buoyant knot
#

myAudioSource.PlayOneShot(myAudioClip)

#

myAudioSource can come from GetComponent. myAudioClip comes from SerializeField OR from a scriptable object

buoyant knot
#

I’m going to take the plunge btw, fen. I’m going to refactor all my physics to manually do the simulation with kinematic RBs. It’s going to take a while, but I think will be worth it.

spice smelt
#

what if i want all of my weapons to react when jumping for examle little move

#

and also how do i add a soudeffects

buoyant knot
golden ermine
#

Can someone help me do this? I have an script that is attached to player canvas and it counts have many wood logs is collected and it shows in in the textUI. I have prefab that is Campfire with sprite set to not on fire and when player collects 3 wood and enters campfire trigger it will change sprite to campfire that works with animations and it will heal player when its inside of its trigger. I have trouble with this cause Campfire is prefab and im counting the wood in player canvas so i cannot assign it from script inside campfire prefab. Can someone help with that

spice smelt
#

when I jump i dont want them to be steady in one place i just want them to follow my camera with little delay

wintry quarry
spice smelt
#

how do I make them follow my camera with a little delay

wintry quarry
#

follow the camera?

#

is this an FPS game?

spice smelt
#

YE

wintry quarry
#

Google "unity fps weapon sway" and find a tutorial

short hazel
#

Weapon sway is the term

golden ermine
buoyant knot
#

prefab campfire script needs to be able to get a reference to the count

golden ermine
sage mirage
#

@swift crag Hey! Something else about before. Do I have to add my Sound Effect from Project windows right to my Hierarchy in order to use PlayOneShot from the single Audio Source that I have?

golden ermine
#

and also i want multiple campfires

swift crag
buoyant knot
#

you might want a singleton that gives access to the total game inventory/score

swift crag
#

You should add fields to your player component to hold the audio clips

#

like [SerializeField] AudioClip hurtSound;

violet topaz
#

does anyone know how to assign the player to the camera follow script when changing scene ```cs
public class CameraFollow : MonoBehaviour
{
[SerializeField] private Vector3 offset;
[SerializeField] private float damping;

public Transform target;

private Vector3 vel = Vector3.zero;


private void FixedUpdate()
{
    Vector3 targetPosition = target.position + offset;
    targetPosition.z = transform.position.z;

    transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref vel, damping);
}

}```

buoyant knot
#

CampfireScript can use Inventory inventory = Inventory.GetInstance();
then read inventory.logCount in Start

golden ermine
buoyant knot
#

yes, but it’s harder because you need to manage references to things to avoid FindComponentInScene or something

#

singleton is the easiest way. You sure don’t want to keep two sets of counts of logs, right? And you definitely don’t want that in a static class

swift crag
#

rather than having the campfire look at the player inventory

buoyant knot
golden ermine
#

i dont get it how do u mean

#

like i have 2 prefabs of campfire

swift crag
sage mirage
# swift crag `AudioClip` is not a component. It is an asset.

Yes! I mean how can I use AudioSource.PlayOneShot() if there is a string name required as a parameter inside the method? Do I have to add those Sound Effects assets on my Hierarchy as objects and make tags for each one of them in order to get reference with the method above?

swift crag
#

you'd find the campfire when you mouse over it

#

or whatever you do to decide you're going to interact with the campfire

buoyant knot
#

campfire needs to access that data from somewhere

swift crag
#

i'm suggesting to invert this

#

Campfires should have no idea about my inventory

#

what are they doing in my backpack?

golden ermine
#

and when i have 3 wood collected and approach any of them it should take away 3 woods and change sprites and start animation as well as heal the player when isnide of trigger. While the other one can do the same only if i have 3 more wood

buoyant knot
#

either way, you need the link between the thing with the logs and the campfire

swift crag
#

The player should look for a campfire nearby and tell the campfire to light up

#

The player can then deduct 3 logs from their inventory

buoyant knot
#

and I would rather my inventory not know about the campfire, than the campfire not know about inventory

swift crag
#

Campfires that steal your wood sound a lot weirder than players that put wood in campfires

#

The inventory wouldn't know either. The inventory is an inventory.

#

The player notices the campfire and has an inventory.

#
void OnTriggerEnter(Collider other) {
  if (other.TryGetComponent(out Campfire campfire) {
    if (inventory.logs >= 3) {
       campfire.Ignite():
       inventory.logs -= 3;
    }
  }
}
#

Problem solved.

buoyant knot
#

there are a lot of ways to do this. not difficult

swift crag
#

I think this is the most natural way to do it, and also, conveniently, the easiest to implement

#

the campfire doesn't need to be made aware of your inventory

golden ermine
#

uh also i have this script that is attached to player, also when entered ontrigger it will make campfire https://hastebin.com/share/zolepomowa.csharp

swift crag
#

Instead of finding a campfire in the scene, just see if the thing you bumped into in OnTriggerEnter2D is a campfire

golden ermine
#

can i do that with if(collision.gameObject.tag == "Campfire")

buoyant knot
#

i don’t understand the difficulty here

swift crag
#

actually, looking at your code, you've already solved the problem more-or-less how I described

buoyant knot
#

when you collide/trigger, both things get references to each other

swift crag
#

the player notices a campfire, ignites it, and deducts 3 logs

#

maybe there is a miscommunication here

buoyant knot
#

player should have a reference to an inventory, and UI display should also have a reference to inventory

swift crag
#

yep yep

golden ermine
buoyant knot
#

this is why I thought it would make sense for inventory to be a singleton, unless it is a multiplayer game

swift crag
# golden ermine

you're still using CampfireSpriteRenderer, which may not be from the campfire you just collided with

golden ermine
swift crag
#

That looks more reasonable. I'd go a step further and create a Campfire component that does everything for you

#

instead of doing a bunch of GetComponent calls

floral wren
buoyant knot
#

player should not have any knowledge of the campfire’s structure.

swift crag
buoyant knot
#

player has no business setting animator flags

swift crag
#

the player knows how to tell campfires to ignite. the player doesn't care how the campfire works

#

encapsulation will prevent so many errors

buoyant knot
swift crag
#

of course, you can always split the difference

#

inventories as non-static objects, but with a static reference to the player's inventory

buoyant knot
#

which would probably mean inventory would be a serializable POCO

golden ermine
#

Okay but how can I now make gameobject that is inside that campfire that i collided with set to true with in that if statemnet

swift crag
floral wren
swift crag
#

It should have a reference to the animator and to the sprite renderer.

golden ermine
swift crag
#

It should have a method that, when you call it, does all of the work needed to make the campfire light up

#

Then you can just get that single Campfire component and tell it to turn on

buoyant knot
swift crag
#

Imagine you have lots of things that can ignite a campfire. If you decided to change how the visual works, you will have to change every single place that lights campfires

golden ermine
swift crag
#

replacing GetComponent<SpriteRenderer>() with GetComponent<CoolNewThing>()

#

That's a hassle, and you'll probably miss something.

#

So, instead, just hide all of that logic inside the Campfire component

#

Change it once and you're golden.

obsidian fern
#

Does anyone have an idea how I could go about making an inventory system like the one in dredge? With puzzle pieces that can be rotated around to fit into each other

buoyant knot
#

Campfire needs its own Monobhevaiour, my man

buoyant knot
golden ermine
rich adder
obsidian fern
golden ermine
swift crag
#

I have lots of really small components I only use in one or two places. They make my life simpler.

rich adder
#

many diff ways to do it

#

tilemap is interesting usecase too, never tried it though

buoyant knot
#

tilemap will work well. but you need math

rich adder
#

like everything else 😛

swift crag
#

I'm pretty sure this was a homework problem at my university

obsidian fern
#

I don't know how I'm going to learn how to do this

buoyant knot
#

you need an SO that has information about the position of each tile.

timber tide
#

Easy way is to just check neighbors of the 2D array

rich adder
#

seem codemonkey has one, just be careful with codemonkey code xD

buoyant knot
#

you need a function to rotate the coordinates of each tile, and output a shape.
and you need a function that can look into the tilemap and retrieve the SO

rich adder
#

eh why would u use invoke repeating?

solar heron
#

Can someone help me, im trying to update the InvokeRepeating method because im trying to make my mobile clicker game clicks counter go up

rich adder
#

jesus..

#

use a coroutine

buoyant knot
#

yeah

obsidian fern
#

Seems way over my head. But this is unfortunately my goal

timber tide
#

it's basic array navigation

solar heron
buoyant knot
#

I would not store all that info into playerprefs

golden ermine
rich adder
golden ermine
#

is this okay

buoyant knot
#

you would want to store the counts of everything into a JSON/BSON

rich adder
#

I love bson

#

i use mongo and bson is fun to work with

solar heron
buoyant knot
#

if someone is determined enough to look up the save file and edit it, they are determined enough to figure out how to read it

rich adder
buoyant knot
solar heron
buoyant knot
#

I would make an SO with details about a specific type of thing: name, click frequency, reference to sprites etc.

golden ermine
#

is now everything fine?

buoyant knot
#

then make a single component that takes in info from that one coroutine to start running it. I expect you only need to define one IEnumerator to make your code work

rich adder
golden ermine
#

lmao

#

i made that script before but didnt used it so i just used it now, i didnt bother to change a name lol

rich adder
#

its a good name

#

tells you what it does

buoyant knot
#

i would just call it campfirep

#

and then give it responsibility over anything a campfire needs to do

rich adder
#

CampfireController

golden ermine
#

also can i move that if statement from playermovement script inside campfire script so that when player is inside campfire trigger it will lit not when campfire is inside of player trigger

buoyant knot
#

because changing the animator to IsLit has nothing to do with healing

buoyant knot
#

player has no business knowing anout the inner workings of campfire

golden ermine
#

also can i add to if statement (Input.GetKeyDown(KeyCode.E) && everything else) will that work so when im in trigger and then press e it will lit

buoyant knot
#

player knows about player

golden ermine
#

or maybe put first if statement inside that input.getkeydown(keycode.e)

uncut veldt
#

Hi quick question im having a problem with rotation as i have a motorbike in a project and i want to aplly lean to counteract the wheel collider lean as that leans in the wrong dirrenction i am currently using this to do that ow wver it doesnt work as intended at all cs transform.rotation = Quaternion.Euler(new Vector3(transform.rotation.x, transform.rotation.y, -Mathf.Clamp(leanCoeffitient * frWheel.steerAngle, -maxLeanValue, maxLeanValue))); any help is apreciated

buoyant knot
#

you also do not want to write the number 3

#

you want to use private const int, and define 3 at the top

solar heron
#
    private void Update()
    {
        StartCoroutine(GiveMoneyPerSecond());
    }

    IEnumerator GiveMoneyPerSecond()
    {
        yield return new WaitForSeconds(time / MPS);
        money += 1;
        PlayerPrefs.SetFloat("money", money);
    }
``` uh is this good XD
buoyant knot
#

especially for school, I would dock you for putting that magic number 3 randomly in your code

solar heron
#

nope i guess not its wayyy to fast

buoyant knot
#

that starts a coroutine every frame

golden ermine
solar heron
#

I want it to be once every time / MPS

buoyant knot
#

also stop using playerprefs like that

rich adder
wintry quarry
uncut veldt
rich adder
buoyant knot
#

getkeydown is true for one frame when you press a button

golden ermine
buoyant knot
#

nope

rich adder
#

yes also dont put 1 framebuttons

#

in trigger enter

buoyant knot
#

those trigger callbacks happen once every physics frame

timber tide
# obsidian fern Seems way over my head. But this is unfortunately my goal

Basically, designate a pivot for your items and inventory. Preferably the most top left index would be [0][0] of each of them. In your item's data, make an array of vector2Int. Now, say a dagger takes up 3 spaces vertical, then your array of vector2Ints would be [0, 0], [0, 1], [0, 2]. Now, when you pick up the dagger, first scan from the top left to the bottom right of your inventory. When you find an open space, take that index and try finding open indices for all of your dagger. If the open inventory index is [2, 0] then you now make this the pivot and add/check if your dagger fits at this space so add your Vector2Ints with this value each -> [2, 0], [2, 1], [2, 2]. If each slot is empty, add the dagger, otherwise search for the next open slot and redo the vector3Int addition and check operation.

golden ermine
rich adder
#

only use bool in Trigger

buoyant knot
#

i use input system, but that’s beyond him rn I think

rich adder
#

yes

buoyant knot
#

i think GetKey tells you if the key is currently pressed, not necessarily this frame

golden ermine
#

how to fix

edgy prism
buoyant knot
#

also, you need ontriggerStay, probably

cosmic dagger
rich adder
golden ermine
rich adder
#

isEPressed = Input.GetKeyDown(KeyCode.E)

buoyant knot
#

you need to stop guessing and asking us

rich adder
cosmic dagger
# golden ermine

again, posting the error helps. that's not how you use TryGetComponent . . .

swift crag
edgy prism
#

mr Navarone I have a bone to pick with you

swift crag
#

I suggested making the player tell the campfire to ignite.

rich adder
swift crag
#

It should be a very simple class

buoyant knot
#

right now, we tell you X is wrong, and then you make some haphazard change immediately. You will not learn unless you take a moment to think

swift crag
#

This is all the campfire should care about.

rich adder
swift crag
#

when you tell it to turn on, it turns on.

edgy prism
# rich adder oh uh that dont sound good

Hahha you remember a few days back we were talking about inky? I have spent all of today and more of yesterday than I care to admit trying to figure out how to implement it in my code

swift crag
#

you're creating needless complexity by making the campfire try to find and reason about the player's inventory

rich adder
edgy prism
golden ermine
buoyant knot
rich adder
golden ermine
#

okay guys this is what it looks like now, so first issue is why is trygetcomponent not working

swift crag
#

because that's not how you use it, full stop.

rich adder
swift crag
#

you should read the documentation

#

you can't just mash random words together and get a working program

rich adder
#

that and Ive shown you example

#

twice

rich adder
#

the doc does suck for TryGet

#

not gonna lie

#

I sent in a "Report issue with this page"

swift crag
#

what is the problem?

cosmic dagger
eternal falconBOT
rich adder
swift crag
#

i noticed that the old docs don't do that

#

the generic type is implicit

edgy prism
rich adder
#

yeah its weird, hopefully they fix it lol

#

also would be nice to show that you can also use it if you already have a non local var

cosmic dagger
#

yep, weird they added it in there . . .

eager elm
#

that's also pretty advanced for beginner code, just use GetComponent() and check for null

swift crag
#

it has an out parameter, I guess

rich adder
#

Rigidbody rb = null;

if(TryGetComponent(out rb))

#

they also missed this example

golden ermine
#

i know this is incorrect but i dont understand it by that document

cosmic dagger
rich adder
#

it means its reduant

golden ermine
#

yes

rich adder
#

you can remove <PlayerUI>

swift crag
#

It's not exactly what you intended, though.

#

It is storing the PlayerUI object it found into the woodCount variable

cosmic dagger
swift crag
#
if (playerUI.gameObject.TryGetComponent(out PlayerUI ui)) {
  // the ui variable isn't going to be null in here
  if (ui.woodCount >= 3) {
    ...
  }
}
#

This is a valid usage.

#

The method returns true if it finds the component.

#

You can then use the component inside the if block.

#

If the component is not found, the block is skipped.

eager elm
#

the entire code is unnecessary though, just change

GameObject playerUI to PlayerUI playerUI

swift crag
#

that would also be reasonable, yes.

#

I almost never reference a GameObject

#

I always want something more specific

golden ermine
rich adder
swift crag
#

That ought to work! I would break the big line up into smaller chunks.

#

But it looks fine to me.

golden ermine
#

Okay thanks guys, also did i fix bool that says when e is pressed. Cause i dont see why it shouldnt work lol

rich adder
#

nah do it like i suggested @golden ermine

eager elm
golden ermine
rich adder
#

you're gonna get null reference exception then

golden ermine
#

how to fix it

rich adder
#

make it not null

golden ermine
#

yea but how can i assign it when its in prefab

rich adder
#

depends why does campfire care about UI in the first place

#

some type of unity style dependency injection, pass the component through method from whoever has the reference

golden ermine
#

cause in playerUI script i count how many wood i have

rich adder
#

the UI should not care about logic

golden ermine
#

i know but its not only ui i named my script wrong

rich adder
#

and your stats should be public /singleton available

rich adder
golden ermine
#

they are public

rich adder
#

you need a singleton

#

so you can make it static

#

then you just access stats when you need them

#

PlayerUI.Instance.wood

#

or w/e

golden ermine
rich adder
#

right

#

so you need to just assign it

#

this isn't needed

#

and the other one in if statement trigger

golden ermine
rich adder
#

looks good

#

tryget is useless now

#

and still doing it on a null obj

golden ermine
rich adder
#

did you assign the instance

#

to the PlayerUI

golden ermine
#

no where to assign it

rich adder
#
private void Awake()
    {
        if(instance != null && instance != this )
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
        }
    }```
golden ermine
#

okay i did it

#

thank you it works now, now i can have as many campfires as i want haha

rich adder
#

🙂

golden ermine
#

😟

rich adder
#

haha that comes later tho, you did well so far

#

quick learner

#

using class /struct will just help you group stuff together

golden ermine
#

hahah thanks

#

okay

sand veldt
#

i think its a dum question but is it necessary to clear a list or we can set it to null

private void table_OnTableSitEvent(object sender, Table.KitchenObjectSOsEventArg e)
{

    kitchenObjectSOs=null;
    kitchenObjectSOs = e.kitchenObjectSOs;
    CreateUIIcons();

}
wintry quarry
sand veldt
#

i dont want to clear data from the real list

wintry quarry
#

kitchenObjectSOs = e.kitchenObjectSOs; is sufficient

#

kitchenObjectSOs=null; can be deleted, as it is simply overwritten on the next line

#

it's kind of like

int x;
x = 5;
x = 3;
print(x);```
#

you don't need the x = 5 line, it adds nothing of value.

pine abyss
#

Hello folks!
Weird question. Would anyone have any idea how to use the SetLookAt IK function to rotate an animated head of an avatar based on mouselook? I know how to make it rotate with regard to another GO, but based in mouse? That's too much for me... thanks! ❤️

wintry quarry