#💻┃code-beginner
1 messages · Page 668 of 1
yes
thats why I have the IDs on the scripts
but I think youre onto something with the prefab
so if you modify the template, and then instantiate it, they'll all have the same ID
ill try modifying the instantiated gameobject
since you did the modification before the instantiation
either move the ID generation to after the instantiation, or move the instantiation to before the ID change
hell you could have the Instantiate call in AddCorrespondingItem
i made a dict now instead of the list and added the id to the initialized object and it worked, thanks a lot
Question about ScriptableObjects. If I understand it right, SOs are used to define like...an overarching class, that other classes inherit common functions and fields from. So I might have a "MountableVehicleSO" script, and a "TrebuchetEmplacement" script that inherits from MountableVehicleSO. Is that right so far?
Inheritance is not really related/unique to SOs. You can have a similar inheritance chain with MonoBehaviours or just plain classes.
Got it, yeah after I wrote that I realized that's the case.
Ok I think my question instead then is....when do I use an SO, vs using MonoBehaviour?
MonoBehaviour for components on GameObjects. ScriptableObjects for storing arbitrary data and being able to reference it in the inspector.
When you say "being able to reference it in the inspector", what is it I need to do to make that data available in the inspector? Derive from that class in the class definition? Or simply instantiate an SO instance inside of another class?
Both. Derive from an SO and create an instance of your class. Specifically via create asset menu attribute.
So I have this code at the top of my SO:
{
public Player[] playersInVehicle; // This might be an AI instead. What effect would this have?
[SerializeField] public int numberOfSeats; // Maybe this can be the size of the array above?
public Transform dropOffPoint;
[SerializeField] public GameObject vehicleCamera;
public bool isPlayerOnBoard;
public bool isAIDriven;
private bool vehicleCanMove;
private bool vehicleCameraCanMove;```
Also all Mountable vehicles have some method logic for entering and exiting that they share:
```public void EnterVehicle(Player _player) {
bool playerHasEntered = false;
for (int i = 0; i < numberOfSeats && playerHasEntered != true; i++) {
if (playersInVehicle[i] == null) {
playersInVehicle[i] = _player;
playersInVehicle[i].transform.parent = dropOffPoint;
playersInVehicle[i].transform.localPosition = Vector3.zero;
vehicleCamera.SetActive(true);
playersInVehicle[i].GetComponent<GameInput>().OnChangeSelectedInventorySlotByKey += GameInput_OnChangeInventorySlotByKeyAction; // Start listening for key press (This might be changed to a vehicle control in the future)
isPlayerOnBoard = true;
playerHasEntered = true;
}
}
}```
(This is really early in development so a lot of this might change) What is it I need to add to make that possible?
Ugh, that formatting is horrid.
Check the ScriptableObject docs page. It has an example and explanation on how to create instances of it. That being said, I'd avoid putting runtime logic in it.
There's absolutely no need to for this to be an SO over MonoBehaviour imho.
Got it. That's the feeling I'm coming to, too.
SOs are best used for immutable data. In your case it's only the "number of seats" field.
Hello I have a question: Im making guns in unity, but I have an issue on understanding how to approach gun attatchments
my idea is this: have the gun's prefab contain all attatchments possible as children of the gameobject but they are disabled at first, on my gun script I have a float called "gunAttatchment" and the default value is 0 (no attatchments). In this scenario let's say I picked up a flashlight, it will set my gunAttatchment float from 0 to 1, and if its 1, then it'll enable the game object that is my flashlight. Is this a good approach or is there something I am missing?
edit: while rereading this, i have encountered a flaw in my own logic, now it would work if it were single attatchments, but I want to have multiple attatchments at the same time, and since each is a different value, what value would it even yield for it to have both objects enabled?
rather than using a float (and why would it even be a float rather than an int) just use a flags enum, assuming you need some way to save which attachments are active. otherwise you just need some method that can enable/disable specific ones
i meant integers yeah
of course there are probably dozens of other ways to handle it, i'd recommend just finding a tutorial that suits your needs
the reason why im kinda avoiding booleans is because I dont want like 10 lines for different attachments
that's what a bitfield solves
(what boxfriend was suggesting with "flags enum")
a bitfield is an integer that's treated like a bunch of booleans
and some attatchments will be overlapping in the same place, so laser sights cannot be active with flashlights
and in enum form they have nametags so you aren't just relying on arbitrary indices
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}```
like this?
something like that, yeah, but you'd generally do 1 << 0, 1 << 1, etc so you don't accidentally typo a value
if you have multiple attachment points, and each attachment point can have many different attachments (but not at the same time), wouldn't having a field for each attachment point be a separate field be a more direct model?
kinda like weapon attachment slots in.. idk, pubg, i guess
so logically, if my gun only has a flashlight, it returns value 1, if my gun only has a holosight it returns 2, but if it has a flashlight AND a holosight, it'll yield 3?
3 or whatever value I set it to
yeah
well no you can't set it to something else, it's bound by what the flashlight and holosight flags are
its bound by the flags that I set
so if the flag is set to 3, then the value that it must return is 3, correct?
ah i think you don't have the exact terminology down yet
yeah i dont, sorry 😭
a "flag" is each one of the bits in the integer - a flashlight flag, a holosight flag
you can have multiple flags together, but the combined result isn't called a flag
the combined result is a bitfield, which specifies all the flags at once - which are set and which aren't
so you would have a flashlight flag, a holosight flag - which would just mean each attachment individually
then you could have a flashlight+holosight bitfield, which specifies that they're both set
you could also have bitmasks, which are structurally the same as bitfields - just used in a different way
bitfields are for storing what's set and what's not, bitmasks are for operating on bitfields
so you might have a flashlight bitmask (equivalent to the flashlight flag itself), which you can use on some unknown bitfield to set, clear, or check the flashlight flag
so value 1 is the bitfield from the flashlight flag?
and the flashlight flag and holosight flag together form another bitfield
yeah
and I define what bitfield comes out of the flags
for some reason in my adhd induced thought I thought of having
flashlight flag = 1
holosight flag = 2
flashlight and holosight flag = 12 (😭)
if you use the | operator you can combine them so you can do something like this: Options options = Options.Option1 | Options.Option2; and then if you were to cast it to int it would be 3
i mean.. if you use strings/chars as flags.. but then it wouldn't be a bitfield lol
a bytefield/charfield
Flashlight and Holosight = Flashlight.Option1 | Holosight.Option2; like this?
and in defining the enum you can even include that as its own flag like
[Flags]
public enum Options
{
Option1 = 1 << 0,
Option2 = 1 << 1,
Option1And2 = Option1 | Option2,
Option3 = 1 << 2,
//etc
}
no, it'd be the enum name on the left of the ., so something like Attachments.Flashlight | Attachments.HoloSight
i was using the previous "Options" enum that was pasted earlier
ohhh
Can I get a Unity Cheat Sheet for application development, I'm new, starting out in Unity, but I'm a intermediate/advanced level C# programmer.
I would like to learn how to create proper scripts for PlayerMovement, GUI, etc.
Like in general C# we dont have Monobehavior
So, how do I learn these, the document doesn't teach it.
Also, like SeralizedFields, and other intialization things confuse me, and I want to get started, I've been trying to use and learn C# and Unity for a couple of weeks coming as a Java programmer.
see !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
There is no context, you just sent me to a site.
I'll look into it, thank you.
yes, that site has plenty of info
Which one specifically for my need?
It's just unity's version of programming I need.
programming essentials and maybe the junior programmer pathway, i guess?
feel free to skim over parts you're already comfortable with
public enum gunAttatchments
{
noAttatchments = 0,
// scope attatchments
attatchmentHolosight = 1 << 0,
attatchmentScope8x = 1 << 1,
// underbarrel attatchments
attatchmentFlashlight = 1 << 2,
attatchmentLaser = 1 << 3,
attatchmentKnife = 1 << 4,
// barrel attatchments
attatchmentSilencer = 1 << 5,
attatchmentMuzzleBoost = 1 << 6
}```
something like this?
where do I define these? im lost
you would generally have the enum and its members as PascalCase, and also it would act kinda like a namespace so you wouldn't need attachment in the enum member names - you would have GunAttachments.HoloSight, not GunAttachments.AttachmentHoloSight
ohhhhh
wherever it's relevant, really - so if you have a general gun script it could be there
or it could be its own file if you can't find anywhere specific for it
btw @oak mountain did you see this suggestion?
you mean define a slot first instead of the method im going with?
thats honestly a better ideia ngl
you ever played unturned? thats kinda where I got the idea
How do I check if a game object exists in the scene on play, without also returning True if it gets instantiated into the scene later?
On Start and OnAwake methods both fail to correctly test if the object existed when I hit play vs. the object later got instantiated in
XY problem my REAL problem is I have a room loader and I need to load rooms into the room loader that already exist in the scene that I placed myself, and I need a way to differentiate stuff I put in the scene vs stuff that gets loaded later
ideally I want a sollution that removes all possibility for human error - I COULD put a bool on the room that I flag myself manually if it existed at start or not, but that's way too likely to get saved into the prefab and @#%@^ everything up
not sure if this is optimal, but i do have an idea -
have some persistent singleton listen for sceneLoaded, and then set a state "first frame of scene" to true (or something like that)
then on Awake/Start of each object, check if that state is set
or on sceneLoaded, go through each existing object in the scene to mark them as such
Can't your room loader first just search the scene for such objects, and all the objects it finds from that search are known to be from the scene? Then, any objects it spawns itself are known to be loaded later?
the on-scene-start singleton that is watching the application method seems to have worked 
If I have a complex scene, wouldnt doing an asset search of every gameobject be slow?
Would there be some way to only look for specific game objects?
yes it's kinda slow but on scene startup isn't that ok?
FindObjectsOfType is the simplest approach
when i set the rotation of my object to a degree value between 180 and -180 it works fine, but when i get the value elsewhere (ie. transform.rotation.x) it turns into a number between 1 and -1. is this a radians thing or am i just stupid?
You're looking at a Quaternion
Never ever try to look at the individual components of it

i just need to read this whole website apparently
alr thanks you guys
Any particular reason the icon of the script shows updated there but not in the folder?
Is that a thing that just happens sometimes?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
pay particular attention to the last two lines
okok, thx
Omg same! I’m like good with Java and C#, but like all the new unity specific functions make me so confused. Would be great if someone just made a massive cheat sheet of just unity specific functions instead of like mass searching through the unity website
a massive cheat sheet of just unity specific functions
that's called the documentation
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GoBack : MonoBehaviour
{
int sceneIndex;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
sceneIndex = SceneManager.GetActiveScene().buildIndex;
if (!PlayerPrefs.HasKey(sceneIndex.ToString()))
{
PlayerPrefs.SetInt(sceneIndex.ToString(), sceneIndex);
Debug.Log("worked");
}
int ScenetoOpen = PlayerPrefs.GetInt(sceneIndex.ToString());
Debug.Log("Scene is opened succesfully, hip hip hurray,we're extra dextra crazay.");
}
public void Backward()
{
SceneManager.LoadScene(sceneIndex - 1);
Debug.Log("Hip hip hurray");
}
}
and you said that no logs are printing at all?
is there an instance of this script in your scene?
yes its inside a button inside a panel
@untold elk i just realized, your logs in the console were hidden 🤦♂️ #💻┃unity-talk message
you are getting logs, but you cant see them
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
public void Backward()
{
SceneManager.LoadScene(sceneIndex - 1);
Debug.Log("Hip hip hurray");
}
\
``` does not work its the one that isnt printed
Then Backward() isn't being called.
have you made your logs unhidden, first?
yeah i got that to work
so what is supposed to be calling the Backward function?
when i click my button named BackWard if that is important at all
How do you actually tell that button to run this function?
feel like there would be a mousebuttononeclick function with the button to indicate it is hit but objectively it hasnt reached me in code on how to fix that or write sum like that,otherwise my buttons in previous scenes use public void and run properly so it confused me
so... you arent doing anything to call it at the moment?
then obviously its not gonna run
this is very easy to setup, though. a ton of basic tutorials on UI will teach you how to set this up
ok what do u recommend to search for calling buttons then on unity
so i can not suffer incorrect tut
yeah just "unity UI buttons tutorial" should work
ok tysm i will come bac w a manifested success hoping lol
tysm!
btw am i calling the back() or the sceneIndex
sceneIndex is an int. how are you gonna call an int?
oop tru
If you're using the UnityEvent on a button, you'll only be able to call functions or properties
I tried setting a serializefield for both button and a function to define it but it is unsuccesful
[SerializeField] private string theexamplesisaidbefore = "GamePlay";
``` made sense u couldnt put backward but now i am curious
your terminology is entirely messed up. you are supposed to be referencing the Backward function on your button
what is this supposed to mean?
according to the random tut : ( its supposed to create a string just for enabling the scene w whatever name or level it was but istg ive not seen unity code using serializefield but this was 3yo tutorial so ill give it slack and me braincell growth
"create a string"???
how familiar are you with programming and c# in general?
i literally started w tutorials like 1.5 days ago
you should really familiarize yourself with the basics more before continuing. i would recommend spending at least a couple weeks learning the basics and practicing before continuing
ok assumed i could do a tutorial by tutorial basis definently tells how not easy the csharp is for beginners but i do need this for a school proj so am curious if u would know what id exactly have to add (its not a grade where the code is important alas its a history project)
also is code 🐒🙉 monkey a good place to start he has a full course and seems trusted in the unity community
c# is actually one of the easiest programming languages to learn for beginners.
yes i love Code Monkey. i watch all of his vids and read all of his newsletters as soon as they come out lol
even if i explained exactly what you need to do, you wouldnt understand most of it. i cannot explain something to you in spanish if you cant speak spanish
yeah makes sense lmao
is his full course tutorial for beginners from beginner/intermediate made exactly 2 years ago best or would any of the code be broken in unity 6x now
no it should be fine, a lot hasnt changed
in a multiplayer context, players character using the same material, if i did: skinmesh.sharedmaterial = newmat, will this also change the other players? like how this player see the others ?
also in normal context i know that: var mat = skinmesh.material create a copy, assign to that skinmesh and that var mat so i will have to keep this mat reference at all time to call Destroy(mat) and cant do Destroy(skinmesh.material) right? or will it just auto get gc when no longer referenced (var mat is lost or skinmesh is destroyed)?
im getting this error on code that i dont think should be having an error
Assets\Ancient Language\PlayerMovement.cs(88,62): error CS1061: 'Rigidbody' does not contain a definition for 'linearVelocity' and no accessible extension method 'linearVelocity' accepting a first argument of type 'Rigidbody' could be found (are you missing a using directive or an assembly reference?)
anyone know what's up here?
In a multiplayer context nothing is ever directly synced like that. If a player changes their material every client needs to do that same thing
Eg. If it’s four people playing thats not four people playing in the same connected game thats four different games that are ideally identically setup
- Is that an error in unity console?
- What unity version are you using?
- You should configure your !ide
!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
• :question: Other/None
if a dictionary is null, does that mean it doesnt exist, or that its empty?
the former
err okay, so i have a class that stores info about player stats and stores them with a static call of that class, and im trying to add a dictionary to it but:
void SomeFunction()
{
if (adventures == null)
{
print("No adventures?");
}
else
{
print(adventures);
}
}
it says its null and i cant add to it from other scripts, it acts like it doesnt even exist
2022.2.0f1
it is
{
for (int i = 0; i < adventuresList.Count; i++)
{
print(adventuresList[i]);
print(GameDataManager.Instance.adventures);
GameDataManager.Instance.adventures.Add(adventuresList[i], false); // line 23, the problem in this case
GameDataManager.Instance.advProgress.Add(adventuresList[i], 0); // presumably also an issue
}
}```
show where you assign Instance.
thats not assignment
its static so shouldnt matter right ??
im able to call other information from GameDataManager.Instance without issue
like what? where ? and when
Sure, if you're only accessing other static methods and variables from GameDataManager, then those will work, but there's no instance being assigned, so non-statics will fail
It looks like you want it to be a singleton, which means you need to assign an instance to that variable at Awake()
i solved it, it was an issue with my save/load and i had to use ?? srry
thanks though
Hello, I'm completely new to Unity, I've been following a tutorial and I'm now getting to coding stuff, I generated a script, but when I try double clicking to open Visual Studio, there's nothing there
you could try double clicking it again with VS already open, or alternatively right-click the file in unity and select "Show in Explorer", then drag the file directly to VS?
could be that the !ide isn't configured?
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
• :question: Other/None
This seems to work, thank you!
how could that possibly be the issue?
I mean I've seen that as a solution here and there, and it doesn't hurt to make sure that it is configured
configuring your ide wouldnt magically make it so that text appears in your ide
I'd still like to fix it so I can simply double click on it tho
i mean, configuring your ide is essentially making it compatible with unity
if it's not compatible with unity by default, then it's not a stretch to think that it's a possible issue
that's not the case at all...
feel free to correct me
also are you opening scripts via file explorer?
unity has the Project tab where you can open the scripts from directly
all IDE's that are compatible with unity at all are compatible with unity by default. configuring your IDE makes it so that respective csproj and sln files are generated so that your IDE can properly talk with Unity. Though, this doesnt necessarily mean that it wont work with unity at all without configuration
Dragging the script into VisualStudio seemed to work, The tutorial is telling me to double* click, which does open up VisualStudio, but no code appears
Check the view tab in VS and make sure the necessaries are visible
Solution explorer etc
oh ok - i mean the more i know the better
I do not know what this means
Edited
yea but were you double clicking from the file explorer, or from the unity editor?
The Unity Editor
It opens to visual studio, but no code shows up
does the same happen if you open it from file explorer?
not dragging, just Open With -> Visual studio
i mean, did no code show up when you did it via file explorer?
try creating a new default script. maybe the meta data for that one is corrupted
oh my bad, its not the same, the code does show up if I open it using file explorer
ok then, in unity, go to
edit > preferences > external tools, and check that Visual Studio is the IDE
creating a new one has the same effect
nice ok, you can try to "Regenerate project files" too, could help here
Still no change ):
check if you have the Visual Studio Editor package installed in the Package Manager
Where do I find the package manager?
should be under Window in unity
really strange, and did you check what Dalphat suggested? They edited their message, but check View tab in VS and see if everything is there like Solution explorer
Did you go through the manual installation instructions of !ide? It seems like you might be missing some C# workloads.
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
• :question: Other/None
that's what i was thinking, but apparently configuring ide will not magically help here
I cant get a screenshot of it, but idk what Im looking for, Solution explorer is there
hello everyone i recently started using unity and downloaded some asset from the store ( VFX ) but they got the default pink texture and i don't know how to fix it
Unless I'm missing something, they never confirmed that they configured it properly
i think it is worth it to check that the IDE is configured
since you'll be needing that to get any further help here anyway, if you have issues with code for an example
Sounds like the asset is for a different render pipeline.
It's installed and up to date, I dont know what to check for besides that
might be but can't you have different render pipeline at once ?
did you check everything in the bot message's link for visual studio?
You can have several in the project, but can only have 1 active at the same time.
goddamnit
may i ask how to change said pipeline ?
I mean, how exactly did you expect to use several at the same time? Render the frame several times and then combine the results or something like that?😅
how do i make it so that a ui element DOESNT move with the camera?
put the UI in world space instead of canvas space
when you put it like that it stupid yes, but dunno maybe tech magic stuff
There's a window for converting the whole project somewhere.
To do it manually, just assign the render pipeline asset in graphics/quality settings. See the manual for more details:
https://docs.unity3d.com/6000.1/Documentation/Manual/render-pipelines.html
well to be more specific - set the Canvas to world space
thanks
oh also, for something like a scriptableobject, how can i make it so that certain information below it in the inspector only appears when an enumeration value is a certain value?
so that for example i can have items fulfilling different purposes (food needs a value for how much hunger it replenishes, but a furniture or clothing item doesnt need that)
- Have different scriptable objects for different item types.
- Have a custom editor/inspector that would only expose the fields that you need.
I'd say 1 is the recommended approach.
I was doing the Unity Hub way, redoing it manually fixed it, I can now double click to open it, Thank you so much! You guys were a big help
ahh maybe 1 can work, but im having trouble contextualizing it -- a generalized item SO with stuff that every item would have (eg name, icon etc) and then somehow every item can have a secondary "object" reference with different SOs to give them separate info? or am i going about it wrong?
That's what inheritance is for. You can have a base BaseItem SO. Then extend it with ConsumableItem and other types of items if they need their own specific parameters.
Another approach is to use composition
oh inheritance, i need to read about these things then. thanks for giving me pointers about how to learn this
can someone help me out w this
I think it's called 'velocity' before Unity 6. What Unity do you use?
2022
Yes, that's it then...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collision_Off : MonoBehaviour
{
public GameObject Platform2; // Assign platform_2 in the Inspector
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
BoxCollider box = Platform2.GetComponent<BoxCollider>();
if (box != null)
{
box.enabled = false;
}
}
}
}
can someone help me debug. if u want images of my project i have those.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
it's 2d but in 3d workspace and i'm only really using 3d variables
what exactly is the problem?
for some reason when i touch the particle thingy the box collider for platform_2 is still enabled. want pics or perhaps a vid?
or try to explain
may i ask why you are not using sprites because i am guessing you got this wrong
Theres basically a couple platforms, the player controller works and the goal is to reach the particle thingy, which will disable the platforms and give you the wall jump ability. Currently i'm working on disabling the platforms.
The code is meant to do that but it doesn't work.
I'm just using 3d objects. It's only 2d in the sense that the player can't move in the z axis
just use debug.log inside the oncollisionenter and see if the collision is even taking place
narrow down the issue
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
aight thanks
what is the equivalent of rigidbody.linearDamping for unity 2022
You mean Variable ?
i think its a float value, i didn't fully understand what you said though.
ty
lol thanks anyway
if the gameObject is inactive in the scene to which the above Script is applied. and i am running this Function in another script with different gameObject which is active. Will the function still work ?
Sup. I have a question. Why does
'''cs
Material material2 = Platform2.GetComponent<Renderer>().material;
if (material2 != null)
{
material2.color = Color.clear;
}
'''
make the block 'platform2' look black?
... why didn't the code tag work?
You want to make it Transparent ? Color.clear makes it a black transparent color . RGB(0,0,0)
you can probably set the alpha of the color to 0
maybe set the color to white and alpha to 0
how do i do that?
aight i'll try it out
also its cause you used an apostrophe (') instead of the actual character (`) they look very similar
what does it say
CS1612: Cannot modify the return value of 'Material.Color' because it is not a variable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collision_Off : MonoBehaviour
{
public GameObject Platform1; // Assign platform_1 in the Inspector
public GameObject Platform2; // Assign platform_2 in the Inspector
public GameObject Player; // Assign the player in the Inspector
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject == Player)
{
BoxCollider box2 = Platform2.GetComponent<BoxCollider>();
if (box2 != null)
{
box2.enabled = false;
}
Material material2 = Platform2.GetComponent<Renderer>().material;
if (material2 != null)
{
material2.color.a = 0; // Set alpha to 0 for transparency
}
BoxCollider box1 = Platform1.GetComponent<BoxCollider>();
if (box1 != null)
{
box1.enabled = false;
}
}
}
}
There is a Surface Type, which you can set it to transparent, I have no idea how to access it with a script though
Or either make another gameObject with surface type set to transparent and instantiate it in its place after destroying previous one.
hi again, i have this cool shader pack but it works only in the default render pipeline how do i change that simply ?
If you want it to be completely invisible, just disable the whole renderer instead of changing the material
is there any other web site that can provide shader and stuff for unity ?
The asset store
other than the asset store
Otherwise, material.color is a field and not a variable thus the error. Its declaration in the Material class is : public Color color { get; set; }
That means that you can get it however you like but you can only set it by assigning it a new value.
In short: You can't modify a field with a value type without replacing it entirely.
Usually you just do this :
Color tempColor = material.color; // Extract current color (optional, you can just create one yourself)
tempColor.a = 0; // Transparency to 0 or whatever you'd like to do
material.color = tempColor; // Reassign back
But as Osmal said, it might be more efficient and/or more suitable to disable the renderer completely if you're only interested in a toggle mechanism for show/hide. Since the draw call won't ever happen when disabled, this can greatly increase performance, especially if you got a lot of objects that implements this mechanic.
why other than the asset store?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
itchio, github, reddit
How do I increase two different values at the same time?
it has to be done within the same time
there should be a way
I've seen games doing that
You're confusing things that happen in the same frame with things that the computer is processing at the same time
Unity is single threaded, nothing happens at the same time. The fact you think you find this necessary is a beginner red flag.
its like I have a image bar & a charge float variable,
charge is set 3f so when I press a button it'll drop the value to 2
but bar is split into 3 equal halves which drops by 30% when i press a button
so you have to fill both values together as both of them will fill up by time'
im giving a general explanation of it
The computer does millions of little things every frame, one by one, before the frame is drawn. As a user you don't see anything except what it draws at the end of the frame, which is the final state of all those millions of little things. You can't see the millions of little things changing because it only draws the final state of the frame when it's done.
doesn't matter
I just need the same speed to fill both values
I cant bcuz the image fill amount is restricted between 0-1
I don't see why that means you can't
how would setting both at the same time solve that
That has nothing to do with you wanting to do both?
Ig I'll dig more
I follow UI toolkit guide for making labels upon objects. I don't get why do my label in screen corner instead of being upon object
If you're trying to fill a bar based on progress, then you divide the current value by the max value. Use that in your fillAmount
I can divide the bar but
In general, the dash bar is just one image divided into 3 parts. But I also have the charge value which holds how many times you can dash. Charge holds 3 while the bar doesnt. So basically I have to write a function where I can fill the bar to 1 as the charge increases to 3. And ofc they both increase their values by time.
Right. This doesn't seem at all like the issue you were describing before about things happening at the same time.
In the future, just explain your goal rather than what you think you need to do.
That's literally just a/b, it's not a complicated function
The increasing of the values part is totally unrelated to the drawing it in the filled image part
yeah I figured it out
well , it's my first project and i don't want to spend any money on it and the free asset become rapidly limiting
The other place people use is itch.io like Batby mentioned
Though if the free assets are too limiting for your first project, then you might want to scale it down a bit
Hello I have a question about the roll a ball tutorial (https://learn.unity.com/course/roll-a-ball/tutorial/moving-the-player?version=6#66f2d394edbc2a011dded4a3) OnMove gives us a Vector2, which we are using to make a Vector3, however, we're using the y coordinates to use a z coordinates and I don't understand why, I never used playerInput component before and I'm confused 🙏
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Input is naturally a Vector2 because your keyboard arrows, or analogue stick on a gamepad is on 2 dimensions.
X axis is left and right, and Y axis is up and down.
In a 3D controller, you want the up and down (y axis) of the input to move the character on the z-axis which is forward and back.
So that's why you use the Y axis from the input as the value for the Z axis of the character.
oh that makes sense! thank you
I was wondering if I could have some help, I'm trying to set up a button that destroys the previous instantiated object and then instantiates a new one. The issue is I can't destroy something that doesn't yet exist the first time the script is running I think?
using UnityEngine.UI;
using Unity.VisualScripting;
using TMPro;
public class Random : MonoBehaviour
{
private Button button;
public float number = 0f;
public TextMeshProUGUI buttonText;
public GameObject[] balls;
private GameObject presentBall = null;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
button = GetComponent<Button>();
button.onClick.AddListener(RandomBall);
}
// Update is called once per frame
void Update()
{
}
private void RandomNumber()
{
Debug.Log("Button Has been Clicked");
number = UnityEngine.Random.Range(1, 20);
buttonText.text = "" + number;
}
private void RandomBall()
{
Destroy(presentBall, 2);
int colourBall = UnityEngine.Random.Range(1, balls.Length);
Vector3 location = new Vector3(10, 0, 0);
GameObject presentBall = (GameObject)Instantiate(balls[colourBall], location, Quaternion.Euler(0, 0, 0)); // New Gameobject Called presentBall which = the instantiate summon
}
}```
Then just don't destroy it
Check if the object is null
If I don't destroy it then I'd have a button that generates infinite coloured balls which all over lap, I tried to declare the ball as null when the script starts but it's still throwing a hissy fit about it not being declared before use.
I mean "don't destroy it if it doesn't exist"
The "infinite balls" is a different problem. The last line makes a new variable, it doesn't change the presentBall field. Remove the GameObject part from there
if statements mf, do you know it?
And that solved it! Thank you so much :)
Yes but I can't see how one would of helped 🤷♂️
It would help prevent trying to desroy a null reference.
ok how do i "install" an asset bundle that i got from somewhere else than the asset store ?
Depends on what format it is in? Assuming it's just normal assets that unity can import, just drag and drop them in the editor.
ok but if something else ( i don't have any special exemple) ?
Those usually have special instructions
Guys i made this code but i really have feeling that its messy and i could do better. Im trying to make it better but i cant. Can yall help me to make it better?
private void Update()
{
CardController();
UpdateUI();
slimeRequirement = baseSlimeReq;
IncreaseSlimeReq();
}
public void IncreaseSlimeReq()
{
foreach (Transform child in GameObject.Find("Upgrades").transform)
{
if (child.gameObject.GetComponent<UpgradeBase>().GetType() == GetType())
{
slimeRequirement += slimeRequirement / 3;
slimeRequirement -= slimeRequirement % 5;
}
}
}
same, try apply a design pattern
if you have completed the feature, try go back to it whole and refactor it all to a pattern
are u telling me?
yea
thats a long story, try searching it fr
im not expert also, trying to refactor my garbage code atm also
well ok ty
"design pattern" isn't exactly a magic thing to make code better
there are situations where you don't need them
Cache your references for one, you are performing a search for multiple objects each frame over entire scene hierarchy.
Find generally should not be done in Update
either cache that list of children, or preferably use static references
but i need to check it everytime
the list of upgrades is going to change?
If that's the case you should keep track of the list of upgrades somewhere and access that.
yes
yeah you shouldn't treat the hierarchy as storing data, really
store stuff yourself and then sync that to the hierarchy
that way you have direct access and it makes it easier to access stuff
if that big change isn't viable, at least use a serialized reference for the Upgrades game object, so you can avoid that magic string
then i need to control a list everytime
you kinda already are - the upgrade gameobject's children
if that big change isn't viable, at least use a serialized reference for the Upgrades game object, so you can avoid that magic string
what did u mean, i didnt get it
which part exactly, or the whole thing?
wdym serialized reference
can u give me a example?
a serialized reference is basically a reference you set in the inspector
"if that big change isn't viable, at least use a serialized reference for the Upgrades game object, so you can avoid that magic string " this part
...so the whole thing
not here "yeah you shouldn't treat the hierarchy as storing data, really
store stuff yourself and then sync that to the hierarchy
that way you have direct access and it makes it easier to access stuff"
yeah that's still a big chunk you're asking me to rephrase lol
you gotta be more specific
can u give me a example pls?
public Transform upgrades;
you likely already have plenty of these
it's one of the first things you learn to do in unity scripting
wdym so you can avoid that magic string
ok so.. dude do you know what "avoid" means
yeah, that makes my job a whole lot easier
in this case i need to control the childs every time
so i cant make a variable for the children
cuz then i cant get the children which added new
a magic string (or magic number, etc) is a specific hard-coded string that you use as a data point - like the "Upgrades" string here
they're generally not a good idea since they can easily be typo-ed, they don't have a clear link to anything else, and they can easily get out of sync if you decide to rename one
you can still make a variable for the container gameobject though
yeah i made it now
if i shouldnt get the game object by typing gameobject.find, then how?
with a serialized reference, which i explained here
ohh ok i got it
🙂
but because its a upgradeBASE idk if i can add upgrades gameobject even tho this script isnt in hierarchy
that has nothing to do with it
or i have to add upgrades gameobject every single time when i make a new upgrade card
UpgradeBase = upgradecardbase
that tells me nothing
wait
1min
if i add here the upgrades game object do i need to add the upgrades gameobject for every single inheritances from upgradeBase's (upgradebases classes i mean)
is this in UpgradeBase?
yes
this kind of spaghetti is why i recommended this
i cant put it cuz upgradebase is in project
yeah you aren't supposed to
that's a default reference
set it on an instance of the script, not the script itself
then i need to set it every time when i make a new child which inheritances from UpgradeBase right?
what do you mean by "set"?
wouldnt it be better by taking the gameobject by just using GameObjectFind
lemme show u
you wouldn't set the variable when you create a subclass
you'd set the variable when you instantiate it
if you do it on Start, sure - the main point is that you shouldn't do it in Update
oh ok i made it in start
(but generally, as i mentioned before - direct references are better than Find)
but i wanted so say
this, mainly
that the tactic how i coded looks messy here like at the start of the update func i have to set the "slimeRequirement = baseSlimeReq;"
it looks like shit
i think thats a bad way to do this
ok... and why do you need to do that every frame?
private void Update()
{
CardController();
UpdateUI();
slimeRequirement = baseSlimeReq;
IncreaseSlimeReq();
}
public void IncreaseSlimeReq()
{
foreach (Transform child in GameObject.Find("Upgrades").transform)
{
if (child.gameObject.GetComponent<UpgradeBase>().GetType() == GetType())
{
slimeRequirement += slimeRequirement / 3;
slimeRequirement -= slimeRequirement % 5;
}
}
}
i need to check it
if i buy the same card i increase the slimeReq
yeah you shouldn't do the same calculation every frame
just keep that same variable and only update it when something changes - when you buy one of those cards
i think you should step back from your code and take a bit to think about how everything links together first
that way you can figure out what kind of relationships and calculations make sense, and then implement that
yeah im trying it rn
ty for the help
if i write it so then it increases the card which i bought not the classes variable
public void IncreaseSlimeReq()
{
slimeRequirement += slimeRequirement / 3;
slimeRequirement -= slimeRequirement % 5;
}
public void BuyCard()
{
if (GameManager.instance.slime >= slimeRequirement && GameManager.instance.level >= levelRequirement)
{
GameManager.instance.AddSlime(-slimeRequirement);
IncreaseSlimeReq();
isBought = true;
drawCount += 1;
}
}
how can i do it that the classes slimereq increases?
...like that?
but then it increases the cards slimeReq not the classes slimeReq
is slimeRequirement static or something? if not, there is no "class' slimereq", it belongs to each instance of the class
public abstract class UpgradeBase : MonoBehaviour
{
public abstract int levelRequirement { get; }
public abstract int slimeRequirement { get; set; }
so i cant make it static too
cuz its abstract
if i would able to do it static the problem would gone
you could trigger some event or loop to call some method to call IncreaseSlimeReq on each instance
like how
could u give me a example?
but how can i learn
i cant learn it if i cant see it
its too complicated to search that cuz my games arch is different like u said
Hello, I'm on windows using unity 6.1
I created a prefab folder and dragged a sphere into that folder. It's showing as a prefab now, when I drag the prefab from the folder into the hierarchy the new one is showing up wherever the camera is looking instead of where the original one is. Is there anyway to change that to make it appear at the original location?
Sounds like you parented it to the camera by mistake, show us a screenshot of the hierarchy
So in-game when you look around, the sphere is always dead center?
i think they mean when they place it manually in the scene it ends up where the scene camera is looking which is expected behavior and not really a code issue
prefabs don't exactly have a position, when you create one it'll be wherever you're looking
Ah, that makes more sense
you could reset the transform to get it to be at 0,0,0 but that also sets rotation and scale (and might not be what you're going for)
there is an option to set its position to the origin instead of where the camera is looking, i just don't quite remember where that setting is
looks like it should be in Preferences > Scene View
Thats what I mean. I was running through a course on udemy and he said it should have the same coordinates as when you first created the prefab. If its not broken then that's fine, but now I'm more so just curious on how to get it to go to that original location when I drag it into the hierarchy
trajectoryBodies[i].gameObject.layer = ignoreLayer;
Collider[] collider = Physics.OverlapSphere(trajectoryBodies[i].rigidbody.position, trajectoryBodies[i].radius, simluationLayer, QueryTriggerInteraction.UseGlobal);
trajectoryBodies[i].gameObject.layer = simluationLayer;
any ideas why its telling me my object has two layers after this layer switch?
both ignoreLayer and simulationLayer are set in the editor.
fwiw this also doesnt work:
Collider[] collider = Physics.OverlapSphere(trajectoryBodies[i].rigidbody.position, trajectoryBodies[i].radius, simluationLayer, QueryTriggerInteraction.UseGlobal);
trajectoryBodies[i].gameObject.layer = 1 << 10;```
what's telling you it has two layers?
If instantiated by code at runtime it will keep this position (if you do not specify a new position). You should be able to revert the position on the instance after creation however.
hey guys im breaking my brain with this, plz help
int[] buttons = new int[] {1};
for (int i = 0; 0 < buttons.Length; i++) // this runs twice... for some reason
{
print(i);
// a bunch more code
}
for (int r = 0; 0 < buttons.Length-1; r++) // but this runs zero times!
{
print(r);
// a bunch more code
}
(i condensed the code a bunch so sorry if some of it doesnt seem to make sense)
i just want the loop to run through once, just like how theres only one value in buttons
also @ember tangle
This is the standard integer value which identifies the layer, not the LayerMask.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/GameObject-layer.html
0 < buttons.Length is always gonna be true, 0 < buttons.Length - 1 is always gonna be false
you sure that first one runs 2 times and not forever?
it adds to i at the end of the loop right? i mean i get an error because of my other code so it could very well run forever if that isnt the case
it adds to
iat the end of the loop right?
what about it? you aren't using it in the condition
read your condition again
also - do you use i as a number anywhere? if not, you could use a foreach instead to avoid this kind of mistake
oh man im silly youre right i used 0 instead, thank you very much
The error "A game object can only be in one layer. The layer needs to be in the range [0…31]"
ok it's not actually telling you that it's in multiple layers
see above ^
yes, and i get the same error with bitwise operation to set the integer
Im using layermasks [SerializeField] private LayerMask simluationLayer; [SerializeField] private LayerMask ignoreLayer;
set correctly in the editor
- trajectoryBodies[i].gameObject.layer = 1 << 2;
+ trajectoryBodies[i].gameObject.layer = 2;
Collider[] collider = Physics.OverlapSphere(trajectoryBodies[i].rigidbody.position, trajectoryBodies[i].radius, simluationLayer, QueryTriggerInteraction.UseGlobal);
- trajectoryBodies[i].gameObject.layer = 1 << 10;
+ trajectoryBodies[i].gameObject.layer = 10;
```this would work - but of course you wouldn't want that for DX
yeah, but GameObject.layer isn't
what is DX
developer experience - you'd want to be able to set it in the inspector with names, like you would a layermask, yeah?
the problem being you can't use a layermask here
I understand now
since GameObject.layer is just an int and not some wrapper, i don't think there's a utility to get a single flag out of a layermask in this way
so i guess you'd just have to loop to find the first flag set if you want the input to be a layermask
LayerMask.value doesnt work either which is annoying
yeah because LayerMask.value is the int value of the mask, not an id of one of its flags
online solutions also point to either looping or log2
okay I dont understand. Layer is an int, LayerMask.value is the int of the layer, but layer = layermask.value does not work?
because layer is a layer index not a layermask
just because two things are int doesn't mean they represent the same thing
just like Vector3 can represent a color, a position, a rotation, euler rotations. Just because they're the same data type doesn't mean they're interchangeable
so layer 10 = 10, layermask 1 << 10 does not equal ten right?
a layermask of layer 10 is 1024
the important things with masks is to look at it in binary
okay so its like the bits of int eg 0000000001[etc]
that's like, the 11th
whatever man 😛
I thought layer one was 1000 etc, layer 2 was 0100 etc
layer 1 is 0000001
layer 2 is 0000010
and so on - for a MASK
i mean you have the right idea
(they start at 0)
alright I think I get it
what type is invs
byte
You have to cast the byte to float
then cast to byte
Depends what you're trying to do
you probably want to go to int first then byte cus float to byte wont end well
It really depends what you're trying to do here
Time.deltaTime cast to an int is always going to be zero
I can't imagine that's what you want
so like this
Wait and you're just multiplying deltaTime by 1
What's the point of that
That does nothing
i want to animate a fading off and on effect
You can't store a float in a byte
i just want to test it
Are you trying to get a 0-255 value?
yes, i want it to be fading effect
Test what
how delta time works
color is floats (0-1), color32 is byte (0-255)
it's the number of seconds elapsed since the previous ferame
it's normally a very small number like 0.015
because frames are fast
yeah i figured that, but color doesnt accept the visibility, nor anything above 1
you need a value that you increase or decrease over time
wdym the "visibility" like alpha?
a float
yes
like this:
float alpha = 1;
void Update() {
alpha -= Time.deltaTime;
myColor = new Color(1, 1, 1, alpha);
}```
something along those lines
Color uses 0-1
but you declared a Color which is not byte value 0-255 but float 0-1
no i declared it to be color32 above
your alpha value needs to be a float
there isnt such thing as new Color32
then you still need a float but now you need to multiply it by 255
🍿
when i try to put a float in the color32, i get an error saying, it only accepts byte values
float alpha = 1;
void Update() {
alpha -= Time.deltaTime;
myColor = new Color32(255, 255, 255, (int)(alpha * 255));
}```
yeah because using Color32 is stupid here
oh so you want me to change it to color
yes
ok is there a way to change
with your keyboard
those values into the color format
public Color myColor;
myColor = new Color(209f/255f, 112f/255f, 108f/255f);
or better yet
set it up in the inspector
some very simple maths lets us go from 0-255 to 0-1
literally just do public Color myColor; and set it up in the inspector
ooo
Yea, setup the colour that way then animate it in code as you desire
should i use time.delta time right
if you need the value to change consistently over a series of frames, yes
You can also create a value for the target color/fade you want and use this btw
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Color.Lerp.html
This is so weird, I'm trying to instantiate a fence but for some reason my spawnmanager is instantiating the wrong obstacle.
- My SpawnManager gameobject is assigned the right prefab in the SpawnManager Script (Obstacle_White_Fence)
- When I start the scene, a fence named Prop_Barrier03 is spawned? Anyone know why the right prefab fence isn't spawning?
show any related code
not a video of it
code is in video but script is:
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
[SerializeField] private GameObject[] obstaclePrefabs;
private Vector3 spawnPosition = new Vector3(25, 0, 0);
float startDelay = 2.0f;
float repeatRate = 2.0f;
private PlayerController playerControllerScript;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>();
}
// Update is called once per frame
void Update()
{
}
void SpawnObstacle()
{
if (playerControllerScript.gameOver == false)
{
int obstacleIndex = Random.Range(0, obstaclePrefabs.Length);
Instantiate(obstaclePrefabs[obstacleIndex], spawnPosition, obstaclePrefabs[obstacleIndex].transform.rotation);
}
}
}
okay where is the object spawned in the video ? it should say (clone) usually
It looks like it's spawning at the right location, but what might be causing the issues is the prop_Barrier03 doesn't ahve rigidbody/ box collider. When I click on the instantiated obstacle, Prop_Barrier03 pops up
I mean it is spawning Obstacle_White_Fence which what you put as the prefab to spawn, so the code is clearly working correctly. You need to check what exactly the orriginal prefab has
maybe i should put the rigidbody and boxcollider on the prop...
but shouldn't that stuff be on the parent?
can you show the Obstacle_White_Fence(Clone) components
is there something you're misunderstanding because everything looks correctly
the original prefab had the components on the parent , no Prop_Barrier03
Prop_Barrier03 is just a mesh, and rightfully so doesnt need anything else on it since its just visuals
basically what I'm asking is, what exactly you expect to happen that isn't happening because it all seems to be doing what you set it up to do
I see what you're saying. I think I was expecting to see my prefab's name when I selected it in playmode and not the mesh. My original issue is that the fence does not fall over when I run into it with my player. My player has the following components.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
else if (collision.gameObject.CompareTag("Obstacle"))
{
gameOver = true;
playerAnim.SetBool("Death_b", true);
playerAnim.SetInteger("DeathType_int", 1);
Debug.Log("Game Over!");
}
so is Gameover becoming true and is Debug.Log Game Over printing ?
yes
is it only the prop not tipping over ? where is the code that supposed to make it fall over?
okay so the Event is working, thats one thing you can X off the list
so whats left is this
Only the prop not tipping over. Prop Mass is 20kg and player is 90.7kg. Do I need code to make it fall over if the object is supposed to have rigidbody and a collider?
are you using transforms to move? usually that doesnt yield good results, that mass value are probably pretty high for a prop that supposed to fall over I think..
worse case scenario and Imo a better thing to do is add a slight artificial push with some code
like AddForce
are you actually applying any kind of torque here? If you have a capsule running into a box collider and they're both standing perfectly upright there's no net torque, unless the fence drags on the ground, in which case the friction force would cause a net torque.
I'm not freezing any xyz on the fence but I am freezing the player's x and z position/reotation
oh yeah also friction plays big part here lol
wait you're freezing the player's position?
That means the player isn't actually moving via physics
so it's definitely not going to cause any impact on the fence
it kept falling over after a few jumps so did that lol
thats from rotation
it means the way you're moving your player is completely outside the physics engine
if it can still move after having its position constrined on the rb
I just took off the constraints and still same result where the fence doesn't move
it doesn't matter
because you're still moving the player in whatever same way you were before
which is outside the physics engine
I think I see what you're saying. My player's transform isn't moving at all which is correct so technically there isn't an impact happening right?
Maybe you should explain how your player is moving
so we don't have to play a guessing game
the tutorial just make a moveleft script that's put on objects to make them come at the player
using UnityEngine;
public class moveLeft : MonoBehaviour
{
[SerializeField] float moveLeftSpeed = 30f;
private PlayerController playerControllerScript;
private float leftBound = -15f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>();
}
// Update is called once per frame
void Update()
{
if (playerControllerScript.gameOver == false)
{
transform.Translate(Vector3.left * Time.deltaTime * moveLeftSpeed);
}
if (transform.position.x < leftBound && gameObject.CompareTag("Obstacle"))
{
Destroy(gameObject);
}
}
}
in an ideal situation the transform gets moved by the rigidbody first since thats what simulates the physics rather than other way around
yeah you're moving it directly via the Transform, bypassing the physics engine entirely
you need to move your player via its Rigidbody
transform.Translate same as teleporting , ignoring physics (sometimes it catches up creating an illusion that is working but its not working correctly)
either by setting the velocity directly or by adding forces
Gotcha I think I'm understanding now. If I wanted to fix this I should move the player by it's rigidbody and then always have the obstacles spawn +30 units away on the X or something
one question
im making an retro styled game
is using iEnumators to make animations with meshes
and a foreach loop insted of animating
sure but second part, maybe you should add a range so its not always the same distance to jump ? that could be monotonous and less challenging
bad for performance
why not just use an animator..
you heard that what's better for performance?
Thank you all again. I learned a valuable lesson on physics today 🧠🤯
insted of animating it with the animation window im doing it with IEnumators and meshes bc i want to get that retro style and i dont want the animation to be smooth i want it to be like these stop animations
that doesn't make sense
is it bad for performance???
it does
there's nothing stopping you from having a retro style with the animator
or having a non-smooth animation with the animator
no thats not what i mean
that's what you said
i dont want it to rotate from this position to this i want it to be like not smooth at all
bc i want to get that retro style and i dont want the animation to be smooth i want it to be like these stop animations
I understand that
the causative link between "wanting a retro style" and "using a coroutine" doesn't make sense
i think it would be better that way
What I'm trying to figure out is how you decided that's not possible with the animator
you can have discrete animation with an animationclip just fine
its not like animator has some magic "smoothing frames" going on by default
plenty of people made retro games in unity using animator not sure where you got that assumption lol
ill try it with the animator
no, you just have an incorrect assumption lol
check the dopesheet in the animation window. you can set the animation curves there, you can make animations discrete there by making a tangent constant
looping through a series of frames is what animator is doing anyway and switching sprite on SpriteRenderer
off topic but does anyone here actually like unity courses
im trying to learn unity but half of them are just "BUILD A PLATFORMER" or something really boring
its not offtopic but not a code question #💻┃unity-talk
oh sry
and also..because most of them are introducing you to the basic components you can use to create more complex games
by doing that
yea thats true
might just try to make an original idea
but everytime i do i go to far lol
ofc the idea is so learning the components to then create your own projects with them , your preferred genere etc. but you have to start small..even platformers can get quite complex (see metroidvanias)
thats true im just bored of making platformers
"original ideas" are barely a thing, every idea has been recycled at some point or another, the execution of the idea is what makes something stand out though
true
wait
is it gonna bake animations by doing that
what do you "bake animations"
this
still don't know what you mean there
do you know what baking animations is or are you just using a word you heard
ik what it is
animations aren't automatically baked, otherwise there wouldn't be a whole thing about baking animations
yall, why does it now show a dark body only
you are doing integer division
so you have 0,0,0,0
like im cyling through meshes
and that is animation baking
in the script
notice in my example above I'm using float literals to avoid this @supple flume #💻┃code-beginner message
i have to specify f in the 255?
you just need it on one or the other
the point is to get it to do floating point division
or - again
the best and easiest way here is to define your colors in the inspector
https://www.ghostbin.cloud/cpd40 how come i can only go left and right? any help appreciated!
Do some debugging
Make sure the input is being received correctly for example
Log the movement direction rather than your characters right direction
ok did it movedir.y is changing but move.y isnt
move.y shouldn't
It's the z axis you're setting
oh yea
oh that just helped me ty i realized move is a vector2 so i made it vector3 and it worked
appreciate it
That'll do it
yea lol
Hey all! I'm a bit of a beginner at Unity and I'm trying to detect collisions between the player and the door. Once the player collides with the door, I want it to rotate 90 degrees in the correct direction depending on where the collision is coming from. then after the collision is exited, it should close on its own. However, my script isn't detecting any collisions from what it looks like, since when my player collides with the door, it doesn't move at all. Yet, I can tell it's colliding somehow because the player is not clipping through it. Is this because I'm using the VRChat sdk? Please help :') https://pastebin.com/d9pHfnJF
Howdy! I'm getting to the part in my game where my voice actor is going to start recording. My noob brain originally was going to make an audio source for each line so I can just .play them when I need them but I'm realising that is stupid.
I basically want to have one audiosource object and then the clips of all the voice actor lines attached to it. But how do I then fire that off and tell it which clip to play from another script?
aSource.PlayOneShot(specificAudioClip);
But I would have to then put the audioclip attached to the script im working on?
or aSource.Stop();
aSource.clip = newClip;
aSource.Play();
no, theres many ways to reference something from a script
it doesnt necessarily need to be on the gameobject
Can use Resources to load it or Addressables
How can I load all the 'audioclips/voicelines' into this so I can then fire them off from another script?
you can keep an array of audioclips
and swap em out
a Collection of some sort
I'd need a script on the audiosource object to do that right?
ever heard of a singleton?
If i were to design such a system i would have a list of clip addresses where i configure stuff for an NPC and either randomly pick a clip or via some id (if via an id, id instead configure a list of ids to some audio config entry)
its a static class... u and since theres only "one" you can call it from any script as long as its in the scene
Oh! That looks great to be honest
But then I have to put the clips on each script that sets it off
If that makes sense
public void Play(int index)
{
if (index < 0 || index >= clips.Length || clips[index] == null)
return;
source.PlayOneShot(clips[index]);
}```
AudioManager.Instance.Play(0)
u can keep all the audioclips On the manager if u want
The manager?
Perhaps understand this first before paying someone to do voice work...
it'd be smarter than spreading them around w/ ur scripts in my opinion
He's a friend 🙂
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance;
public AudioClip[] clips;
private AudioSource source;
void Awake()```
Still. its not a hard concept to have 1 component that references the assets and does playing
yea.. either or
if its something small or a SO object. (has its own audio clip for ever object)
u can pass the clip thru the function
or have em on the manager.. really doesnt matter too much
Is this meant to be the "player" saying things as certain major events happen?
you should log the collisions in teh code
with debug logs.. getting information from the collider
then go from there.. (make sure its stable first) then move along to directions and stuff
So now from my other script
I need to somehow fire off 'element 0'
I assume I need to make this a singleton like you said?
i logged them and they do work. it is colliding with the player. it's just not moving the door?
for the door u can use Tweening libraries or animations.. i prefer my scripting.. (i can change values and have it open this way or that way)
u (or I could atleast) just have a trigger volume on either side of the door to tell which direction it should open
hm i'll try that next
well debug thru the next bit... does it call a funciton or event or something?
thats the simple method...
Would it be better to put the play function inside the audio manager itself?
and onec the door opens u can disable certain colliders
I guess it would
so ur not triggering things when ur not supposed to
@high summit I dont think this design will help you as you will have calls to play a clip with an index which isnt reliable. If these clips are for when the player collects something or interacts with something, why not have the clip referenced on that and get it from there to then play? (e.g. pick up fuse, get clip from fuse and play)
ya, thast the point
it does all the logic stuff.. u just tell it what clip.. and maybe volume and pitch
if u wanna be fancy
So i need to put a play function event in here that can be called from another script
stop.. and look up singletons and how they work first
you have just confused them 😆
u need logic in the Awake() to control and make sure theres only that 1 singleton
The awake on me errored, one sec
Joshie ^
holy heck.. arent u in luck
it even has audiomanager as an example
here lemme show you the updated code cause i realized the vrchat sdk has a specific function for player collisions (i changed the collider to trigger so it opens when you get close) https://pastebin.com/TzXpB8pg
ya, im trying to ignore the fact ur using VR skds
i dont work with it.. so no clue if it matters or impacts whats happening here
ye fair
this is my first time too haha
Okay I think im getting somewhere
then u can load in the clips in the inspector
then since its a static u can call it from anywhere
just make sure its on a gameobject or something
Do you understand what static does?
But i need to tell it which clip?
since its named instance u just:
cs AudioManager.Instance.PlaySound(yourClip);
well obviously..
No but my clip is in the array
u can code it do play certain clips..
audioManager.Instance.PlayAPow();
audioManager.Instance.PlayDogBark();
``audioManager.Instance.PlayOOooyeaaa();`
then have functions that already know which clip to play..
but thats extra work. when u want things to be modular
its not modular if you need an index to get a clip
Whats the difference between using the file name or the index really
i use two methods
Urgh I'm a little lost here
Gonna be honest lol
Bit out of my depth
This is why I almost made an audiosource for each voice line 
Then think, how were you going to reference them all?
By putting the audiosource on every object that had the original trigger event on
Then do that with audio clips instead and 1 audio source and bam done
Oh hangon, explain with some detail how you intend these audio clips to be played?
Originally?
is it player enters a physics trigger and a clip is played?
I had it working my way but I realised id have to add a bazillion audiosources for ewach clip
One sec ill show
an audiosource for every voice line
This doesnt mean much to me, how is a fuse collected?
okay and how does the interaction work or get triggered?
great. So why not have the audio clip on the object the raycast hits?
Then we instead get the clip and play it on an audio source your interaction system has a ref to
I just think it makes more sense to have all the voice actors lines/clips attached to it's own audiosource?
vs sending them 'from' objects
no, please read what i said again
easy..
if(fuse2Collected){audiomanager.Instance.PlayClip(fuse2Sound);}
if(fuse1Collected)
{audiomanager.Instance.PlayClip(fuseSound);}``` and so on
🙏 im trying to explain this as simply as i can
objects that can be interacted with can have an audio clip on them and this can be retrieved during the interaction process and played
But what i'm saying is id rather have all the voice lines ready waiting on the audiosource
like this
I see no good reason too
It's just easier to manage I guess
Than having each voice line/clip on every object that triggers one
Its not, how do you know what index the clips have?
I assumed I can just select 'element 0'
If the answer is "i hard code an index" then you just make your life harder later
What if you need to insert a clip elsewhere? remove one? oh shit my indexes are all wrong now!
okay I see what you're saying
BUT if my "fuse 1" gameobject in the scene just has the clip referenced on it already that is easy to update and is intuitive to manage
I am presuming they all share some script or some base class here (which would make this easier)
otherwise you can have a new component you use:
if(hitObject.TryGetComponent(out InteractableAudio comp))
{
audioSource.PlayOneShot(comp.GetAudioClip());
}
thats all ill say for now im tired
okay this isn't firing/I can hear anything
But doesn't seem to show an error
clip is loaded too
Yeah so this doesnt load any clips
use debug logs
dont assume its not firing
i seen that
put a log in there next to it
"audio fired"
"audio supposed to fire"
kk
check "play on awake" just to see if the clip is fine
thats the first thing i do.. (make sure hte audio source is close enough to the listener.. and the clips in there and the volumes high enough to here)
then i go back to the code/logic
Okay so
if (fuse1collected && fusepickup2.fuse2collected && fusepickup3.fuse3collected)
{
AudioManager.Instance.PlaySound(allfusescollected);
Debug.Log("audio suppose to fire");
I get the audio suppose to fire log message
and I can't try play on awake because I'm sending the audioclip to the audiosource in code lol
But it's not making it to the audiosource, as the clip slot stays empty
Also no error when it's suppose to happen
check the clip
why does it not look like the others?
may be a clue
ur naming is actually hella confusing
nah.. they still look different lol
What ya mean?
why does 1 have a speaker and the other has a music note?
put a log in the singleton as well
Oh the pickup sound is just playing on an audiosource
Where as all the fuses is a clip
Pickup sound works fine
Just the clip is being sent to the 'main audiosource'
public void PlaySound(AudioClip clip)
{
source.Play();
Debug.Log("Singleton Fired");
}
i'll try this
Yep I'm getting singleton fired
Okay so..
The singleton is firing only on the one without a valid clip
I didnt give it 'collectedfuse3audio' yet and that one fires the singleton
All fuses collected doesnt
make sure its not spamming play...
u could PlayOneShot(clip)
if u do Play().. u should do Stop() before it
so it doesn't try to play clips on top of clips
yea..
ur logic doesn do anything with it
lol.. 😛
might want to assign the clip to the audiosource if u want to play it...
might be helpful
OH wait
ya..
all ur code does is Play an empty audiosource
this was the hint we needed ^
now you've solved ur problem, created an audiomanager.. and learned and utilized a singleton
good run 👍
now u can build onto it
Beats having about 70 audiosources for all the voicelines lol
ya, thats ridiculous.. lmao
I knew it was, I was so tempted to just do it but I was like Nah I'll do it properly
and if ur audio is 3D u can even move around the audio source as u play it.. 😉
works great 👍 say i open a door.. i can play a creaking sound and use the doors transform to get spatial 3D audio
It's the character speaking in this instance so 2d is perfect
cool cool
fun fact, this would actually work.. and it wouldnt be all that unperformant..
its just really really bad idea lol
programming persuades u to make things reuseable and scaleable.. == work smarter not harder
Yeah honestly, I jumped into too big of a project for my first game and first time touching c# but I'm about 75% done in about 3 weeks with this little game, And I'm pretty proud of where I'm at so far, Learnt alot about cinemachine, The basic stuff, bit of 3d modeling/blender, Sound design, Optimization, Render culling for performance, Cutscenes/Interactions/Raycasting.
The placeholder voicelines are hillarious in this lol.
https://pastebin.com/z74RAvkx DOOR WORKS! working code for those interested yippee. turns out i was just assigning the hingejoint values incorrectly
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
https://www.ghostbin.cloud/soo55 hi this is my first time with multiplayer. i was wondering why the player cant see the bullet come out of the gun? but the host can still see the bullets after the client clicks, the bullets just dont show for the client. any help appreciated, thank you!
Are they spawned on the client?
Networking is an advanced topic and there's a channel specifically for that: #archived-networking
o ok
Hi, I am working on an asset.
It works fine when located in the Assets directory, however, if I add it as a package from git url, it can't find the Easings namespace.
What am I doing wrong?
Here's the asset, there's only 2 scripts:
https://github.com/nnra6864/SmoothSceneCamera
Please @ me and thanks in advance!
Easings seems to be a static class. Not a namespace.
You'll nee to check what assembly is the erroring script part of as well as the Easings script, and whether it's in your project/packages at all.
seems like the Easings class is in the same package. what's likely the issue is that when it is in the Assets folder, the Easings class is being added to the Assembly-CSharp assembly. however that won't happen for packages, you are required to use asmdefs for packages
https://docs.unity3d.com/Manual/cus-asmdef.html
that worked, thanks a ton!
using textmeshpro, is there a way to have it so that each line of text is underlined from one border of the thing all the way to the other border? so like not constrained by the text, rather the underline goes all the way across
this is a coding channel
mb