#💻┃code-beginner
1 messages · Page 51 of 1
My favourite part of Unreal is the ability to add infinite colliders to even just one Object and just manually set up the subscriptions when the Object is made
GetComponentInParent also works if you call it on the object with the component on it
The fact that im being doubted this much makes me wanna check my facts, 1 sec
yeah, give it a look real quick
i need to stop "giving things a look" in my actual projects
i keep finding random crap in my scripts
ah, int wtf = 123;, hello there
git stash :)
hmm true
git stash my work, do the thing, hard reset and reapply stash
I prefer to just have a few projects in different editor versions and render pipelines
but I cleaned all of those up recently
Can confirm what Osmal said is true
Weirdly its not documented (at least in OnTrigger/OnCollision) but theres a few forum posts saying that the events get sent to the RB object, not the collider
Also im just 99% sure thats how it is
The object with the collider will not recieve messages if the parent has a RB
Yeah, event/subscription based collision would be cool to have in unity
i wouldn't think it would be hard to add that
Anything that moves away from messages, with their nitpicky names and occasional lack of specificity, would be a win in my book
well I showed you how in that SO post :p
you just get a unityevent for what to do when the trigger occurs so you can link that up to any custom event system too
is there a way to check in the method update, if something collided? I mean i want the experience on the floor to move toward the player. But for it to move, the move method needs to be inside the update. So what I need is like inside the update method something saying. IF the object collided, move.
becuase if I do that inside the on collision tigger the method is called 1 time and I need it to be called every frame to keep moving
Use a physics query like a Raycast or CheckBox
hmm never used both.
You should use Raycast/Cast/BoxCast/OverlapCollliders/etc if you want to know what is colliding in the middle of a normal evaluation.
You should use OnCollisionEnter/Exit/etc if you want a method to be called only when you enter/exit/stay in collision with something.
OnCollision methods let a script know what to do AFTER a collision happened. Casts let you move things while respecting collisions at any time.
hmm ok ..got it
How do I detect if a player enters an area? I put a box collider in the area that I want to be detected and it istrigger. Im having trouble code wise because im trying to access the colliders script from a gamemanager script and i dont think im doing it correctly.
Why do you need to use a gamemanager here?
Put a OnTriggerEnter on the area/box collider object
Because the gamemanager has a whole lot more information
The method has a parameter for what collider entered it
My Game Manager
{
public static GameManager instance;
public GameObject player; //test
int enemiesRemaining;
//door stuff - Dami
EndDoor endDoor;
[SerializeField] GameObject door;
FinishLine finish;
[SerializeField] Collider box;
static private int floorLevelMax = 1;
int currFloorFinish;
public bool isPaused;
void Awake()
{
instance = this;
endDoor = door.GetComponent<EndDoor>();
finish = box.GetComponent<FinishLine>();
player = GameObject.FindWithTag("Player");
}
public void UpdateGameGoal(int amount)
{
enemiesRemaining += amount;
if(enemiesRemaining <= 0)
{
StartCoroutine(endDoor.OpenDoors());
ExitDoorCondition();
}
}
public void ExitDoorCondition()
{
if(finish.isInBox == true)
{
currFloorFinish++;
Debug.Log(currFloorFinish);
if(currFloorFinish == floorLevelMax)
{
YouWin();
}
}
}
public void statePause()
{
isPaused = !isPaused;
Time.timeScale = 0;
Cursor.visible = true;
Cursor.lockState = CursorLockMode.Confined;
}
public void YouWin()
{
Debug.Log("We got here at least");
statePause();
currFloorFinish = 0;
}
}```
Hey guys I have a prob here, cant understand why.. it was working and now its not.. and I am confused. I have this message. but in the code I have like this
My Collider```public class FinishLine : MonoBehaviour
{
public bool isInBox;
void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player"))
{
isInBox = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
isInBox = false;
}
}
}```
Drag-drop an object in the Inspector
Then you have another script attached somewhere else, that doesn't have it
Like below the Circle collider here
oh no
i didnt see it.. might have dragged
byt mistake.. damn I am so tired like 10h straigh in unity + work
I think i am going insane
need a rest hahah thank you !
Your gamemanager has a static instance accessor. Just use that in OnTriggerEnter
what do you mean?
You can access your game manager from anywhere. So do what you need in the Game manager from the finish line script.
the boolean
What is the goal of this? To call YouWin?
"Tell me you copy-pasted the code without telling me you copy-pasted the code"
dude i didnt?
Which boolean and what about it?
GameManager has a singleton setup. It has a static field you can access anywhere that will refer to the one GameManager in the scene, use it
the boolean in finish line. I need to check if it is true, bc if it is, i need the things in ExitDoorCondition to happen
Call ExitDoorCondition from finish line
Don't check the boolean
okay but please dont insinuate i just copy pasted code. I didnt. I wrote this, I just dont have a full understanding really
I can do that?
Yeah... you have a static accessor
Sorry im not totally familiar with this. I literally just learned what this was like 4 days ago
GameManager.instance.ExitDoorCondition();
okay cool. thanks
Is there a way to tell Unity when to compile ur code rather then on each time u save a file
You can set the editor to not automatically reload
preferences -> asset pipeline -> auto refresh
It will recompile when you hit ctrl-R, or when you create/move/delete a script asset
I guess that, more pedantically, this just means it doesn't look for changes to files until you hit ctrl-R
if you create a new script asset in unity, it sees the change immediately
And then there's CompilationPipeline.RequestScriptCompilation() method if you want to trigger a compilation via code, like with an editor window or context menu
hey guys.. why that doesnt work? the game object with this script always go towards the player.. even if I dont move with the player .. this object goes inside the player to its center, but even tho they have same position .. the object is not deleted
Just remember it when you're wondering why your code changes aren't working haha.
It's a common confusion when doing that at first
very unlikely for the positions to be exactly equal
unless you directly assigned it
Yeah lol^^
Also why are you checking the same condition twice?
so if its unlikely how do I do that check? is there a way to say, if u are 1cm from the player delete?
I just dont like having to compile alot because compile times in Unity are pretty slow compared to Godot or unreal IMO
sure
check within a certain threshold, yes
ops.. i forgot to delete
Vector3.Distance(a, b) will give you the distance
then you can check that it's within some small amount
Distance is not a Vector3
"I cannot put a float into a variable of type Vector3" would be a more user-friendly message
When you try to use a variable of type Foo in a place that wants a Bar, C# will try to convert it.
Since you did not explicitly ask for a conversion, this is an implicit conversion
it would also be harder to write. It's not necessarily a variable assignment that the expression is feeding into. but yes compilers overall could be clearer with errors
If this is impossible, you get an error.
You will get a different kind of error if you try to perform a cast (an explicit conversion) between two incompatible types.
Sometimes an explicit conversion is legal, but an implicit one is not
now its working.. thank you
e.g. float explicitly, but not implicitly, casts to int
now i need to learn about this checkbox or raycast to use instead of ontrigger enter.
When this is the case, the error will be appended with "an explicit conversion exists, are you missing a cast?"
indeed
the thing i find funny is how int to float is implicit
even though, by definition, the number of floats that loses precision when they become an int is exactly equal to the number of ints that lose precision when they become a float
doesn’t implicit just mean you don’t have to ask?
You don't have to tell the compiler
No cast required
that’s what I thought. making sure
For everyone in here who has helped me, I just posted a first (very early) preview of my game in #archived-works-in-progress
Just wanted to let everyone here know, so you can see what you have helped me build so far 🙂
Hi. I have been stuck on this problem for a bit now. Im trying to reference this playerInventory script in my script but it wont let me do it in any way.
public Inventory playerInventory; Player.cs
using UnityEngine;
public class Inventory
{
public List<Weapon> ownedWeapons = new List<Weapon>();
public void AddWeapon(Weapon weapon)
{
ownedWeapons.Add(weapon);
}
}
``` *Inventory.cs*
Everything else will show but not inventory. Not even while debug mode turned on
your inventory class is not a monobehaviour/scriptable object and isnt using [Serializable] so nothing will show in inspector for you to setup.
If you want to access an instance of inventory that already exists, then itll have to be a monobehaviour or SO. If you want it to create a new Inventory for you and just save some values to it, use [Serializable]
Add [System.Serializable] before the class declaration for Inventory
Hello i am using AI in unity
agent.stoppingDistance = range;
void Chase()
{
// if (Vector3.Distance(transform.position, player.position) > range)
{
Movements(player.position);
}
}
is if here is usefull or not i am calling Chase function in Update
What does Movements() do?
agent.SetDestination(movDir);
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Then if the distance is greater than range, you set the destination to the players position
Can't say if it's useful. You tell us if that's what you want
Well, this will do that when the distance is greater than range.
There is no function to stop when too close though (in the code you showed)
i am using this also
agent.stoppingDistance = range;
is if statment needed or not
what do you think?
If the AI is already within the range should you SetDestination?
no but i want to know because vector3 use power i am not too sure
i mean without if it still working fine but i wanted to optimize it
Hey, guys! I have a question. I want to make in my game a functionality that when I click QuitButton to exit playmode and application, I want it to happen with a delay of 1 or 2 seconds. I was thinking to use IEnumerator in order to achieve that and also was thinking to use waitforseconds to do that. Can you please tell me which way is the best to make this functionality work?
Sorry, glossed over that. If your stopping distance is the range... then it will stop at range
Not sure at all what your most recent comment meant though
Question: I'm using the free FIrst Person Character Controller, and I'm getting the following error when trying to declare a variable using a class from one of it's scripts:
I tried that and I get the following error:
Assets\Dudesss Custom\Furniture\Scripts\FreeObjectPlacement.cs(16,16): error CS0246: The type or namespace name 'FirstPersonController' could not be found (are you missing a using directive or an assembly reference?)
what do you think will happen if, for example you have a AI at 5m, and the range is 10m and you do a SetDestination?
nothing
When I put using at the top, it can't find the namespace:
Is there a class named FirstPersonController? Is it in a namespace?
Why would they do SetDestination there? The if is for if the range is too far
They wanted to know if they had to do an if to stop
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
exactly, so why are you questioning this?
because they have already defined the stopping range, so why do anything which is within that range?
Are you using that namespace in the script that's trying to reference this class?
I'm using a different namespace in my script
I figured with using, I could call the other namespace's class
i wanted to know
is SetDestination will cost processing power while player is not in Chase Range Compare to Vector3 distance
Is there something wrong with this script?
When I go into Game Mode to test it; none of the text actually changes......
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
!code
Only shows a download link on mobile
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello guys
heey, hello everyone again... I need help with location permissions on my game in android... This is the code https://gdl.space/xayokuhipu.cs the game ask for location permissions on awake, that works correctly, but the first time the game ask you for location permissions it doesn't send your coordinates to the API, that doesn't happen again when you restart the game... Could someone help me? I have no idea about what's happenning...
why is my project taking so long to load???
beause the project loading imps are on a go slow, probably due to lack of food
lack of food?
I hope you are able to know what's happenning...
Ah, right.
If you have using then you can reference the types inside that namespace
did you not feed the Unity imps?
Although if you have assembly definitions in your project, you also need to make sure the assembly has a reference to that namespace's assembly
That script is using the following assembly, but I'm not sure if I should reference it and I don't know how:
It's sarcasm
Go read the documentation about unity imps
Damn, you had to ruin it
I've added a link to hastebin on the OG post.
You do know that computers run on imps and that you have to feed them don't you?
it has been loading for 12 mins
Not a code question
could someone take a fast look to it...?
Do you have any .asmdef files in your project?
My class is using an assembly definition
i made a script to automate the rations
Then that assembly definition will need to reference one that contains the FirstPersonController
what's the syntax to make an instantiated prefab have the position and rotation of the parent object?
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
One of the ones with position and rotation parameters
transform.parent.position
transform.parent.rotation
ohhh I see, I did have it right, it just didn't register the syntax for the first argument as correct until I typed both
it told me it couldn't convert from Vector3 to transform
what does this mean?
google is being inconclusive, something about the editor being open too long? a few people saying "nvm fixed" and not saying how
It's not anything related to your code, I'd say just restart the editor and see if it goes away
hey guys, how do I check on update for something that enter my collider if I cant use the ontrigger enter method as it call things 1 time. checked raycast and box something but cant understand how to do it. any help?
OnTriggerStay
then describe it more specifically, what are you trying to do if not be notified constantly about something inside the trigger
So basically what I need is that I have a player.. when I kill a monster he drops exp on the floor.. and I want that when I get near the exp .. it will fly to me. But my player has a collider to check other stuff so I am using another empty object that follow player position with a trigger to check that collision with the exp
but the prob is that the script is on the object that will collide the empty one.. and I need to call the method MOVE on the exp script
but it needs to move only after entering the area of the trigger of the empty object
and that is it
this is the movement and it is working
now I just need to make that move be called when I enter
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the area that I can collect
so the problem is that you dont know how to call the Move function?
Its also very unclear what this empty object is really needed for, you can simply check OnTriggerEnter what kind of object has entered the call logic according to that
I'm not sure how to find the assembly definition for StarterAssets namespace
hi just wondering if anyone could help with my invoke? just wanting to delay the asked for request bt 2 seconds but in game it just says invoke couldnnt be called, thankyou
You invoke by using the function name only.
this isnt an empty object if there is a collider on the object, but regardless OnTriggerEnter you just check if the object has the script you are looking for. If it exists, then call Move and pass the transform in as a parameter
And you cannot use parameters
I tried that and got the same result
Because your function has parameters. In other words, you cannot use invoke for what you're doing.
oh invoke was the only way i knew to delay things, what else can i use to delay the function i am trying to sorry?
A manual timer in update, or a coroutine.
i did actually try a coroutine but it didnt work either, how do i impliment a manual timer into my code?
Coroutine will work.
Manual time is tracking deltaTime in update by storing it into a float variable and checking if it has surpassed some value.
Your IDE should be throwing an error
This is the error i recieve using a coroutine in my code as shown above
Yes, because you're not passing anything to the coroutine and it's expecting it.
what should i pass through? this is how it was shown in the video just obviously with my additions in
Whatever you want message to be? Think for a second of what your function is actually doing.
showing a desription of the item
You have not passed in a string to the function
What value do you want message to be
is the value not the 2 for 2 seconds
What?
Your functions purpose (assuming you actually know its purpose), is to display a message on a text component as a tooltip.
When you call that function, you have to give it the message to display as outlined by the functions parameters that you've made.
But I'm starting to realize this is likely a copy paste attempt at functionality with little to no knowledge of coding.
i watch videos to try learn what to do and add and use them to complete the actions i need, in this instance id have only known how to use a invoke but am in unknown territory here, the actual terminology behind alot of the code keywords kind of go over my head causing me to misunderstand alot which i apologise for, i usually just learn better being taught it first then figure out how to apply it into my own, as this is a little slip up i just need a little help with ive turned here for some help
This isn't about invoke or coroutines or how to make something happen after an amount of time, it's basic coding and understanding of functions.
You may want to do a tutorial on basic coding
If you don't understand words like "parameter" and "value" then you should look into the intro to C# guide in the pins. It's not going to be possible to help you if you literally do not understand the words you're being told
hello. i have a rigged model GO (with no components, freshly instantiated), and an animation clip array. what is the simplest way to make that model play the animations in the array at runtime?
this wasnt meant as a bad or snappy remark either i just wanted to not come across as a doughnut
Is the clip array something you know before the game starts running or something you dynamically load at runtime
know it beforehand
parameters are the bools float etc i thought, am i wronh?
Wrong
Then I would recommend making an Animator Controller instead of an array, with those animation clips as states set to transition to the next after it's done. Then all you'd need to do in code is set the object's animator to that controller:
https://docs.unity3d.com/ScriptReference/Animator-runtimeAnimatorController.html
SetAndShowToolTip(string message)
It's expecting you pass a string representing the message when you call the function.
variables then?
thank you very much
so do i need to add my message i want to be displayed on screen in the brackets ?
for this to work
or am i way off
Simply put: What value do you want message to be when you call that function
i have the message set up in a different script thats added to the items to give them each specifc item descriptions
Then you probably want to pass that value to the function
but isnt my value different with each different item description?
You would need to pass the value you want to display to the function that displays a value
What value do you want to pass to that function
the item desription
what item description
but thats different with every item because its in another script
so the value can differ depending on the item
So what item description do you want to show
one for each food i pick up
so 3 different item desriptions
not just 1 specific item desription
one with like the ingredients for pie when hovering over pie
Well, you're calling this function in Start of your ToolTipManager script, so what item description do you want to show when the ToolTipManager is created?
one for cake ingredients
the one that is entered into the next script
so i have the script youve seen
What does this mean
I have a Vec3 that is the normal of a plane. I have two other Vec3s, A and B. How do I get the angle between A and B on that plane normal?
Yes this is the code I am looking at
it goes into the next sccript the setandshowtool
This is the same code that I have been looking at. What value do you want to display when this object is created
then when attaching this script to the desired item i can enter whatever message i wish in the inspector
Other than the fact that the OnMouseExit function seems to be unfinished, this is fine
I am getting an error can someone help me
But also irrelevant
Invalid file content for Library/StateCache/SceneView/8c/8cd7c613bf844de3b80696e27a479d5e.json. Removing file. Error: System.ArgumentException: JSON parse error: The document is empty.
at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type)
at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x0005c] in <4648fab9f0e14a8c97a9b3401f73e835>:0
at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in <4648fab9f0e14a8c97a9b3401f73e835>:0
at UnityEditor.StateCache`1[T].GetState (UnityEngine.Hash128 key, T defaultValue) [0x00067] in <273a7cbcc8d7454ea7ae78e07082aa77>:0
UnityEditor.WindowLayout:LoadDefaultWindowPreferences ()
Not related to any of your code, you can probably just ignore it or restart the editor
i did
how though this script is added to the item then the message is entered there, not in the script i wish to get a delay on
it still wont let me test it untill it is gone
Close your project, delete the Library folder, then re-open the project and let it regenerate the Library
This script is calling the function fine, it's passing an argument. ToolTipManager is calling the function in Start with no value
That's the one you need to fix
Hello, I've been having some trouble lately and I came here to understand why. I make the player movement script, and the mouse looking script... I place a game object and I try pressing against it. I see that I can walk through it and just put a box collider on it. I try again but i can still walk through it? I went on ChatGPT before this and i did all the things it told me but it never worked... Does anyone know what I could do?
oh, nvm thank you @polar acorn
How are you moving the player
but the value is determined in the next script isnt it?
You are calling the function in Start of TooltipManager. What value are you trying to display in Start of TooltipManager
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalInput, 0.0f, verticalInput)
transform.Translate(movement * moveSpeed * Time.deltaTime)
}
and i already put the movespeed variable
- !code
- That's teleportation, it's not going to collide with anything
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
If you want physics, you have to use physics. Either a Rigidbody or a CharacterController
Thank you so much!
a tooltip message
what message
the item description
which item
3 different items
hello, just get started with unity, should i start lookin into linear algebra of some geometry in order to learn how to manipulate 3d object?
also could someone, please, share some websites with free 3d assets?
which one
all of them?
i dont just want 1 to work i want alk 3 of them to work
at once? Comma separated?
no each individually when hovered over my mouse cursor
I'm not asking about when you're hovering
I'm asking about what value do you want to display in Start of TooltipManager
Then why are you trying to display a message in Start
If you don't want to display a message in Start
nothing until an item is hovered over
So then why are you trying to display a message in Start
what is "null"
nothing
where does it need to be set up then to only appear when an item is hovered over
You seem to already be doing that
but i want a 2 second delay before the item desription is shown
Yes, that seems to be what your coroutine does
but your saying it needs to display a message when started
thanks bro 😎
i dont want that
No, I'm saying you are currently doing that
and I'm asking why
i want it when the specific item is hovered over
when it seems like you don't want that
thats why ive asked where does the coroutine need to be then
to do what i am asking
When you want to display it
Digiholic are you someone who is advanced helping the beginners?
but how do i say that in code
like i cant type the code when hovering over an item to say do it now
Again, you already are. You're displaying the message when you hover an object
So why are you trying to display something in Start as well
but how do i add a delay to that
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
StartCoroutine
thats what im askinf
where does the coruitine need to go though if not in start thsts what ive asked
Where you want to use it
Which in this case is on hover
when an item is hovered over
so i need to do it in the other script for onmouseenter
Yes, start the coroutine there
fixed it thankyou
Hello, my brain is about to crash, I need some explaining from someone please.
I am watching this tutorial video where we create a script called "PlayerMovement"
and we also create a script called "PlayerCollision"
https://prnt.sc/0KhhmW7aj37L There is s "PlayerCollision" variable we wrote called "movement", in order to refer to the "PlayerMovement" script we wrote line 7.
But why do we have to we have to put "PlayerMovement in the empty slot in order for it to work, haven't we refered it in the script yet?
https://prnt.sc/0dAPF_PeZmdD
https://prnt.sc/pqPkBX04AP_r
please someone explain
You have to tell it which PlayerMovement you want to use
to... to make it public?
So you can set it in the inspector?
and reference it in other scripts?
Theoretically, it looks like you could just as easily have done [SerializeField] private instead
You also need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
so you cannot refer it from the script?
I don't think anything else is gonna reference this
I don't know what you mean by this
I already somewhat did
It took me 1 hour
somewhat isn't enough

there was no IDE at all
...what?
There still isn't
So finish configuring it. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
which one should I use
which one do you want
??? Just configure the one you're using
installed via unity hub?
Did you install it via the hub?
I installed both visual studio and unity hub, so I am confused on which one to take care of
Did you install Visual Studio from Unity Hub or not
I don't remember 😔 I tried it to install it from both
because IDE didn't work
I will just do both methods
😎
I'm too cool
As long as you have one IDE that is properly configured, with it being what is opened and configured in the External Tools settings then it should work
No one is asking you to do both, your being asked so they can help you with the context needed
I tried to fix it for an hours before
this is the best I got
I'm aware, and software sucks
But the thing people suggest you get an IDE for isn't working for you currently
😎
I am doing it
🤙
https://prnt.sc/Oi2pmMqZ4VM0 fixed 🙏 🤙 😎
external tools keep getting switched I don't know why
thanks for the help @north kiln @polar acorn
@polar acorn I'm sorry, but I still didn't figure out how to reference the FirstPersonController script. I don't know where it's Assembly definition is.
You might need to create one
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this should say in units like "K" and "B"
for example. instead of 7,025 it shows in 7K
but when I debug Log it, it does work properly
but not the textbox
If your log displays that value then your text is being set to that. Are you sure the text you're looking at is the one this script is referencing and that it's not being set somewhere else
Why are you using find, and why are your variables of type game object. Just make a public variable for the text component and drag in the object you want directly
oh
yo i have a collider in this 3 d game and it get turned on during animation and i have a code saying if acollison happens on this other object it get deleted but when i play the animation to swing the hammer down the object thats supposed to be deleted because of the contact does not get deleted what do i do?
Show code
how do ido it again on this sever have been onthis server since forver
here very simple
Put a debug in it to see if it's triggered at all
ok
Show the inspectors of both objects
What Do you mean by show inspectors
doesnt look like it triggered
I mean send screenshots of both objects inspectors
Which one has the rigidbody
none
So fix that
well i had one but it didnt do anything
now some how its workin even tho before i had one and it didnt work
well now i have a massive glith
glitvh
glitch the hammer pice get disconected and starts flying like super man bro
man it work but now the hammer part flies like super man
Is there a unity function that gets called when an object gets SetActive(true); ?
is it OnEnable() ?
Ye.
Which GetMouseButton is it for XButton4?
i tried with index 4 but it doesnt work
maybe 6?
if 0 and 1 are Left click and right
why doesnt this work?
print(gameObject.transform.transform.parent.parent.name);
textAssetText = gameObject.transform.transform.parent.parent.GetComponent<SettingsPopup>().textObject;
imageComponent.color = textAssetText.color;
colorField.text = ColorToHex(imageComponent.color);
What is image component
have you debugged which part is specifically null?
also that transform.transform.parent.parent is definitely questionable...
Image component was null
no i have it
Or text asset text (text object) was null
thats just so confusing then because its not null
nre means that something before the member access operator was null but tried to access a member
The text object should not be null, log them both
🪄 debug them both so you dont have to guess by looking at the inspector
You can just log them to see if they are null
Don't rely on what you think refers to what. Just debug or log what the compiler sees.
alright
trying to add a check so it doesn't destroy the enemy gameobject before detecting another collision from the projectile game object since with raycasting i ran into the issue where the enemy would destroy before the fake projectile would reach it
have not been able to figure it out
How can I cache a current object and all of its children then when I want to revert everything back to that state?
the note at the top of enemy cs can be ignored i forgot to remove that
If you want to “revert” some objects back to some state, you need undo function, not just caching
well the problem is im changing a lot continuously
if there isnt a simple way to do it thats fine
ill just work my code for it
I remember unity provides some undo function you may search it
could just use version control for this if its a lot of changes. Create some branch, work on that branch, if it doesnt work then just go back to the main branch without merging. If you want to keep some small changes along the way, then commit those and undo the others
otherwise you would be looking at making a custom editor script to store everything, which could work but its more effort for something that may be buggy
hello
how do I create a simple first person controller?
I've looked at heaps, but they're whack
Define "whack"
how can I make a prefab have a constructor with an optional argument? i want to have the option of inputting a size for an object, but if no argument is given, have a default value
and will it work with Instantiate()?
a prefab with a constructor doesnt make sense, you need a script that inherits from monobehaviour and then adjust it on awake/start
or adjust it after instantiate, depends what object you are adjusting
Making an asteroids clone for a project, was planning on
asteroidBreakFunction
{
makeTwoClones(0.5 current size)
destroy(self)
}
or alternately
asteroidBreakFunction
{
makeClone(0.5 * current_size)
makeClone(0.5 * current_size)
destroy(self)
}
pseudocode, I know the syntax is wrong
just planning
i mean both would be doing the same thing so really doesnt matter which you choose to go for, you'll need to specify 2 positions somewhere whether it be in each makeClone parameter or if makeTwoClones calculates that by itself.
Either way, just adjust the size after getting the object returned from instantiate
Ohhhhh right, I forgot that instantiate leaves a variable to play with behind
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
whats the difference between transform.SetParent(parent) and transform.parent=parent
they one and the same or is one more stable etc?
I think it's the same in that overload.
But there is a second parameter in SetParent
https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
Oh, yep
"This method is the same as the parent property"
ah okay thanks
the objects made by this function are disabled, along with all the components
I double checked and even remade the prefab, it's not prefabbing a disabled object
Just to be sure, show the inspector of the asteriodPrefab object?
And the clones are disabled? Not just invisible?
Fracture doesn't have any code that disables this?
Or any code anywhere that disables this asteroid?
Fracture was leftover code, removed with no consequence
and I'm just starting on any asteroid handling code of any kind, nothing should touch it
Can you test by making a brand new prefab which is just a plain cube, no scripts, no tag, and set that as asteriodPrefab for now?
Unless asteroidPrefab is not GameObject
Does the asteroid have a tag?
yes, it has the tag 'asteroid'
it needs that for the laser collision detection code
If you untag it, use your original prefab, see what happens
I'm just trying to figure out possibilities here. Thanks for your patience and cooperation so far
and thank you for yours
okay
strange thing
did the first part
I mean, second
okay let me start over
I replaced the prefab with asteroid1 again
now the first set of children are enabled
the second generation are not
Are you using object pooling
this is sort of a recursive system, every time the asteroid is destroyed it's going to be replaced with two 50% scale clones until it hits a minimum
probably not, because i don't know what that is
Okay, I'm going to suggest you ctrl+shift+f and search for SetActive
See if there's any that passes in false
new error message btw
no instances of SetActive with a false pass anywhere in files
Then it might be because of that error message, I'm not sure
Try to refactor your code to not spawn inside the OnDestroy
Sorry I'm out of ideas
thanks for trying
Try to use ondisable
making a five nights a freddys fan game and i want to sork on the like office movement I know i need to use clamp to do the classic movement style but would cinemachine be the best way of making it so the further to left or right i go the faster it moves
If I subscribe to an event when a scene loads and both the object that causes the event and the subscriber will both live the entire scene do I still need to unsubscribe? The reason for not wanting to do so is that I will need to add a reference to the event caller on the subscriber and that seems like unnecessary coupling
typically, it's suggested to add and remove events to avoid memory leaks. also, if you subscribe to it, you already have the reference to unsubscribe . . .
hey guys, if I have this setup here, where I have a prefab experience with an array of gameobjects, and I referenced inside that array 3 dif exp tpes. and inside the enemy when it dies I am saying drop(instantiate) the experience. But is there a way to tell which one?
The subrscription happens in another function that passes on the ref, so I would have to store it. But would it cause a memory leak? when the scene is finished and both objects are destroyed?
your enemy has a specific experience prefab. it will always load that one. if you want to randomly choose an experience prefab from that list, you need to select a random number based on the array length, then use that number as the index when accessing the array . . .
yeah but I cant do something like that: ``` Instantiate(_experienceLowPrefab[0], transform.position, Quaternion.identity);
it wont allow me
experienceLowPrefab is the prefab, it's not an array. the array is on your ExperienceLevels script . . .
hmm.. so i need to create a method in ExperienceLevels, that is called when the enemy die in the enemy script
possibly, bc the event is still referencing that block of memory. the objects are destroyed but the memory from the subscription is not released . . .
and that will tell which one to spawn?
Ok, thank you, better safe than sorry I guess
There is no way of unsubscribing without adding a refference to that object right?
not sure why you have a separate script just for the array of experience. you can put the array on the enemy script and randomly choose an experience level when the spawns (or dies) . . .
it is just very hard for me yet to think and choose which scripts to create and where to put things..
Its harded than coding it self. Sometimes I get lost for hours just trying to ifigure out where things will be
if I create a script only for exp.. or if I create 1 for the enemy and inside the enemy it will contain the experience logic etc
so hard to decide those things
also if I have 5 types of enemy.. dont know if I create 1 script and control all or should i create one for each.. or create 1 prefab for all and control it with other prefab
and things like that so hard to decide and understand
not that i can think of (at the moment) . . .
hmmm, you could unsub in the subscribed method, but only if the event is invoked before the GameObject is destroyed . . .
If both objects are destroyed (like both are in a scene, and you change scenes) then it should be fine. Anyways, people use lambda subscriptions all the time and you cannot unsubscribe those without storing it first
if you create a script for the experience prefabs, then every GameObject you want to use it will need a reference to that script. it's easier if the GameObject 'Enemy' has the array of experience itself to choose from. you can have multiple enemy prefabs with a different number of experience prefabs [in the list] . . .
hmm.. and as a good practice or best way to do it. always when I have like 10 enemies or 10 types of experience.. should I control all of them using an array inside just 1 prefab?
you can make a ScriptableObject holding an array of experience prefabs and create the asset in your project folder; then, declare an SO variable on your enemy prefabs and reference the SO asset [from the project folder]. that'll save memory and allow for customization by creating multiple SO assets with different experience prefab setups . . .
if each enemy type has a group of experience they can provide, i'd use a ScriptableObject holding an array of the experience prefabs. if all enemies pool from the same group of experience prefabs, then using the SO works just fine. every enemy will point to the same SO in memory and randomly select from that pool
if a group or specific enemy uses a single experience prefab, place a check in the enemy script to avoid selecting from the array . . .
Each enemy will have similar behaviour right? Ex: regardless of who the enemy is, they may have an idle, moving, attacking mode.
Calling the functionality for these 3 examples should be done from 1 script, while the idle, walk, or attack functionality can differ between them. Like one may idle by standing around, one may wander, this functionality can be in another class and plugged into your enemy class
will check you guys input in some minutes, thank you for ur feedback, just finishing some work stuff.
Im trying to make a cube runner game for mobile but how do i make a working script so it works
looks like this now
i want it to jump when you click
i did check a tutorial but it dosent work
This could literally mean anything. A script for what? If you haven't started, I suggest searching YouTube or Google for a tutorial to follow . . .
are you getting an error? what is not working?
lemme try it again
how can i call a function as a prefab?
if the ore is being mined the "hp" of the ore should go down and if they hit zero the prefab calls a function that adds money
but i cant get a reference to the moneyscript
are you trying make object in scene reference some script on the prefab?
I made Exactly like the tutorial can anyone help me
That's obviously not even close to what the tutorial shows
i did like he did
that is definitely one for @polar acorn
so do you compare his code to your code?
How do you suppose those are the same as what you have
IDK IM NEW TO PROGRAMING
New to reading too?
no i dont have a solution right now
i dont know how to get a reference
no its just like everything he does when i try it dosent work
the prefab should call a script function that is on the player
Do it the same way and it'll work
i cant cuz everytime i do it dosent work
bro try it yourself it to write the code exactly like that it wont work
Why don't you try it yourself first
because the code you showed was just nonsense
do it the same way as the tutorial and then come back
I REMADE IT LIKE 5 TIMES THE THINGS HE USEDOSENT POP UP OR IS ON MY KEYBOARD
https://unity.huh.how/references/simple-dependency-injection
you may need this, pass the reference of your player to the gameobject after instantiate the prefab
You can't skip parts that you don't know how to write
I AM TRYING AND IM DOING MY BEST
if you don't know how to type a character then either google it or ask
I DID GOOGLE IT AND ITDOSENT WORK
ty
Ok cool. If you can't follow a tutorial then there isn't much we can do for you
first check the syntax, you have mismatched '{'
and syntax of function call rb.addforce is wrong
this is my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float jumpForce;
private bool canJump;
// Awake is used for initialization
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Start is called before the first frame update
void Start()
{
canJump = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && canJump)
{
Jump();
}
}
// Handle the jump logic
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
canJump = false;
}
// Handle collision events
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
canJump = true;
}
}
}
jumpforce dosent comme up
```cs
code
```
Post the code correctly
how do i pass the reference? its not working
can you show where
As written above
like where in the above
warp your code in ```cs your code here```
Can you show screenshot?
wait i'll do it for you
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float jumpForce;
private bool canJump;
// Awake is used for initialization
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Start is called before the first frame update
void Start()
{
canJump = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && canJump)
{
Jump();
}
}
// Handle the jump logic
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
canJump = false;
}
// Handle collision events
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
canJump = true;
}
}
}
thanks
Ok, so what's the issue
gameobject go=instantiate(prefab);//or instantiate the script directly
go.getcomponent<script on ore>().init(pass the reference to moneyscript to script on ore)
```some ways like this
copied his code that dosent work
Sure, but what doesn't work
On this playercontroller script its supposed to come jumpforce that dosent work
I will try it thank you
Are all errors resolved throughout all your scripts?
think so
do you save the script or there are any compile errors
If there are any errors present then the code will obviously not compile
And the new version won't show up
New version being these fields that were meant to show up in your player controller script
mabye works now
First resolve any errors you might have, recompile and then check
IT WORKS
Good
FINALLY
Are you new to just Unity or programming in general?
new to unity and programming
ye but thanks fo the help
Good luck either way
Just don't try forcing yourself into Unity without learning the basics (C#) first
.init is not defined
ah i have to create it first right?
ofc not defined, you have to create this function on your script first (and the field of type moneyscript)
yes ok
then the ore get the reference to the script on player
How can I disable a game object?
setactive
You click the gameobject
and deselect the tick in the upper left corner of the inspector
also not a code related issue in that case
i did it thank you @gaunt ice
Hi guys, I have a problem. I'm using the latest unity 2022.3.11f1 and I have just started using Unity having not used it for some years and wanting to get back in it. I have noticed that whenever I create a Enum list , save it, let it do its magic in Unity, then look at the script with the Enum in there, the IDE will freeze and lag for about 10-20seconds before eventually becoming normal again. I don't know what is causing this and the enum is not exactly hugh... it can just be 1 item in the list and it will lag just from switching away from the script to another script and then back, and it freezes again. Any ideas on how to get this to stop doing this?
this is all the code that is in there at the moment, and this is causing IDE to freeze?
It's probably unity recompiling the assembly after code changes.
You can disable auto refresh in preferences(or was it project settings?🤔) so that it doesn't recompile after every little change. You'll need to force refresh manually though.
Though, usually it wouldn't affect the vs itself. I think...
Why is my character starts to floats when i add a RB and m only using the rb for gravity and the gravity is set to -40 globally
What else do you have on the GameObject?
Just a heads up I'm going to be posting a decent size help question
Can you take a screenshot of how it floats(preferably in the scene view with gizmos enabled)
yeah a min
(i may be in the wrong room so let me know if i am.)
i am writing a enemy controller script and for some reason when the enemy touches the player #1 The player wont take damage, i know the damage and hp work as i have tested the hp earlier. #2 when the enemy touches the player it just rebounds and goes in a different direction randomly and i dont know why that is.
i can provide the scripts if you want to look at them.
Maybe a video demonstrating the issue and your code.
alright give me one moment
member names cannot be the same as their enclosing type - What does this mean?
That means that your field/method/property name is the same as the class name.
The real question is why is it floating before the play mode.😅
Thanks
lol my bad it was the animation that came with the model that was messing my bad i figured it jeez
I'm aware of the compiling after a change, that's fine, but unfortunately thisis beyond that. The other scripts that do not include Enums will save, and compile. (The bit I refered to earlier by magic Unity stuf) however, without any changes. If I then switch to another script from the tabs, then switch back to Enum without doing anything to either scripts, the editor freezes for about 10-20seconds. It's like having 1 FPS. You can see the cursor moving in the places you're clicking on within the script but its heavily delayed and takes about 10-20 seconds to fix itself. Unity itelf is doing nothing its just the IDE that seems to be doing something. ONLY when an ENum has been put into the code. If I delete the enum, I can switch all day everyday and it's instant, I can click on the script anywhere and type, and it's lag-free and instant. moment I put enum in there and save it, I can't type or do anything for about 10-20 seconds when I switch back to the script containing the enum.
not sure if I'm explaining this well
i cant get it filmed (My screen recorders not working)
but here are the two scripts
(Player Controller)
public class Playercontroller : MonoBehaviour
{
public int maxHealth = 100;
private int currentHealth;
private PlayerMovement playerMovement;
private void Start()
{
playerMovement = GetComponent<PlayerMovement>();
currentHealth = maxHealth;
}
//private void Update()
//{
// if (Input.GetKeyDown(KeyCode.BackQuote))
// {
//MountRideable();
//}
//if (Input.GetKeyDown(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Space))
//{
//playerMovement.Dismount();
//}
//}
///
//private void MountRideable()
//{
// playerMovement.Mount(rideable);
// }
// Method to apply damage to the player
public void TakeDamage(int damageAmount)
{
// Reduce the player's health by the damage amount
currentHealth -= damageAmount;
// Check if the player's health has reached zero or below
if (currentHealth <= 0)
{
Die(); // Implement game over logic or player respawn here
}
}
private void Die()
{
// Implement game over logic or player respawn here
// For example, reload the level or show a game over screen.
}
// Method to heal the player
public void Heal(int healAmount)
{
// Increase the player's health by the heal amount
currentHealth += healAmount;
// Ensure that the current health does not exceed the maximum health
currentHealth = Mathf.Min(currentHealth, maxHealth);
}
}
(Enemy Controller)
public class EnemyController : MonoBehaviour
{
public float moveSpeed = 2.0f;
public int maxHP = 50;
public int damage = 20;
public float damageRate = 1.0f; // Damage per second
private int currentHP;
private Transform player;
private float nextDamageTime;
private Rigidbody rb;
private void Start()
{
player = GameObject.FindWithTag("Player").transform;
currentHP = maxHP;
nextDamageTime = Time.time + damageRate;
rb = GetComponent<Rigidbody>();
if (rb == null)
{
rb = gameObject.AddComponent<Rigidbody>();
rb.useGravity = true; // Enable gravity for the enemy
}
}
private void Update()
{
if (player != null && Vector3.Distance(transform.position, player.position) < 10f)
{
transform.LookAt(player);
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}
}
private void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player") && Time.time >= nextDamageTime)
{
Playercontroller playerController = other.GetComponent<Playercontroller>();
if (playerController != null)
{
playerController.TakeDamage(damage); // Deal damage to the player
nextDamageTime = Time.time + damageRate; // Update the next damage time
}
}
}
public void TakeDamage(int damageAmount)
{
currentHP -= damageAmount;
if (currentHP <= 0)
{
Destroy(gameObject); // Destroy the enemy if its health is depleted
}
}
}
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Sounds. Weird. What version of VS are you using?
I can only guess that it's a bug with VS, intellisense, or possibly the unity VS plugin.
so do you got any ideas with my code at all?
Fixed it dont worry anymore!
what should i do to make my character have an animation?
not sure to be honest, the one it automtically installed when I installed Unity
yes I feel this is the case. I think its something to do with when it is checking to see if other scripts are referencing it
I may have found a temporary solution/workaround, it seems if after I create the enum, I close everything down, then open it again, I can now switch between the enum class and others , without any lag now
but if I make a change then save, it lags again until I close it all off lol
nevermind, that worked once but not again lol :\
hello all, i got a big issue with unity, it's not about code but since yesterday, every time i change something like a parameter or a small code, there is an unlimited loading that arrives.. cannot fix, i use unity 2020.3.48f1
i have been working for 3 years with it and since yesterday, i'm forced to close it with task manager each time i change something
do you have any Console for Errors?
Just for future reference, for large code blocks, you want to use one of the websites that dilch posted to more concisely post it in this chat, as to not clutter and clog up the channel
you got it

3 years on the same project, or 3 years in general?
3 on the same
nothing at all, just a "hold on" or a "reloading .."
it's very random, something it does some times it doesn't.. i have no idea what is happening
#💻┃unity-talk for non-code related issues, that don't fit in any other chan.
Close the project, delete the library folder, re-open
Yeah, #💻┃unity-talk
Hey guys. I create a scriptableobject to control my enemies most common stats etc... But now I have a doubt. to keep it simple, imagine i have 2 enemies. I have a spawn manager object and a script spawn manager. My question is. with 2 enemies I can have 2 prefabs.. but imagine I had 100 enemies, and all different from each other. Would i create 100 prefabs? or if not how can i create something that my spawnManager will be able to spawn all those 100 dif enemies? I cant have 100 prefabs right?
You can do that with 1 prefab, but you would need 100 SO's with the different stats. When spawning you'd assign the SO to the spawned enemy.
i'll try thanks
hm. So i create 1 prefab called enemy. Ok. I assign the enemySO script there. But ok. I still dont get how I will be able to use instantiate and choose 1 from the other. Lets say. Instantiate(_enemy, transform.position, Quaternion.identity);
how here I say which enemy from 1prefab? i am still confused 😂
[SeriliazeField] private MyEnemyComponent _enemy; // assign prefab
MyEnemyComponent enemy = Instantiate(_enemy, transform.position, Quaternion.identity);
enemy.data = scriptableObjectList[index];```
@teal viper do you know how to disable visuals "Running low background priority tasks" ?
It seems this is casuing the lag
and where is this list? this is my current EnemySO
What I gave you is obviously pseudo code, the list is where you need it to be.. probably the spawn manager..
so this list should be of which type?
Do your enemies have the same script?
You would then pass the EnemySO script as a parameter to your Enemy script and apply the values in there:
public void LoadEnemy(EnemySO enemyData)
{
this.Health = enemyData.health;
....
}```
It's a list of your scriptable objects.. so ..
damn, all of this is so hard 2 days trying to do something that is surely simple but its taking so long just to understand it 🤣 need to be resilient. well anyways thank you !!
does anyone know how to get your game to your iphone
hi! has anyone seen this error before? this occurs when I build. -macosx_version_min has been renamed to -macos_version_min
Hello, Is it possible to get an image sprite top right coordinates?
this is still a code channel
I think this relates to code (at least based on google it relates to Xcode issues) But if there is a better forum to post let me know please! Have been struggling with this for weeks
then show your code
before an answer is provided for this, could you explain the purpose of it?
https://xyproblem.info
So I have a small Image inside a Large Image, what I'm trying to achive is getting the small Image on the top left of the Large Image Sprite
just to confirm, are these Image components or Sprite Renderers?
Image
change their anchor point on the rect transform to the upper right
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/class-RectTransform.html
Well it is a lot of code. I think it has to do with somehow not being able to compile on mac but zero issues on pc. Have you seen this error before?
my guy, i said show your code because i know damn well the issue is not related to your code and i hoped you would be smart enough to realize that. unless of course you do somehow have code that is using that -macosx_version_min which i sincerely doubt
But this wont work, because The image sprite will contantly change. And they parent Image have PreserveAspect turned On
why wouldn't that work?
that sets the anchor to the upper right no matter what the size of the sprite assigned is
Because this will make the parent Image go to the top, not the center
set the pos and anchor of the small image rect tf
I only want that small logo on the topleft of the parent Image sprite, witout changing the parent locagion
you dont need to change any setting of rect tf in large image
change the child instead
ok you are on to something. Based on my research at apple developer forums it is an error that has to do with compiling but if I knew I wouldn't be asking lol. If you have a better thread to post on or any ideas with the error would appreciate it.
use id:browse to find a relevant channel to ask your question in. this isn't a code issue, which i pointed out yesterday before you'd even provided any details about the issue (other than it being a mac build issue)
Tried this byt still the Parent Images go into the top
why have you changed anything on the parent?
No, I don't
Here is the parent Image
This is the child Image
do you have any layout group and the small image is not child of large image?
What version of Visual Studios is everyone using?
A layout group?
Its a child
so @gaunt ice do you have any Idea?
have you tried my settings first to see if changing child rect tf still affect parent
I've Done it, done setting up the Anchor point
but when I changed the Image and the image has a different resolution.
the small Image will stuck on the air
Found Nothing, still the same reult
Hi guys, i need your help : I started Unity today, and i just want to move a capsule arround, i can move it with WASD but the problem is... Jump, a sort of jump work but i can go to infinity (not the goal) i just want a normal jump, jumping and then going back to ground: here's my code :
BTW: I'm really new and i know a lot about c# but +/- nothing about unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows.Speech;
public class PlayerMovement : MonoBehaviour
{
// Start is called before the first frame update
public float speed = 4;
public float jumpForce = 20;
RaycastHit _hit;
void Start()
{
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.position += Vector3.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.A))
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.S))
{
transform.position += Vector3.back * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.D))
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Space))
{
}
}
}
Thank's in advance
Anyone know how one would make a tree have physics (to fall on the ground) after it gets chopped by the player
Animate it, give it a rigidbody, or approximate it via code and move the transform yourself
add rigidbody to it
learn rigidbody or character controller.
rigidbody jump is easier, still need to learn how to make a grounded check to prevent ininite jumps
quick question: Is [SerializeField] a viable option or are there better options to get references?
stick with that as much as possible
ok thank you
You should read through this too https://unity.huh.how/programming/references
if runtime is needed, I'd do whatever DI unity allows (pass reference thru method)
nah its still slow
good to know
It just interates a list of components on the gameobject. If you only have a few, it's actually pretty fast. If it fails to find the component, it's pretty slow
Drag and drop serialized references also take time for the cpu to set up when runtime starts
ok i understand, but sometimes its the best option right?
Drag amd drop is usually the best option
serializefield?
Only for runtime is it useful really, and only then I stick to TryGetComponent so it atleast adds extra null check already
eg. like Collision methods , Triggers, Interactions with rays so on
I would make the cut tree a dynamic RB, then give it some torque/force
I add a RB but it does not take the model with it and phases through the ground
then you didn’t do it right
you would need to make a whole new tree object with a rigidbody
and if it phases through the ground, you didn’t set its collision properly
it would need a collider, model, etc and all that, you know
That is one way to allow it yeah
Personally, I use GetComponent in awake for most references, but it is sliiiightly slower (almost unnoticeable)
assuming the tree is a part of the terrain
there are others?
if the tree was already its own gameobject, then you’d need to alter it, and make a stump or something like that
Of course. Just making it public...
what do you mean?
If it's public, it is serialized
You only need the SerializeField attribute on private fields
but then there is no reference?
What?
I'm talking about drag and drop references
yes
i was too but i didnt consider using public
thats smart
xD
never thought about it
It is not. Use private whenever you can. Only use public when necessary
Hi, I have a class with a static variable that is initialized in the awake() method. Whenever i pause the runtime, change something in the code, and resume the runtime. Unity recompiles and the variable looses its value. Why is this happening?
You are PAUSING and changing code?
You should be stopping
unity doesnt even support hot reload
changing code at runtime will just give you missing script errors
Iirc, they got an asset that does it. Or maybe that was someone else
Don't try to change code while the game is running
iirc one a while ago but it was kinda messy / ugly
its been a while since i've heard about it tho
Thanks guys, makes sense. Honestly i was supprised, that unity handled "hot reloads" if thats the term, pretty well so far and got used to it, because it allowed me to see instant results to changes i was making. Just not doing that would certainly solve the issue 😏
runtime you can change fields in the inspector and affect runtime but those are variables serialized already.
I even changed conditions for if statements and removed code fragments and stuff like that which would take effect on a running game. I thought that to be a nice and convenient feature 😄
Why is
Debug.Log("Local Y: " + letterDescription.transform.localPosition.y);
printing different values from what i see in the inspector? it's printing -500 and the inspector value is
That's a rect transform. What you see there is the Rect Transform's AnchoredPosition
Ow
private void StartLetterScrolling(float desiredYPos, float duration)
{
scrollTween = letterDescription.rectTransform.DOMoveY(desiredYPos, duration).SetDelay(letterStartScrollDelay).OnComplete(() =>
{
scrolled = true;
OnScrolled?.Invoke();
});
}
Im using DOTween to move a text
on Y axis (just scrolling it up)
i thought that doing DoMoveY on rectTransform will figure this out for me
i see that there is DOAnchorPosY
i'll give it a try
yea use DOAnchorPosY for rect
works flawless now
thanks
just to confirm
there is no such thing as local anorched pos?
afaik anchored pos is kinda like the local pos for screen space
There is the fast scripts reload plugin on the asset store, which works but has its limitations like you cannot just add an entire new method or class
Anchored is local, by definition. The parent is what it's anchored to
thank you
Thanks for the info. Might check it out
Very beginner question here but how do I change the speed of my animation as the sample button does not seem to exist my my animator window?
Have a question, its better to have 10 custom scripts with the function update, or only one update function with all things inside ?
only for performance reason
1 update to manage more updates is the best way to go usually
Well, scripts have a small amount of overhead, so without knowing more, 1 update function would be faster.
Its completely negligible though for 10 scripts. Just pick what suits your problem the best.
I have all my other scripts hook onto this 1 gloabal Update usually
I wouldn't worry about it until you actually get performance issues
Hello is it possible to get an Image Source from an Image Component?
by image source what you mean
cause its just a sprite/texture ?
Getting this
that would be a sprite yes
var mysprite = myImgcomponent.sprite
is it possible to get the sprite corners coordinates?
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
congrats!
Is value = calculation(); if(value) more performant in any way than if(calculation())? I'm thinking in way of memory allocation/garbage collection
If you are reusing the value after the if / in the if block use the variable
otherwise it doesnt really matter
Nah, I would just assign the value for readability and debugging
Pretty sure they're identical when it comes to bytecode
I think the second one actually looks more like the first when compiled
Thats what i ment and kind of thought. Thanks 🙂
Nothing here is physics though, it's teleportation
what does this mean
It means Unity collaborate is not a thing anymore.
oh ok
You have to use PlasticSCM (the version control package)
Or use something third party like git and save yourself the headache.
using System.Collections.Generic;
using UnityEngine;
public class SimpleMovement : MonoBehaviour
{
public float movementSpeed = 5f;
public Rigidbody2D rb;
Vector2 movement;
//update is called once per frame
void Start()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * movementSpeed * Time.fixedDeltaTime);
}
// Update is called once per frame
void Update()
{
}
}
is thier a issue with the code
the character refuses ot move
Check the values in the inspector
Oh and you just set the movement once on start
set it repeatedly in update
As sidia said, don't use start. That runs ONCE in the objects lifetime. So for ONE frame right at the start, you capture input. Then you never do again
what do I need to do during or after Instantiate() to let me manipulate the object afterwards with more code?
write what instantiate outputs into a variable
how do i make it do it multple times?
oh, so like GameObject thing = Instantiate(stuff);
As they said, Update
Yeah. Or use a type.
Like MovementScript mover = Instantiate(prefab);
But the prefab has to be the same type as the variable
yes
im confused
Doesnt that only work if the prefab is referenceed as that type?
oh nvm you edited it
Update
The method you have at the bottom of your script?
Update runs every frame
Yeah. Just move everything from start to there
is there a way to do it so that the code runs before the Start() function on the new object runs? Or is that default behavior?
Oh wait, what?
My first thought was Awake, but maybe I am confused
Awake
Would be good to know what you are trying to do
I need to set a variable, 'size' of one of the new objects, and 'size' is used in a function in Start() to change the scaling
He wants code under instantiate to run before start
Then put it after Instantiate @green copper
so
Instantiate(thing)
thing.size = 2
[Thing's Start() uses the size to affect scaling before it fully exists]
Instantiate as the type, set the variable. It should be before start. The main thread will be occupied with that code
Start doesn't run until the start of the next frame
So this should function?
yes
Yeah. I would instantiate it as an asteroidConstructor instead of GameObject though
still doesnt want to move
Show code
show your new code
using System.Collections.Generic;
using UnityEngine;
public class SimpleMovement : MonoBehaviour
{
public float movementSpeed = 5f;
public Rigidbody2D rb;
Vector2 movement;
void Start()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
}
private void Update()
{
rb.MovePosition(rb.position + movement * movementSpeed * Time.fixedDeltaTime);
}
}
asteriodInfo.asteroidPrefab should be of type asteroidConstructor
Nope
Not what we said
Put the rb.MovePosition back in FixedUpdate
You're still only checking your input one time in start
Move the INPUT into Update
Start only runs once. How would you get input during the game when it is in start?
Why is that? asteroidConstructor is just the script where I apply a random rotation and velocity, and set the scale, of the prefab
How else are you going to start the race in second gear and get the 5.51
NICE reference
Because there is absolutely no reason to use a prefab of type GameObject when literally the first thing you do is get a component from it
Because then you skip the getcomponent. And scripts have a .gameObject property anyway
You rarely want GameObject references honestly
Just use that component as the reference and save the GetComponent call
I'm glad someone got it I thought it'd be too esoteric
so asteroidConstructor childRock1 = Instantiate(asteroidInfo.asteroidPrefab)?
or do I need to also put a getcomponent in the instantiate somewhere?
If astroidPrefab is of type asteroidConstructor, sure
No
You don't really want GameObject references very often. Just make the prefab the type you'll use most
forgive me what input
Essentially, if you ever need the prefab to do more than just exist you shouldn't be using GameObject
The lines with the word Input
Look at your code. Do you see the word "input" anywhere
Also consider that we are saying move the stuff out of start....
So it's the stuff in start
i changed start to update
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");```
seems to have worked
I think I get what you're saying, but I'm still unfamiliar with the syntax for instantiations and stuff.
asteroidPrefab is a prefab of a gameobject with a bunch of components attached, how can I instantiate the entire thing but only assign the script to a variable?
Yes, that is what we've been saying for the past half hour
Simple: Change the type of asteroidPrefab to the type you want, and that's what Instantiate returns
You might have to drag the object back in since it's technically a new field you've made by changing the type
but other than that, nothing changes
public asteroidConstructor asteroidPrefab;
Or
[SerializeField] private asteroidConstructor asteroidPrefab;
Drag the prefab with that script into the box
That broke the collision system with the projectiles for some reason....
Are you getting errors? You might have forgotten to assign something
no errors, the laser now just phases through the rock
collision was detected with OnTriggerEnter2D
and if collider.gameObject.tag == "asteroid"
Changing the type of a prefab would have no effect on that whatsoever