Using Unity, I’m trying to add GameObjects with a particular script to an array. I’ve tried a bunch of different methods and ultimately I’ve ended up with this, and for the life of me I can’t find why it’s giving me the error, because everything I’ve googled for the last hour has said it’s mostly from syntax and I cannot find the syntax error. I wonder if it wouldn’t just make sense to use a get/set but I really don’t understand how those are different from for loops. Thank you!
public class QuestFinderScript : MonoBehaviour {
GameObject[] objects;
public List<GameObject> interactables = new List<GameObject> ();
int interactablesSize;
void Start(){
interactables = new List<GameObject> ();
objects = GameObject.FindGameObjectsWithTag ("Untagged");
interactablesSize = objects.Length;
for (int i = 0; i < interactablesSize; i++) {
InteractionSettings iset = objects [i].GetComponent<InteractionSettings> ();
if (iset != null) {
interactables.Add [i];
}
}
}
}
asked Feb 23, 2017 at 20:19
4
Thanks to your input, I’ve fixed it — part of the problem was that I didn’t realize the script I was referencing was a child, not a component of the gameobject itself. But if anyone’s curious:
interactables = new List<GameObject> ();
objects = GameObject.FindGameObjectsWithTag ("questable");
interactablesSize = objects.Length;
Debug.Log (interactablesSize);
for (int i = 0; i < interactablesSize; i++) {
InteractionSettings iset = objects [i].GetComponentInChildren<InteractionSettings> ();
if (iset != null) {
interactables.Add(iset.gameObject);
}
}
answered Feb 23, 2017 at 20:40
jannarjannar
511 gold badge1 silver badge4 bronze badges
1st problem: As Pogrammer says, Add is a function for list, not an indexer.
Add(i) is correct
Of course, the error is due to your 1st problem.
2nd problem: Interactables os list of GameObject, you try to add integer(i is integer) to list of GameObjects.
Review your code and understand what you are going to add to Interactables.
answered Feb 23, 2017 at 20:32
EfeEfe
78010 silver badges32 bronze badges
I keep receiving the above error on the following line of code:
<select
id="buildingSlctRoom@{Model.roomNo;}Request@{Model.RequestNo;}"
class="form-control"
onchange="fillRooms(@{Model.roomNo;},@{Model.RequestNo;},$('#buildingsslctRoom@{Model.roomNo;}Request@{Model.RequestNo;}').val())"
style="width:auto;">
I cant see anything that could be causing this from that code?
Any ideas?
Thanks
class containing roomNo and RequestNo
namespace Timetabling06.ModelViews
{
public class roomCheckerObject
{
public string code { get; set; }
public ICollection<room> rooms { get; set; }
public ICollection<room> deptRooms { get; set; }
public ICollection<building> buildings { get; set; }
public int roomNo { get; set; }
public int RequestNo { get; set; }
}
}
Code that sets object variables :
public ActionResult _roomChecker(int roomNum, int requestNum, String user, int roundID, int day, int time, int length,int[] weeks,int students,String roomType,String park, String[] facilities){
var rooms = db.rooms.Include(r=>r.building).Include(r=>r.facilities);
rooms = rooms.Where(r => r.capacity >= students);
if(roomType != "Any"){
rooms = rooms.Where(r=>r.roomType.Equals(roomType));
}
if (park != "Any") {
rooms = rooms.Where(r=>r.building.park.Equals(park));
}
if (facilities != null)
{
for (var i = 0; i < facilities.Length; i++)
{
rooms = rooms.Where(r => r.facilities.Any(f => f.facilityName.Equals(facilities[i])));
}
}
var deptRooms = db.rooms.Include(r => r.building).Include(r => r.facilities).Where(r=>r.belongsTo.Equals(user));
roomCheckerObject suitableRooms = new roomCheckerObject();
suitableRooms.code = user;
suitableRooms.roomNo = roomNum;
suitableRooms.RequestNo = requestNum;
if(rooms.Count() >0){
suitableRooms.rooms = rooms.ToList();
var buildings = rooms.Select(r => r.building).Distinct();
suitableRooms.buildings = buildings.ToList();
}
if(deptRooms.Count() >0){
suitableRooms.deptRooms = deptRooms.ToList();
}
return PartialView(suitableRooms);
}
I keep receiving the above error on the following line of code:
<select
id="buildingSlctRoom@{Model.roomNo;}Request@{Model.RequestNo;}"
class="form-control"
onchange="fillRooms(@{Model.roomNo;},@{Model.RequestNo;},$('#buildingsslctRoom@{Model.roomNo;}Request@{Model.RequestNo;}').val())"
style="width:auto;">
I cant see anything that could be causing this from that code?
Any ideas?
Thanks
class containing roomNo and RequestNo
namespace Timetabling06.ModelViews
{
public class roomCheckerObject
{
public string code { get; set; }
public ICollection<room> rooms { get; set; }
public ICollection<room> deptRooms { get; set; }
public ICollection<building> buildings { get; set; }
public int roomNo { get; set; }
public int RequestNo { get; set; }
}
}
Code that sets object variables :
public ActionResult _roomChecker(int roomNum, int requestNum, String user, int roundID, int day, int time, int length,int[] weeks,int students,String roomType,String park, String[] facilities){
var rooms = db.rooms.Include(r=>r.building).Include(r=>r.facilities);
rooms = rooms.Where(r => r.capacity >= students);
if(roomType != "Any"){
rooms = rooms.Where(r=>r.roomType.Equals(roomType));
}
if (park != "Any") {
rooms = rooms.Where(r=>r.building.park.Equals(park));
}
if (facilities != null)
{
for (var i = 0; i < facilities.Length; i++)
{
rooms = rooms.Where(r => r.facilities.Any(f => f.facilityName.Equals(facilities[i])));
}
}
var deptRooms = db.rooms.Include(r => r.building).Include(r => r.facilities).Where(r=>r.belongsTo.Equals(user));
roomCheckerObject suitableRooms = new roomCheckerObject();
suitableRooms.code = user;
suitableRooms.roomNo = roomNum;
suitableRooms.RequestNo = requestNum;
if(rooms.Count() >0){
suitableRooms.rooms = rooms.ToList();
var buildings = rooms.Select(r => r.building).Distinct();
suitableRooms.buildings = buildings.ToList();
}
if(deptRooms.Count() >0){
suitableRooms.deptRooms = deptRooms.ToList();
}
return PartialView(suitableRooms);
}
Эдис 0 / 0 / 0 Регистрация: 19.06.2019 Сообщений: 14 |
||||
1 |
||||
19.06.2019, 21:47. Показов 4624. Ответов 14 Метки unity (Все метки)
Привет. Вот мой код :
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
19.06.2019, 21:47 |
Ответы с готовыми решениями:
double x = Convert.ToDouble(Console.ReadLine());… Ошибки в проекте Ошибки в проекте Ошибки в проекте 14 |
1max1 3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
||||||||
19.06.2019, 22:38 |
2 |
|||||||
Ты от класса HealthHelper отнимаешь int ><
Необъявленная переменная.
1 |
Эдис 0 / 0 / 0 Регистрация: 19.06.2019 Сообщений: 14 |
||||||||
20.06.2019, 06:22 [ТС] |
3 |
|||||||
Ты от класса HealthHelper отнимаешь int ><
Необъявленная переменная. Но у меня вё же выходят ошибки. У меня стало не получаться с этим кодом, с 21:30 минуты.
0 |
1max1 3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
||||
20.06.2019, 09:18 |
4 |
|||
1 |
Эдис 0 / 0 / 0 Регистрация: 19.06.2019 Сообщений: 14 |
||||
20.06.2019, 16:29 [ТС] |
5 |
|||
И после этого у меня это появилось: мой код:
0 |
2502 / 1515 / 806 Регистрация: 23.02.2019 Сообщений: 3,700 |
|
20.06.2019, 17:10 |
6 |
РешениеПосле Destroy(gameObject) не хватает точки с запятой.
0 |
6270 / 3898 / 1567 Регистрация: 09.05.2015 Сообщений: 9,189 |
|
20.06.2019, 17:20 |
7 |
Кому-то стоило бы сначала изучить C# на базовом уровне, прежде чем лезть в Unity…
0 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
20.06.2019, 18:47 |
8 |
Да промахнулся я немного, писал от руки.
0 |
Эдис 0 / 0 / 0 Регистрация: 19.06.2019 Сообщений: 14 |
||||
20.06.2019, 21:52 [ТС] |
9 |
|||
После Destroy(gameObject) не хватает точки с запятой. И всё? Добавлено через 7 минут Добавлено через 1 час 13 минут Что делать? Вот мой код:
пожалуйста помогите .
0 |
2502 / 1515 / 806 Регистрация: 23.02.2019 Сообщений: 3,700 |
|
20.06.2019, 23:05 |
10 |
Эдис, почему и для чего вы написали эту строку using UnityEngine.GUI;?
1 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
20.06.2019, 23:17 |
11 |
Наверное там должно быть UnityEngine.UI;
1 |
Эдис 0 / 0 / 0 Регистрация: 19.06.2019 Сообщений: 14 |
||||
21.06.2019, 07:37 [ТС] |
12 |
|||
Потому что когда я пишу Text на 7 строчке он не работает — загорается красным. Для этого я на второй строчке написал using UnityEngine.GUI; Добавлено через 4 минуты Я это делал по видео уроку : Только у него старые коды — не работают сейчас поэтому спрашивал. Добавлено через 4 минуты Добавлено через 12 секунд
0 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
21.06.2019, 09:08 |
13 |
Какой же ты невнимательный, кошмар. Добавлено через 1 минуту
0 |
250 / 186 / 68 Регистрация: 04.03.2019 Сообщений: 1,010 |
|
21.06.2019, 09:39 |
14 |
Я это делал по видео уроку уроки то обрезанные. что вы сможете по ним научиться. догадываться что там дальше?
0 |
0 / 0 / 0 Регистрация: 01.07.2022 Сообщений: 2 |
|
01.07.2022, 19:13 |
15 |
помогите мне пожалуйста
0 |
Содержание
- Error cs0201 only assignment
- Answered by:
- Question
- CS0201 В качестве оператора можно использовать только выражения присваивания, вызова, увеличения, уменьшения и нового объекта.
- error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
- 2 Ответов
- Ваш Ответ
- Welcome to Unity Answers
- Подписаться на вопрос
Error cs0201 only assignment
Answered by:
Question
Hello I am very decent at C# programming but this code I am trying to fix for someone blows my mind. I have looked at this code for several days and can not figure out the problem. Any help would be extremely appreciated.
Thank you in advance,
using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Drawing;
using CWIS;
public partial class training_addemployee : Page
<
public string GetConnectionString()
< // get stored connection string
string strConn = ConfigurationManager.ConnectionStrings[«CWIS»].ConnectionString;
return strConn;
>
public void PopulateECC()
<
// clear out drop down list
ddlECC.Items.Clear();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = GetConnectionString();
conn.Open();
string commandString = «SELECT [ECC], [Description] FROM dbo.TR_ECC ORDER BY [ECC] ASC;»;
SqlCommand command = new SqlCommand(commandString, conn);
SqlDataReader reader = command.ExecuteReader();
string strValue;
string strName;
ddlECC.Items.Add(new ListItem(«», «»));
while (reader.Read())
<
strValue = String.Format(«<0>«, reader[0]);
strName = String.Format(«<0>«, reader[1]);
ddlECC.Items.Add(new ListItem(strValue + » — » + strName, strValue));
>
reader.Close();
conn.Close();
>
public void AddNewRec()
< // routine to run sql insert statement
SqlConnection conn = new SqlConnection();
conn.ConnectionString = GetConnectionString();
conn.Open();
string strPersonalCell = txtPersonalCell1.Text + txtPersonalCell2.Text + txtPersonalCell3.Text;
if (strPersonalCell.Length == 0) < strPersonalCell = «0»; >
string strHomePhone = txtHomePhone1.Text + txtHomePhone2.Text + txtHomePhone3.Text;
if (strHomePhone.Length == 0) < strHomePhone = «0»; >
string strWorkCell = txtWorkCell1.Text + txtWorkCell2.Text + txtWorkCell3.Text;
if (strWorkCell.Length == 0) < strWorkCell = «0»; >
string strECHome = txtECHomePhone1.Text + txtECHomePhone2.Text + txtECHomePhone3.Text;
if (strECHome.Length == 0) < strECHome = «0»; >
string strECCell = txtECCellPhone1.Text + txtECCellPhone2.Text + txtECCellPhone3.Text;
if (strECCell.Length == 0) < strECCell = «0»; >
string strECWork = txtECWorkPhone1.Text + txtECWorkPhone2.Text + txtECWorkPhone3.Text;
if (strECWork.Length == 0) < strECWork = «0»; >
string strActive;
if (chkActive.Checked)
<
strActive = «1»;
>
else
<
strActive = «0»;
>
string commandString;
commandString = «INSERT INTO [CW-IS].dbo.TR_Employees ([Employee_ID], [FName], [LName], [Location], [Address], [Personal_Cell], «;
commandString += «[Home_Phone], [Work_Cell], [Hire_Date], [Hire_Date2], [Hire_Date3], [Termination_Date], [Termination_Date2], [Termination_Date3], [Emergency_Name], [Emergency_Relation], «;
commandString += «[Emergency_Home], [Emergency_Cell], [Emergency_Work], [Temp], [Temp_Agency], [Badge_Issued], «;
commandString += «[FT], [Active_Employee]) VALUES («;
commandString = commandString + «‘» + txtEmployeeID.Text.Trim() + «‘, ‘» + txtFName.Text + «‘, ‘» + txtLName.Text + «‘, ‘»;
commandString = commandString + ddlLoc.SelectedValue + «‘, ‘» + txtHomeAddress.Text + «‘, » + strPersonalCell + «, » + strHomePhone + «, » + strWorkCell;
commandString = commandString + «, » + DateSQLFormat(txtHireDate.Text) + «, «; + DateSQLFormat(txtHireDate2.Text) + «, » + DateSQLFormat(txtHireDate3.Text);
commandString = commandString + «, » + DateSQLFormat(txtTerminationDate.Text) +», «; + DateSQLFormat(txtTerminationDate2.Text) + «, » + DateSQLFormat(txtTerminationDate3.Text);
commandString = commandString + «, ‘» + txtECName.Text + «‘, ‘» + txtECRelation.Text + «‘, » + strECHome + «, » + strECCell;
commandString = commandString + strECWork + «, » + ddlTemp.SelectedValue + «, ‘» + txtTempAgency.Text;
commandString = commandString + «‘, » + DateSQLFormat(txtBadgeIssued.Text) + «, » + ddlFIT.SelectedValue + «, » + strActive;
commandString = commandString + «);»;
bool flag = true;
try
<
SqlCommand command = new SqlCommand(commandString, conn);
command.ExecuteNonQuery();
>
catch
< // if query fails to execute due to syntax error
flag = false;
>
// query #2 to add ECCs relationships
string strEmp = txtEmployeeID.Text.Trim();
string strECC = «»;
for (int i = 1; i 0)
<
string commandString2;
SqlCommand command2;
commandString2 = «INSERT INTO [CW-IS].dbo.TR_ECCToEmployees ([Employee_ID], [ECC]) VALUES (‘» + strEmp + «‘, ‘» + strECC + «‘);»;
command2 = new SqlCommand(commandString2, conn);
command2.ExecuteNonQuery();
>
>
// javascript alert box to notify user of query result
string strMSG;
if (flag)
< // query successfully executed
strMSG = «The new employee was successfully added to the database.»;
// reset form
txtEmployeeID.Text = «»;
txtFName.Text = «»;
ddlLoc.ClearSelection();
txtLName.Text = «»;
txtHomeAddress.Text = «»;
txtPersonalCell1.Text = «»;
txtPersonalCell2.Text = «»;
txtPersonalCell3.Text = «»;
txtHomePhone1.Text = «»;
txtHomePhone2.Text = «»;
txtHomePhone3.Text = «»;
txtWorkCell1.Text = «»;
txtWorkCell2.Text = «»;
txtWorkCell3.Text = «»;
txtHireDate.Text = «»;
txtHireDate2.Text = «»;
txtHireDate3.Text = «»;
txtTerminationDate.Text = «»;
txtTerminationDate2.Text = «»;
txtTerminationDate3.Text = «»;
txtECName.Text = «»;
txtECRelation.Text = «»;
txtECHomePhone1.Text = «»;
txtECHomePhone2.Text = «»;
txtECHomePhone3.Text = «»;
txtECCellPhone1.Text = «»;
txtECCellPhone2.Text = «»;
txtECCellPhone3.Text = «»;
txtECWorkPhone1.Text = «»;
txtECWorkPhone2.Text = «»;
txtECWorkPhone3.Text = «»;
ddlTemp.ClearSelection();
txtTempAgency.Text = «»;
txtBadgeIssued.Text = «»;
ddlFIT.ClearSelection();
chkActive.Checked = false;
ddlShift.ClearSelection();
>
else
<
strMSG = «Fail. Unable to add the new employee to the database. Please try again or contact the IT Department for help.»;
>
RegisterStartupScript(«script1», «»);
>
protected void btnCreateNewRec_Click(object sender, EventArgs e)
<
AddNewRec();
>
Источник
CS0201 В качестве оператора можно использовать только выражения присваивания, вызова, увеличения, уменьшения и нового объекта.
Этот код предназначен для игры-кликера.
Есть 2 проблемы, первая находится в строке 19 на instance == this; :
(Error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement)
(Извините, я новичок в программировании)
Ваша функция GetCurrencyIntoString должна быть в конце return converted; . Ваш метод создания экземпляра должен назначаться экземпляру, и вместо этого вы проверяете, равен ли он этому. Меняем на instance = this;
Так стоит ли запоминать номера ошибок наизусть? Пожалуйста, редактировать свой вопрос, чтобы включить одну проблему во все сообщения об ошибках. Опубликуйте вторую проблему как другой вопрос. Один вопрос на сообщение.
Вы неправильно поняли разницу между = — присвоение — и == — сравнением на равенство; распространенная ошибка новичков. Но меня больше беспокоит существование метода CreateInstance в первую очередь. У этого метода странный контракт; вы можете вызывать его только из существующего экземпляра, и он либо возвращает вам сам, либо возвращает результат вызова предыдущий к CreateInstance . Это выглядит как очень и очень неправильная попытка написать синглтон; то есть класс, экземпляр которого можно создать только один раз. Это то, что вы пытаетесь сделать?
Если это то, что вы пытаетесь сделать, не создавайте метод CreateInstance и, конечно же, не делайте его методом экземпляра! Вместо этого вы хотите сделать что-то вроде: public sealed class C < private static C instance = new C(); public static C Instance < get < return instance; >> private C() <> > , и тогда все ваши методы экземпляра не должны ничего делать с instance или Instance . Они просто работают на this .
Могут быть особые вещи, которые вам нужно сделать, чтобы создать синглтон, производный от MonoBehavior; Я не знаю. Вы должны провести небольшое исследование по этому поводу и посмотреть, существует ли шаблон специально для подклассов MonoBehavior.
Наконец, не используйте числа с плавающей запятой или удвоением для валюты. Всегда используйте тип decimal для валюты. Используйте числа с плавающей запятой и двойные числа для физических величин, таких как длина или масса. Используйте десятичные дроби для количеств, которые измеряются с точностью до десятичных знаков, например долларов. (И вместо 1000f используйте 1000m — m для денег.)
Источник
error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
I am new to the creation in C # . I do not know how to solve t$$anonymous$$s problem . Can you help ?
2 Ответов
Ответ от meat5000 · 18/10/15 17:58
A — B means not$$anonymous$$ng as you dont store the result.
C = A — B has a lot more meaning.
You mean to do velocity = new vector.
Or if you were trying to take away from the velocity you mean
velocity = velocity — new vector.
Ответ от JeevanjotSingh · 18/10/15 18:34
Or Simply How meat5000 said
Ваш Ответ
Welcome to Unity Answers
If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.
Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.
Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.
Подписаться на вопрос
Ответы Ответы и комментарии
5 пользователей подписаны.
Источник