hey how can i access this list of int and strings from another
script?
// Slot One Data
[Serializable]
public class SlotOneStats
{
public string nameOne;
public int roleOne;
public int strengthOne;
public int meleeOne;
public int shootingOne;
public int huntingOne;
public int cookingOne;
public int craftingOne;
public int buildingOne;
public int engineeringOne;
}
i tried changing 'public' to 'static' or 'public static' but whenever i changed to static
it will say
Static member `Main.SlotOneStats.ALLTHESTATICVARIABLEGOESHERE' cannot be accessed with an
instance reference, qualify it with a type name instead
BinaryFormatter bfWriter = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/dataStats" + onSlot + ".fgsv");
if(onSlot == 1)
{
SlotOneStats slotoneStats = new SlotOneStats();
slotoneStats.nameOne = name;
slotoneStats.roleOne = role;
slotoneStats.strengthOne = strength;
slotoneStats.meleeOne = melee;
slotoneStats.shootingOne = shooting;
slotoneStats.huntingOne = hunting;
slotoneStats.cookingOne = cooking;
slotoneStats.craftingOne = crafting;
slotoneStats.buildingOne = building;
slotoneStats.engineeringOne = engineering;
bfWriter.Serialize(file, slotoneStats);
}
I would suggest adding a public instance of the class to the first script:
public class SlotOneStats
{
public string nameOne;
public int roleOne;
public int strengthOne;
public int meleeOne;
public int shootingOne;
public int huntingOne;
public int cookingOne;
public int craftingOne;
public int buildingOne;
public int engineeringOne;
}
public SlotOneStats SOS;
Now just access the public varaible SOS and it should work:
GameObject example = GameObject.Find("Object_with_script").GetComponent<Script_with_class>.SOS;
// do stuff with example
Related
use 2019.1.8f1 ver
I've been referring to a lot of information, but an unknown error bothers me.
Error
SerializationException: Type 'UnityEngine.GameObject' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
[System.Serializable]
public class Map
{
public Node[,] nodes;
}
[System.Serializable]
public class Node
{
public GameObject tile;
public bool walkable;
public Vector3 worldPosition;
public int gridX;
public int gridY;
public int gCost;
public int hCost;
public int FCost { get { return gCost + hCost; } }
public Node(bool _walkable, Vector3 _worldPosition, int _gridX, int _gridY)
{
walkable = _walkable;
worldPosition = _worldPosition;
gridX = _gridX;
gridY = _gridY;
}
}
[System.Serializable]
public class Grid : MonoBehaviour
{
public Node[,] grid;
public void SaveMapData()
{
Debug.Log("Save");
FileStream stream = File.Create(Application.persistentDataPath + path);
BinaryFormatter bf = new BinaryFormatter();
Map map = new Map();
map.nodes = grid.grid;
bf.Serialize(stream, map);
stream.Close();
}
Your Node class references the GameObject class here:
public GameObject tile;
The best solution would be to get rid of that reference. This would also improve the decoupling of your model from the view.
Or try the [NonSerialized] attribute as a quick fix:
[NonSerialized] public GameObject tile;
I have a below code in which I'm reading a file in string format, then converting it into class format then converting it to BeamRecord and at the end converting back it to string format and writing the output in google storage.
DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
options.setProject("beta-194409");
options.setStagingLocation("gs://clrtegbucket/staging");
options.setRunner(DataflowRunner.class);
DataflowRunner.fromOptions(options);
Pipeline p = Pipeline.create(options);
PCollection<String> weekly = p.apply(TextIO.read().from("gs://gcp/input/WeeklyDueto.csv"));
PCollection<ClassWeeklyDueto> pojos = weekly.apply(ParDo.of(new DoFn<String, ClassWeeklyDueto>() { // converting String into class
// typ
private static final long serialVersionUID = 1L;
#ProcessElement
public void processElement(ProcessContext c) {
String[] strArr = c.element().split(",");
ClassWeeklyDueto clr = new ClassWeeklyDueto();
clr.setCatLib(strArr[1]);
clr.setCausalValue(strArr[7]);
clr.setDuetoValue(strArr[5]);
clr.setModelIteration(strArr[8]);
clr.setOutlet(strArr[0]);
clr.setPrimaryCausalKey(strArr[6]);
clr.setProdKey(strArr[2]);
clr.setPublished(strArr[9]);
clr.setSalesComponent(strArr[4]);
clr.setWeek(strArr[3]);
global_Weekly.add(clr);
c.output(clr);
}
}));
BeamRecordSqlType appType = BeamRecordSqlType.create(
Arrays.asList("Outlet", "CatLib", "ProdKey", "Week", "SalesComponent", "DuetoValue","PrimaryCausalKey", "CausalValue", "ModelIteration", "Published"),
Arrays.asList(Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.FLOAT, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR));
PCollection<BeamRecord> apps = pojos.apply(ParDo.of(new DoFn<ClassWeeklyDueto, BeamRecord>() {
private static final long serialVersionUID = 1L;
#ProcessElement
public void processElement(ProcessContext c) {
BeamRecord br = new BeamRecord(appType, {
BeamRecord br = new BeamRecord(appType, c.element().Outlet, c.element().CatLib, c.element().ProdKey,
c.element().Week, c.element().SalesComponent, c.element().DuetoValue,
c.element().PrimaryCausalKey, c.element().CausalValue, c.element().ModelIteration,
c.element().Published);
c.output(br); }
})).setCoder(appType.getRecordCoder());
PCollection<String> gs_output_final = apps.apply(ParDo.of(new DoFn<BeamRecord, String>() {
private static final long serialVersionUID = 1L;
#ProcessElement
public void processElement(ProcessContext c) {
c.output(c.element().toString());
System.out.println(c.element().toString());
}
}));
gs_output_final.apply(TextIO.write().to("gs://gcp/output/Q"));
I have created class ClassWeeklyDueto below :
package com.pojo;
import java.io.Serializable;
public class ClassWeeklyDueto implements Serializable {
private static final long serialVersionUID = 1L;
public String Outlet;
public String CatLib;
public String ProdKey;
public String Week;
public String SalesComponent;
public float DuetoValue;
public String PrimaryCausalKey;
public String CausalValue;
public String ModelIteration;
public String Published;
public String getOutlet() {
return Outlet;
}
public void setOutlet(String outlet) {
Outlet = outlet;
}
public String getCatLib() {
return CatLib;
}
public void setCatLib(String catLib) {
CatLib = catLib;
}
public String getProdKey() {
return ProdKey;
}
public void setProdKey(String prodKey) {
ProdKey = prodKey;
}
public String getWeek() {
return Week;
}
public void setWeek(String week) {
Week = week;
}
public String getSalesComponent() {
return SalesComponent;
}
public void setSalesComponent(String salesComponent) {
SalesComponent = salesComponent;
}
public float getDuetoValue() {
return DuetoValue;
}
public void setDuetoValue(float duetoValue) {
DuetoValue = duetoValue;
}
public String getPrimaryCausalKey() {
return PrimaryCausalKey;
}
public void setPrimaryCausalKey(String primaryCausalKey) {
PrimaryCausalKey = primaryCausalKey;
}
public String getCausalValue() {
return CausalValue;
}
public void setCausalValue(String causalValue) {
CausalValue = causalValue;
}
public String getModelIteration() {
return ModelIteration;
}
public void setModelIteration(String modelIteration) {
ModelIteration = modelIteration;
}
public String getPublished() {
return Published;
}
public void setPublished(String published) {
Published = published;
}
public float setDuetoValue(String string) {
// TODO Auto-generated method stub
float f = Float.valueOf(string.trim()).floatValue();
return f;
}
}
The DueToValue field is declared float type, Only the field declared as varchar is getting parsed rest none of the datatypes are getting parsed.
So how shall I parse field declared as Int or float or even Date ?
When you manually split a string line from CSV, you get an array of strings. Then you have to manually parse the values from strings. Java doesn't handle it automatically.
In your case to handle floats you need to change clr.setDueToValue(strArr[5]) to clr.setDueToValue(Float.parseFloat(strArr[5])), see the doc.
Similarly you can use Integer.parseInt() to parse integers.
For parsing dates you will likely need to use a SimpleDateFormat.
So I run the following program and my cmd prompt gives me an error saying that the getDescriptions() method is not found in the DataElements class. I'm sure there's a simple solution but I'm just stuck. Here's the DataElements class:
import java.io.*;
public class DataElements
{
File file;
private int columns;
private int row;
private int length;
private String name;
private String type;
private int position;
private String[] descriptions;
public File getFile(){
return file;
}
public void setFile(File f){
file = f;
}
public int getColumns(){
return columns;
}
public void setColumns(int c){
columns = c;
}
public int getRow(){
return row;
}
public void setRow(int r){
row = r;
}
public int getLength(){
return length;
}
public void setLength(int l){
length = l;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public String getType(){
return type;
}
public void setType(String t){
type = t;
}
public int getPosition(){
return position;
}
public void setPosition(int p){
position = p;
}
public String[] getDescriptions(){
return description;
}
public void setDescriptions(String[] d){
description = d;
}
}
And here's the main method. If you need the CMSReader class let me know, but the problem seems to be stuck in these two classes
import java.util.Scanner;
import java.io.*;
public class Project2{
public static void main(String[] args) throws FileNotFoundException{
Scanner keyboard = new Scanner(System.in);
boolean fileParsed = false;
String inFile;
String outFile;
if(args.length != 1){
System.out.println("Error. Enter one argument: the file that needs to be parsed.");
System.exit(0);
}
Scanner scan = new Scanner(new File(args[0]));
DataElements storage = new DataElements();
CMSReader reader = new CMSReader(scan,storage);
reader.scanTopData();
System.out.println("Input File - " + storage.getName());
System.out.println("Output File - ");//*************Look at this*********************
System.out.println("Number of Variables - " + storage.getColumns());
System.out.println("Number of Records - " + storage.getRow());
System.out.println("Record Length - " + storage.getLength());
System.out.println("Variable information:");
reader.scanVariableData();
String[] variableData = storage.getDescriptions();
for(int i = 0; i < variableData.length ; i++){
System.out.println(variableData[i]);
}
}
}
I appreciate any help. Like I said, I'm sure it's something dumb but I've been looking at this for too long.
The variable description is not declared in your DataElements class, which is why DataElements file cannot compile, and my guess is that you have an older compiled version (.class file) of DataElements which does not contain that method.
Recommendation:
Start working with a good IDE (IntelliJ is my personal favorite, but Eclipse and Netbeans are also good options). A good IDE, on top of all other goodies it provides, will highlight such issues in a way you won't miss.
As a part of my project I am learning how to handle the printers using "winspool.drv" and "PRINTUI.DLL,PrintUIEntry" to which I am new. I am using powershell for this project. The problem is that my code is throwing an error when I am trying to get printer Handle with openprinter method
Error: Method invocation failed because [OpenPrinter1.Program1] does not contain a method named 'OpenPrinterHandle'.
Code:
$code = #'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace OpenPrinter1
{
public class Program1
{
[DllImport("winspool.drv", EntryPoint = "OpenPrinter", SetLastError =true)]
internal static extern bool OpenPrinter(string pPrinterName, ref IntPtr phPrinter, PRINTER_DEFAULTS pDefault);
[DllImport("winspool.drv", EntryPoint = "ClosePrinter", SetLastError = true)]
internal static extern int ClosePrinter(IntPtr hPrinter);
[StructLayout(LayoutKind.Sequential)]
public class PRINTER_DEFAULTS
{
public string pDatatype;
public IntPtr pDevMode;
public int DesiredAccess;
}
public struct OpenPrinterAccessCodes
{
public const int DELETE = 0x10000; // DELETE - Allowed to delete printers
public const int READ_CONTROL = 0x20000; // READ_CONTROL -
public const int WRITE_DAC = 0x40000; // WRITE_DAC -
public const int WRITE_OWNER = 0x80000; // WRITE_OWNER -
public const int SERVER_ACCESS_ADMINISTER = 0x1;
public const int SERVER_ACCESS_ENUMERATE = 0x2;
public const int PRINTER_ACCESS_ADMINISTER = 0x4;
public const int PRINTER_ACCESS_USE = 0x8;
public const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
public const int PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE);
public const int SERVER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVER_ACCESS_ADMINISTER | SERVER_ACCESS_ENUMERATE);
public const int MAX_PORTNAME_LEN = 64;
public const int MAX_NETWORKNAME_LEN = 49;
public const int MAX_SNMP_COMMUNITY_STR_LEN = 33;
public const int MAX_QUEUENAME_LEN = 33;
public const int MAX_IPADDR_STR_LEN = 16;
public const int ERROR_INSUFFICIENT_BUFFER = 122;
public const int ERROR_INVALID_FLAGS = 1004;
}
public IntPtr OpenPrinterHandle(string printerName)
{
var def = new PRINTER_DEFAULTS { pDatatype = null, pDevMode = IntPtr.Zero, DesiredAccess = OpenPrinterAccessCodes.PRINTER_ALL_ACCESS };
var hPrinter = IntPtr.Zero;
if (!OpenPrinter(printerName, ref hPrinter, def))
{
var lastWin32Error = new Win32Exception(Marshal.GetLastWin32Error());
throw lastWin32Error;
}
return hPrinter;
}
}
}
'#
cls
Add-Type -TypeDefinition $code -Language CSharp
if(!([OpenPrinter1.Program1]:: OpenPrinterHandle("hp LaserJet 1320 PCL 6 (Copy 1)")))
{
throw (New-Object componentmodel.win32Exception )
}
This syntax:
[Namespace.Class]::Method()
denotes invocation of a static method. The OpenPrinterHandle() method in your type definition is an instance method.
To change the behavior, just introduce the static keyword in the method signature:
public static IntPtr OpenPrinterHandle(string printerName)
and then you should be able to do:
[OpenPrinter1.Program1]::OpenPrinterHandle($printername)
public class TaxReturn {
private double rate1= 0.10;
private double rate2=0.25;
private double single_limit = 32000;
private double married_limit = 64000;
private double income;
private int status;
public static int married=2;
public static int single=1;
public TaxReturn(double inc, int stat){
double income = inc;
int status=stat;
}
public double getTaxi(){
double tax1=0;
double tax2=0;
if(status==single){
if(income<=single_limit)
tax1=rate1*income;
else{
tax1=rate1*single_limit;
tax2=rate2*(income-single_limit);
}
}
else{
if(income<=married_limit)
tax1=rate1*income;
else
tax1=rate1*married_limit;
tax2=rate2*(income-married_limit);
}
return tax1+tax2;
}
}
import java.util.Scanner;
public class TaxCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("eneter income; avoid commas");
double income = sc.nextDouble();
System.out.println("are you married; type Y or N");
String status=sc.next();
int statuss;
if (status.equalsIgnoreCase("y"))
statuss=TaxReturn.married;
else
statuss=TaxReturn.single;
TaxReturn tr = new TaxReturn(income, statuss);
System.out.println("your tax is: " + tr.getTaxi());
}
}
I keep getting-16000 for the answer.I dont know if my code is wrong or something wrong with the software. This code was copied from the book. Iva had this problem with other codes too. Any help would be appreciated. Thanks
Your constructor is not correct.
Rewrite it as follow
public TaxReturn(double inc, int stat){
income = inc;
status = stat;
}
By declaring type on income and status variables, you made them local to the constructor.